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_meta.h> /* vlc_meta_t, vlc_meta_ */
38 #include <vlc_input.h>
42 #include "id3genres.h" /* for ATOM_gnre */
44 /*****************************************************************************
46 *****************************************************************************/
47 static int Open ( vlc_object_t * );
48 static void Close( vlc_object_t * );
51 set_category( CAT_INPUT )
52 set_subcategory( SUBCAT_INPUT_DEMUX )
53 set_description( N_("MP4 stream demuxer") )
54 set_shortname( N_("MP4") )
55 set_capability( "demux", 240 )
56 set_callbacks( Open, Close )
59 /*****************************************************************************
61 *****************************************************************************/
62 static int Demux ( demux_t * );
63 static int DemuxRef( demux_t *p_demux ){ (void)p_demux; return 0;}
64 static int DemuxFrg( demux_t * );
65 static int DemuxAsLeaf( demux_t * );
66 static int Seek ( demux_t *, mtime_t );
67 static int Control ( demux_t *, int, va_list );
71 MP4_Box_t *p_root; /* container for the whole file */
75 uint64_t i_overall_duration; /* Full duration, including all fragments */
76 uint64_t i_time; /* time position of the presentation
77 * in movie timescale */
78 uint32_t i_timescale; /* movie time scale */
79 uint64_t i_duration; /* movie duration */
80 unsigned int i_tracks; /* number of tracks */
81 mp4_track_t *track; /* array of track */
82 float f_fps; /* number of frame per seconds */
84 bool b_fragmented; /* fMP4 */
88 bool b_smooth; /* Is it Smooth Streaming? */
91 bool b_fragments_probed;
92 mp4_fragment_t moovfragment; /* moov */
93 mp4_fragment_t *p_fragments; /* known fragments (moof following moov) */
97 mp4_fragment_t *p_fragment;
98 uint32_t i_current_box_type;
99 uint32_t i_mdatbytesleft;
103 MP4_Box_t *p_tref_chap;
106 input_title_t *p_title;
109 #define BOXDATA(type) type->data.type
111 /*****************************************************************************
112 * Declaration of local function
113 *****************************************************************************/
114 static void MP4_TrackCreate ( demux_t *, mp4_track_t *, MP4_Box_t *, bool b_force_enable );
115 static int MP4_frg_TrackCreate( demux_t *, mp4_track_t *, MP4_Box_t *);
116 static void MP4_TrackDestroy( mp4_track_t * );
118 static block_t * MP4_Block_Read( demux_t *, const mp4_track_t *, int );
119 static void MP4_Block_Send( demux_t *, mp4_track_t *, block_t * );
121 static int MP4_TrackSelect ( demux_t *, mp4_track_t *, mtime_t );
122 static void MP4_TrackUnselect(demux_t *, mp4_track_t * );
124 static int MP4_TrackSeek ( demux_t *, mp4_track_t *, mtime_t );
126 static uint64_t MP4_TrackGetPos ( mp4_track_t * );
127 static uint32_t MP4_TrackGetReadSize( mp4_track_t *, uint32_t * );
128 static int MP4_TrackNextSample( demux_t *, mp4_track_t *, uint32_t );
129 static void MP4_TrackSetELST( demux_t *, mp4_track_t *, int64_t );
131 static void MP4_UpdateSeekpoint( demux_t * );
133 static MP4_Box_t * MP4_GetTrexByTrackID( MP4_Box_t *p_moov, const uint32_t i_id );
135 static bool AddFragment( demux_t *p_demux, MP4_Box_t *p_moox );
136 static int ProbeFragments( demux_t *p_demux, bool b_force );
137 static int ProbeIndex( demux_t *p_demux );
138 static mp4_fragment_t *GetFragmentByPos( demux_t *p_demux, uint64_t i_pos, bool b_exact );
139 static mp4_fragment_t *GetFragmentByTime( demux_t *p_demux, const mtime_t i_time );
141 static int LeafIndexGetMoofPosByTime( demux_t *p_demux, const mtime_t i_target_time,
142 uint64_t *pi_pos, mtime_t *pi_mooftime );
143 static mtime_t LeafGetFragmentTimeOffset( demux_t *p_demux, mp4_fragment_t * );
144 static int LeafGetTrackAndChunkByMOOVPos( demux_t *p_demux, uint64_t *pi_pos,
145 mp4_track_t **pp_tk, unsigned int *pi_chunk );
146 static int LeafMapTrafTrunContextes( demux_t *p_demux, MP4_Box_t *p_moof );
150 static uint32_t stream_ReadU32( stream_t *s, void *p_read, uint32_t i_toread )
152 uint32_t i_return = 0;
153 if ( i_toread > INT32_MAX )
155 i_return = stream_Read( s, p_read, INT32_MAX );
156 if ( i_return < INT32_MAX )
159 i_toread -= INT32_MAX;
161 i_return += stream_Read( s, (uint8_t *)p_read + i_return, (int32_t) i_toread );
165 static bool MP4_stream_Tell( stream_t *s, uint64_t *pi_pos )
167 int64_t i_pos = stream_Tell( s );
172 *pi_pos = (uint64_t) i_pos;
177 static MP4_Box_t * MP4_GetTrexByTrackID( MP4_Box_t *p_moov, const uint32_t i_id )
179 MP4_Box_t *p_trex = MP4_BoxGet( p_moov, "mvex/trex" );
182 if ( p_trex->i_type == ATOM_trex &&
183 BOXDATA(p_trex) && BOXDATA(p_trex)->i_track_ID == i_id )
186 p_trex = p_trex->p_next;
191 static MP4_Box_t * MP4_GetTrakByTrackID( MP4_Box_t *p_moov, const uint32_t i_id )
193 MP4_Box_t *p_trak = MP4_BoxGet( p_moov, "trak" );
197 if( p_trak->i_type == ATOM_trak &&
198 (p_tkhd = MP4_BoxGet( p_trak, "tkhd" )) && BOXDATA(p_tkhd) &&
199 BOXDATA(p_tkhd)->i_track_ID == i_id )
202 p_trak = p_trak->p_next;
207 /* Return time in microsecond of a track */
208 static inline int64_t MP4_TrackGetDTS( demux_t *p_demux, mp4_track_t *p_track )
210 demux_sys_t *p_sys = p_demux->p_sys;
212 if( p_sys->b_fragmented )
213 chunk = *p_track->cchunk;
215 chunk = p_track->chunk[p_track->i_chunk];
217 unsigned int i_index = 0;
218 unsigned int i_sample = p_track->i_sample - chunk.i_sample_first;
219 int64_t i_dts = chunk.i_first_dts;
221 while( i_sample > 0 )
223 if( i_sample > chunk.p_sample_count_dts[i_index] )
225 i_dts += chunk.p_sample_count_dts[i_index] *
226 chunk.p_sample_delta_dts[i_index];
227 i_sample -= chunk.p_sample_count_dts[i_index];
232 i_dts += i_sample * chunk.p_sample_delta_dts[i_index];
237 /* now handle elst */
238 if( p_track->p_elst )
240 demux_sys_t *p_sys = p_demux->p_sys;
241 MP4_Box_data_elst_t *elst = p_track->BOXDATA(p_elst);
243 /* convert to offset */
244 if( ( elst->i_media_rate_integer[p_track->i_elst] > 0 ||
245 elst->i_media_rate_fraction[p_track->i_elst] > 0 ) &&
246 elst->i_media_time[p_track->i_elst] > 0 )
248 i_dts -= elst->i_media_time[p_track->i_elst];
251 /* add i_elst_time */
252 i_dts += p_track->i_elst_time * p_track->i_timescale /
255 if( i_dts < 0 ) i_dts = 0;
258 return CLOCK_FREQ * i_dts / p_track->i_timescale;
261 static inline int64_t MP4_TrackGetPTSDelta( demux_t *p_demux, mp4_track_t *p_track )
263 demux_sys_t *p_sys = p_demux->p_sys;
265 if( p_sys->b_fragmented )
266 ck = p_track->cchunk;
268 ck = &p_track->chunk[p_track->i_chunk];
270 unsigned int i_index = 0;
271 unsigned int i_sample = p_track->i_sample - ck->i_sample_first;
273 if( ck->p_sample_count_pts == NULL || ck->p_sample_offset_pts == NULL )
276 for( i_index = 0;; i_index++ )
278 if( i_sample < ck->p_sample_count_pts[i_index] )
279 return ck->p_sample_offset_pts[i_index] * CLOCK_FREQ /
280 (int64_t)p_track->i_timescale;
282 i_sample -= ck->p_sample_count_pts[i_index];
286 static inline int64_t MP4_GetMoviePTS(demux_sys_t *p_sys )
288 return CLOCK_FREQ * p_sys->i_time / p_sys->i_timescale;
291 static void LoadChapter( demux_t *p_demux );
293 static int LoadInitFrag( demux_t *p_demux )
295 demux_sys_t *p_sys = p_demux->p_sys;
297 if( p_sys->b_smooth ) /* Smooth Streaming */
299 if( ( p_sys->p_root = MP4_BoxGetSmooBox( p_demux->s ) ) == NULL )
301 goto LoadInitFragError;
305 MP4_Box_t *p_smoo = MP4_BoxGet( p_sys->p_root, "uuid" );
306 if( !p_smoo || CmpUUID( &p_smoo->i_uuid, &SmooBoxUUID ) )
307 goto LoadInitFragError;
308 /* Get number of tracks */
310 for( int i = 0; i < 3; i++ )
312 MP4_Box_t *p_stra = MP4_BoxGet( p_smoo, "uuid[%d]", i );
313 if( p_stra && BOXDATA(p_stra) && BOXDATA(p_stra)->i_track_ID )
315 /* Get timescale and duration of the video track; */
316 if( p_sys->i_timescale == 0 )
318 if ( p_stra && BOXDATA(p_stra) )
320 p_sys->i_timescale = BOXDATA(p_stra)->i_timescale;
321 p_sys->i_duration = BOXDATA(p_stra)->i_duration;
322 p_sys->i_overall_duration = BOXDATA(p_stra)->i_duration;
324 if( p_sys->i_timescale == 0 )
326 msg_Err( p_demux, "bad timescale" );
327 goto LoadInitFragError;
335 /* Load all boxes ( except raw data ) */
336 if( ( p_sys->p_root = MP4_BoxGetRoot( p_demux->s ) ) == NULL )
338 goto LoadInitFragError;
344 msg_Warn( p_demux, "MP4 plugin discarded (not a valid initialization chunk)" );
348 static int InitTracks( demux_t *p_demux )
350 demux_sys_t *p_sys = p_demux->p_sys;
352 p_sys->track = calloc( p_sys->i_tracks, sizeof( mp4_track_t ) );
353 if( p_sys->track == NULL )
356 if( p_sys->b_fragmented )
358 mp4_track_t *p_track;
359 for( uint16_t i = 0; i < p_sys->i_tracks; i++ )
361 p_track = &p_sys->track[i];
362 p_track->cchunk = calloc( 1, sizeof( mp4_chunk_t ) );
363 if( unlikely( !p_track->cchunk ) )
365 free( p_sys->track );
373 static void CreateTracksFromSmooBox( demux_t *p_demux )
375 demux_sys_t *p_sys = p_demux->p_sys;
377 MP4_Box_t *p_smoo = MP4_BoxGet( p_sys->p_root, "uuid" );
378 mp4_track_t *p_track;
380 for( int i = 0; i < 3; i++ )
382 MP4_Box_t *p_stra = MP4_BoxGet( p_smoo, "uuid[%d]", i );
383 if( !p_stra || !BOXDATA(p_stra) || BOXDATA(p_stra)->i_track_ID == 0 )
387 p_track = &p_sys->track[j]; j++;
388 MP4_frg_TrackCreate( p_demux, p_track, p_stra );
389 p_track->p_es = es_out_Add( p_demux->out, &p_track->fmt );
394 static block_t * MP4_EIA608_Convert( block_t * p_block )
396 /* Rebuild codec data from encap */
398 size_t i_remaining = p_block->i_buffer;
399 uint32_t i_bytes = 0;
402 if ( i_remaining < 10 ||
403 !(i_bytes = GetDWBE(p_block->p_buffer)) ||
404 (i_bytes + 8 > i_remaining) ||
405 memcmp("cdat", &p_block->p_buffer[4], 4) ||
406 !(p_newblock = block_Alloc( i_remaining * 3 - 8 )) )
408 p_block->i_buffer = 0;
412 uint8_t *p_write = p_newblock->p_buffer;
413 uint8_t *p_read = &p_block->p_buffer[8];
419 p_write[i_copied++] = 0; /* cc1 == field 0 */
420 p_write[i_copied++] = p_read[0];
421 p_write[i_copied++] = p_read[1];
425 } while( i_bytes >= 2 );
427 if ( i_remaining >= 10 &&
428 (i_bytes = GetDWBE(p_read)) &&
429 (i_bytes + 8 <= i_remaining) &&
430 !memcmp("cdt2", &p_read[4], 4) )
437 p_write[i_copied++] = 0; /* cc1 == field 0 */
438 p_write[i_copied++] = p_read[0];
439 p_write[i_copied++] = p_read[1];
442 } while( i_bytes >= 2 );
445 block_Release( p_block );
446 p_newblock->i_buffer = i_copied;
450 static block_t * MP4_Block_Read( demux_t *p_demux, const mp4_track_t *p_track, int i_size )
452 block_t *p_block = stream_Block( p_demux->s, i_size );
456 /* might have some encap */
457 if( p_track->fmt.i_cat == SPU_ES )
459 switch( p_track->fmt.i_codec )
465 case VLC_CODEC_EIA608_1:
466 p_block = MP4_EIA608_Convert( p_block );
469 p_block->i_buffer = 0;
477 static void MP4_Block_Send( demux_t *p_demux, mp4_track_t *p_track, block_t *p_block )
479 if ( p_track->b_chans_reorder && aout_BitsPerSample( p_track->fmt.i_codec ) )
481 aout_ChannelReorder( p_block->p_buffer, p_block->i_buffer,
482 p_track->fmt.audio.i_channels,
483 p_track->rgi_chans_reordering,
484 p_track->fmt.i_codec );
486 es_out_Send( p_demux->out, p_track->p_es, p_block );
489 /*****************************************************************************
490 * Open: check file and initializes MP4 structures
491 *****************************************************************************/
492 static int Open( vlc_object_t * p_this )
494 demux_t *p_demux = (demux_t *)p_this;
497 const uint8_t *p_peek;
507 /* A little test to see if it could be a mp4 */
508 if( stream_Peek( p_demux->s, &p_peek, 11 ) < 11 ) return VLC_EGENERIC;
510 switch( VLC_FOURCC( p_peek[4], p_peek[5], p_peek[6], p_peek[7] ) )
521 case VLC_FOURCC( 'p', 'n', 'o', 't' ):
524 /* We don't yet support f4v, but avformat does. */
525 if( p_peek[8] == 'f' && p_peek[9] == '4' && p_peek[10] == 'v' )
532 /* create our structure that will contains all data */
533 p_sys = calloc( 1, sizeof( demux_sys_t ) );
538 stream_Control( p_demux->s, STREAM_CAN_SEEK, &p_sys->b_seekable );
539 if( !p_sys->b_seekable )
541 msg_Warn( p_demux, "MP4 plugin discarded (not seekable)" );
545 stream_Control( p_demux->s, STREAM_CAN_FASTSEEK, &p_sys->b_fastseekable );
546 p_sys->b_seekmode = p_sys->b_fastseekable;
548 /*Set exported functions */
549 p_demux->pf_demux = Demux;
550 p_demux->pf_control = Control;
552 p_demux->p_sys = p_sys;
554 if( stream_Peek( p_demux->s, &p_peek, 24 ) < 24 ) return VLC_EGENERIC;
555 if( !CmpUUID( (UUID_t *)(p_peek + 8), &SmooBoxUUID ) )
557 p_sys->b_smooth = true;
558 p_sys->b_fragmented = true;
561 if( LoadInitFrag( p_demux ) != VLC_SUCCESS )
564 if( MP4_BoxCount( p_sys->p_root, "/moov/mvex" ) > 0 )
566 if ( p_sys->b_seekable )
568 /* Probe remaining to check if there's really fragments
569 or if that file is just ready to append fragments */
570 ProbeFragments( p_demux, false );
571 p_sys->b_fragmented = !!MP4_BoxCount( p_sys->p_root, "/moof" );
574 p_sys->b_fragmented = true;
576 if ( p_sys->b_fragmented && !p_sys->i_overall_duration )
577 ProbeFragments( p_demux, true );
580 if ( !p_sys->moovfragment.p_moox )
581 AddFragment( p_demux, MP4_BoxGet( p_sys->p_root, "/moov" ) );
583 /* we always need a moov entry, but smooth has a workaround */
584 if ( !p_sys->moovfragment.p_moox && !p_sys->b_smooth )
587 if ( p_sys->b_smooth )
589 p_demux->pf_demux = DemuxFrg;
591 else if( p_sys->b_fragmented )
593 p_demux->pf_demux = DemuxAsLeaf;
596 if( p_sys->b_smooth )
598 if( InitTracks( p_demux ) != VLC_SUCCESS )
600 CreateTracksFromSmooBox( p_demux );
604 MP4_BoxDumpStructure( p_demux->s, p_sys->p_root );
606 if( ( p_ftyp = MP4_BoxGet( p_sys->p_root, "/ftyp" ) ) )
608 switch( BOXDATA(p_ftyp)->i_major_brand )
612 "ISO Media file (isom) version %d.",
613 BOXDATA(p_ftyp)->i_minor_version );
616 case( VLC_FOURCC( '3', 'g', 'p', '5' ) ):
617 case( VLC_FOURCC( '3', 'g', 'p', '6' ) ):
618 case( VLC_FOURCC( '3', 'g', 'p', '7' ) ):
619 msg_Dbg( p_demux, "3GPP Media file Release: %c",
620 #ifdef WORDS_BIGENDIAN
621 BOXDATA(p_ftyp)->i_major_brand
623 BOXDATA(p_ftyp)->i_major_brand >> 24
627 case( VLC_FOURCC( 'q', 't', ' ', ' ') ):
628 msg_Dbg( p_demux, "Apple QuickTime file" );
630 case( VLC_FOURCC( 'i', 's', 'm', 'l') ):
631 msg_Dbg( p_demux, "PIFF (= isml = fMP4) file" );
635 "unrecognized major file specification (%4.4s).",
636 (char*)&BOXDATA(p_ftyp)->i_major_brand );
642 msg_Dbg( p_demux, "file type box missing (assuming ISO Media file)" );
645 /* the file need to have one moov box */
646 p_sys->moovfragment.p_moox = MP4_BoxGet( p_sys->p_root, "/moov", 0 );
647 if( !p_sys->moovfragment.p_moox )
649 MP4_Box_t *p_foov = MP4_BoxGet( p_sys->p_root, "/foov" );
653 msg_Err( p_demux, "MP4 plugin discarded (no moov,foov,moof box)" );
656 /* we have a free box as a moov, rename it */
657 p_foov->i_type = ATOM_moov;
658 p_sys->moovfragment.p_moox = p_foov;
661 if( ( p_rmra = MP4_BoxGet( p_sys->p_root, "/moov/rmra" ) ) )
663 int i_count = MP4_BoxCount( p_rmra, "rmda" );
666 msg_Dbg( p_demux, "detected playlist mov file (%d ref)", i_count );
668 input_thread_t *p_input = demux_GetParentInput( p_demux );
669 input_item_t *p_current = input_GetItem( p_input );
671 input_item_node_t *p_subitems = input_item_node_Create( p_current );
673 for( i = 0; i < i_count; i++ )
675 MP4_Box_t *p_rdrf = MP4_BoxGet( p_rmra, "rmda[%d]/rdrf", i );
679 if( !p_rdrf || !BOXDATA(p_rdrf) || !( psz_ref = strdup( BOXDATA(p_rdrf)->psz_ref ) ) )
683 i_ref_type = BOXDATA(p_rdrf)->i_ref_type;
685 msg_Dbg( p_demux, "new ref=`%s' type=%4.4s",
686 psz_ref, (char*)&i_ref_type );
688 if( i_ref_type == VLC_FOURCC( 'u', 'r', 'l', ' ' ) )
690 if( strstr( psz_ref, "qt5gateQT" ) )
692 msg_Dbg( p_demux, "ignoring pseudo ref =`%s'", psz_ref );
695 if( !strncmp( psz_ref, "http://", 7 ) ||
696 !strncmp( psz_ref, "rtsp://", 7 ) )
703 char *psz_path = strdup( p_demux->psz_location );
704 char *end = strrchr( psz_path, '/' );
705 if( end ) end[1] = '\0';
706 else *psz_path = '\0';
708 if( asprintf( &psz_absolute, "%s://%s%s",
709 p_demux->psz_access, psz_path, psz_ref ) < 0 )
713 input_item_node_Delete( p_subitems );
714 vlc_object_release( p_input) ;
719 psz_ref = psz_absolute;
722 msg_Dbg( p_demux, "adding ref = `%s'", psz_ref );
723 input_item_t *p_item = input_item_New( psz_ref, NULL );
724 input_item_CopyOptions( p_current, p_item );
725 input_item_node_AppendItem( p_subitems, p_item );
726 vlc_gc_decref( p_item );
730 msg_Err( p_demux, "unknown ref type=%4.4s FIXME (send a bug report)",
731 (char*)&BOXDATA(p_rdrf)->i_ref_type );
735 input_item_node_PostAndDelete( p_subitems );
736 vlc_object_release( p_input );
739 if( !(p_mvhd = MP4_BoxGet( p_sys->p_root, "/moov/mvhd" ) ) )
743 msg_Err( p_demux, "cannot find /moov/mvhd" );
748 msg_Warn( p_demux, "cannot find /moov/mvhd (pure ref file)" );
749 p_demux->pf_demux = DemuxRef;
755 p_sys->i_timescale = BOXDATA(p_mvhd)->i_timescale;
756 if( p_sys->i_timescale == 0 )
758 msg_Err( p_this, "bad timescale" );
763 if ( p_sys->i_overall_duration == 0 )
765 /* Try in mehd if fragmented */
766 MP4_Box_t *p_mehd = MP4_BoxGet( p_demux->p_sys->p_root, "moov/mvex/mehd");
767 if ( p_mehd && p_mehd->data.p_mehd )
768 p_sys->i_overall_duration = p_mehd->data.p_mehd->i_fragment_duration;
770 p_sys->i_overall_duration = p_sys->moovfragment.i_duration;
773 if( !( p_sys->i_tracks = MP4_BoxCount( p_sys->p_root, "/moov/trak" ) ) )
775 msg_Err( p_demux, "cannot find any /moov/trak" );
778 msg_Dbg( p_demux, "found %d track%c",
780 p_sys->i_tracks ? 's':' ' );
782 if( InitTracks( p_demux ) != VLC_SUCCESS )
785 /* Search the first chap reference (like quicktime) and
786 * check that at least 1 stream is enabled */
787 p_sys->p_tref_chap = NULL;
788 b_enabled_es = false;
789 for( i = 0; i < p_sys->i_tracks; i++ )
791 MP4_Box_t *p_trak = MP4_BoxGet( p_sys->p_root, "/moov/trak[%d]", i );
794 MP4_Box_t *p_tkhd = MP4_BoxGet( p_trak, "tkhd" );
795 if( p_tkhd && BOXDATA(p_tkhd) && (BOXDATA(p_tkhd)->i_flags&MP4_TRACK_ENABLED) )
798 MP4_Box_t *p_chap = MP4_BoxGet( p_trak, "tref/chap", i );
799 if( p_chap && p_chap->data.p_tref_generic &&
800 p_chap->data.p_tref_generic->i_entry_count > 0 && !p_sys->p_tref_chap )
801 p_sys->p_tref_chap = p_chap;
804 /* now process each track and extract all useful information */
805 for( i = 0; i < p_sys->i_tracks; i++ )
807 p_trak = MP4_BoxGet( p_sys->p_root, "/moov/trak[%d]", i );
808 MP4_TrackCreate( p_demux, &p_sys->track[i], p_trak, !b_enabled_es );
810 if( p_sys->track[i].b_ok && !p_sys->track[i].b_chapter )
813 switch( p_sys->track[i].fmt.i_cat )
822 psz_cat = "subtitle";
830 msg_Dbg( p_demux, "adding track[Id 0x%x] %s (%s) language %s",
831 p_sys->track[i].i_track_ID, psz_cat,
832 p_sys->track[i].b_enable ? "enable":"disable",
833 p_sys->track[i].fmt.psz_language ?
834 p_sys->track[i].fmt.psz_language : "undef" );
836 else if( p_sys->track[i].b_ok && p_sys->track[i].b_chapter )
838 msg_Dbg( p_demux, "using track[Id 0x%x] for chapter language %s",
839 p_sys->track[i].i_track_ID,
840 p_sys->track[i].fmt.psz_language ?
841 p_sys->track[i].fmt.psz_language : "undef" );
845 msg_Dbg( p_demux, "ignoring track[Id 0x%x]",
846 p_sys->track[i].i_track_ID );
850 mp4_fragment_t *p_fragment = &p_sys->moovfragment;
853 msg_Dbg( p_demux, "fragment offset %"PRId64", data %"PRIu64"<->%"PRIu64", duration %"PRId64,
854 p_fragment->p_moox->i_pos, p_fragment->i_chunk_range_min_offset,
855 p_fragment->i_chunk_range_max_offset, CLOCK_FREQ * p_fragment->i_duration / p_sys->i_timescale );
856 p_fragment = p_fragment->p_next;
860 LoadChapter( p_demux );
867 MP4_BoxFree( p_demux->s, p_sys->p_root );
873 /*****************************************************************************
874 * Demux: read packet and send them to decoders
875 *****************************************************************************
876 * TODO check for newly selected track (ie audio upt to now )
877 *****************************************************************************/
878 static int Demux( demux_t *p_demux )
880 demux_sys_t *p_sys = p_demux->p_sys;
881 unsigned int i_track;
884 unsigned int i_track_selected;
886 /* check for newly selected/unselected track */
887 for( i_track = 0, i_track_selected = 0; i_track < p_sys->i_tracks;
890 mp4_track_t *tk = &p_sys->track[i_track];
893 if( !tk->b_ok || tk->b_chapter ||
894 ( tk->b_selected && tk->i_sample >= tk->i_sample_count ) )
899 es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
901 if( tk->b_selected && !b )
903 MP4_TrackUnselect( p_demux, tk );
905 else if( !tk->b_selected && b)
907 MP4_TrackSelect( p_demux, tk, MP4_GetMoviePTS( p_sys ) );
916 if( i_track_selected <= 0 )
918 p_sys->i_time += __MAX( p_sys->i_timescale / 10 , 1 );
919 if( p_sys->i_timescale > 0 )
921 int64_t i_length = CLOCK_FREQ *
922 (mtime_t)p_sys->moovfragment.i_duration /
923 (mtime_t)p_sys->i_timescale;
924 if( MP4_GetMoviePTS( p_sys ) >= i_length )
929 msg_Warn( p_demux, "no track selected, exiting..." );
934 MP4_UpdateSeekpoint( p_demux );
936 /* first wait for the good time to read a packet */
937 p_sys->i_pcr = MP4_GetMoviePTS( p_sys );
939 bool b_data_sent = false;
941 /* Find next track matching contiguous data */
942 mp4_track_t *tk = NULL;
943 uint64_t i_candidate_pos = UINT64_MAX;
944 mtime_t i_candidate_dts = INT64_MAX;
945 for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
947 mp4_track_t *tk_tmp = &p_sys->track[i_track];
948 if( !tk_tmp->b_ok || tk_tmp->b_chapter || !tk_tmp->b_selected || tk_tmp->i_sample >= tk_tmp->i_sample_count )
951 if ( p_sys->b_seekmode )
953 mtime_t i_dts = MP4_TrackGetDTS( p_demux, tk_tmp );
954 if ( i_dts <= i_candidate_dts )
957 i_candidate_dts = i_dts;
958 i_candidate_pos = MP4_TrackGetPos( tk_tmp );
963 /* Try to avoid seeking on non fastseekable. Will fail with non interleaved content */
964 uint64_t i_pos = MP4_TrackGetPos( tk_tmp );
965 if ( i_pos <= i_candidate_pos )
967 i_candidate_pos = i_pos;
975 msg_Dbg( p_demux, "Could not select track by data position" );
978 else if ( p_sys->b_seekmode )
980 if( stream_Seek( p_demux->s, i_candidate_pos ) )
982 msg_Warn( p_demux, "track[0x%x] will be disabled (eof?)",
984 MP4_TrackUnselect( p_demux, tk );
990 msg_Dbg( p_demux, "tk(%i)=%"PRId64" mv=%"PRId64" pos=%"PRIu64, i_track,
991 MP4_TrackGetDTS( p_demux, tk ),
992 MP4_GetMoviePTS( p_sys ), i_candidate_pos );
995 uint32_t i_nb_samples = 0;
996 uint32_t i_samplessize = MP4_TrackGetReadSize( tk, &i_nb_samples );
997 if( i_samplessize > 0 )
1001 uint64_t i_current_pos;
1004 if ( !MP4_stream_Tell( p_demux->s, &i_current_pos ) )
1007 if( i_current_pos != i_candidate_pos )
1009 if( stream_Seek( p_demux->s, i_candidate_pos ) )
1011 msg_Warn( p_demux, "track[0x%x] will be disabled (eof?)"
1012 ": Failed to seek to %"PRIu64,
1013 tk->i_track_ID, i_candidate_pos );
1014 MP4_TrackUnselect( p_demux, tk );
1017 i_current_pos = i_candidate_pos;
1021 if( !(p_block = MP4_Block_Read( p_demux, tk, i_samplessize )) )
1023 msg_Warn( p_demux, "track[0x%x] will be disabled (eof?)"
1024 ": Failed to read %d bytes sample at %"PRIu64,
1025 tk->i_track_ID, i_samplessize, i_current_pos );
1026 MP4_TrackUnselect( p_demux, tk );
1031 p_block->i_dts = VLC_TS_0 + MP4_TrackGetDTS( p_demux, tk );
1033 i_delta = MP4_TrackGetPTSDelta( p_demux, tk );
1035 p_block->i_pts = p_block->i_dts + i_delta;
1036 else if( tk->fmt.i_cat != VIDEO_ES )
1037 p_block->i_pts = p_block->i_dts;
1039 p_block->i_pts = VLC_TS_INVALID;
1043 es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + p_sys->i_pcr );
1046 MP4_Block_Send( p_demux, tk, p_block );
1050 if ( i_nb_samples ) /* sample size could be 0, need to go fwd. see return */
1051 MP4_TrackNextSample( p_demux, tk, i_nb_samples );
1056 p_sys->i_pcr = INT64_MAX;
1057 for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
1059 mp4_track_t *tk = &p_sys->track[i_track];
1060 if ( !tk->b_ok || !tk->b_selected ||
1061 (tk->fmt.i_cat != AUDIO_ES && tk->fmt.i_cat != VIDEO_ES) )
1064 mtime_t i_dts = MP4_TrackGetDTS( p_demux, tk );
1065 p_sys->i_pcr = __MIN( i_dts, p_sys->i_pcr );
1067 if ( !p_sys->b_seekmode && i_dts > p_sys->i_pcr + 2*CLOCK_FREQ )
1069 msg_Dbg( p_demux, "that media doesn't look interleaved, will need to seek");
1070 p_sys->b_seekmode = true;
1073 p_sys->i_time = p_sys->i_pcr * p_sys->i_timescale / CLOCK_FREQ;
1077 return b_data_sent || ( i_samplessize == 0 && i_nb_samples );
1080 static void MP4_UpdateSeekpoint( demux_t *p_demux )
1082 demux_sys_t *p_sys = p_demux->p_sys;
1085 if( !p_sys->p_title )
1087 i_time = MP4_GetMoviePTS( p_sys );
1088 for( i = 0; i < p_sys->p_title->i_seekpoint; i++ )
1090 if( i_time < p_sys->p_title->seekpoint[i]->i_time_offset )
1095 if( i != p_demux->info.i_seekpoint && i >= 0 )
1097 p_demux->info.i_seekpoint = i;
1098 p_demux->info.i_update |= INPUT_UPDATE_SEEKPOINT;
1101 /*****************************************************************************
1102 * Seek: Go to i_date
1103 ******************************************************************************/
1104 static int Seek( demux_t *p_demux, mtime_t i_date )
1106 demux_sys_t *p_sys = p_demux->p_sys;
1107 unsigned int i_track;
1109 /* First update global time */
1110 p_sys->i_time = i_date * p_sys->i_timescale / CLOCK_FREQ;
1111 p_sys->i_pcr = VLC_TS_INVALID;
1113 /* Now for each stream try to go to this time */
1114 for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
1116 mp4_track_t *tk = &p_sys->track[i_track];
1117 MP4_TrackSeek( p_demux, tk, i_date );
1119 MP4_UpdateSeekpoint( p_demux );
1121 es_out_Control( p_demux->out, ES_OUT_SET_NEXT_DISPLAY_TIME, i_date );
1126 static int LeafSeekIntoFragment( demux_t *p_demux, mp4_fragment_t *p_fragment )
1128 demux_sys_t *p_sys = p_demux->p_sys;
1129 uint64_t i64 = p_fragment->i_chunk_range_min_offset;
1131 if ( p_fragment->p_moox->i_type == ATOM_moov )
1133 mp4_track_t *p_track;
1134 unsigned int i_chunk;
1135 int i_ret = LeafGetTrackAndChunkByMOOVPos( p_demux, &i64, &p_track, &i_chunk );
1136 if ( i_ret == VLC_EGENERIC )
1138 msg_Dbg( p_demux, "moov seek failed to identify %"PRIu64, i64 );
1141 msg_Dbg( p_demux, "moov seeking to %"PRIu64, i64 );
1145 i64 = p_fragment->i_chunk_range_min_offset;
1146 msg_Dbg( p_demux, "moof seeking to %"PRIu64, i64 );
1149 if( stream_Seek( p_demux->s, i64 ) )
1151 msg_Err( p_demux, "seek failed to %"PRIu64, i64 );
1152 return VLC_EGENERIC;
1156 p_sys->context.p_fragment = p_fragment;
1157 p_sys->context.i_current_box_type = ATOM_mdat;
1158 LeafMapTrafTrunContextes( p_demux, p_fragment->p_moox );
1159 p_sys->context.i_mdatbytesleft = p_fragment->i_chunk_range_max_offset - i64;
1161 mtime_t i_time_base = LeafGetFragmentTimeOffset( p_demux, p_fragment );
1162 for( unsigned int i_track = 0; i_track < p_sys->i_tracks; i_track++ )
1164 p_sys->track[i_track].i_time = i_time_base * p_sys->track[i_track].i_timescale / p_sys->i_timescale;
1166 p_sys->i_time = i_time_base;
1167 p_sys->i_pcr = VLC_TS_INVALID;
1172 static int LeafSeekToTime( demux_t *p_demux, mtime_t i_nztime )
1174 demux_sys_t *p_sys = p_demux->p_sys;
1175 mp4_fragment_t *p_fragment;
1177 if ( !p_sys->i_timescale || !p_sys->i_overall_duration || !p_sys->b_seekable )
1178 return VLC_EGENERIC;
1180 if ( !p_sys->b_fragments_probed && !p_sys->b_index_probed && p_sys->b_seekable )
1182 ProbeIndex( p_demux );
1183 p_sys->b_index_probed = true;
1186 p_fragment = GetFragmentByTime( p_demux, i_nztime );
1190 msg_Dbg( p_demux, "seek can't find matching fragment for %"PRId64", trying index", i_nztime );
1191 if ( LeafIndexGetMoofPosByTime( p_demux, i_nztime, &i64, &i_mooftime ) == VLC_SUCCESS )
1193 msg_Dbg( p_demux, "seek trying to go to unknown but indexed fragment at %"PRId64, i64 );
1194 if( stream_Seek( p_demux->s, i64 ) )
1196 msg_Err( p_demux, "seek to moof failed %"PRId64, i64 );
1197 return VLC_EGENERIC;
1199 p_sys->context.i_current_box_type = 0;
1200 p_sys->context.i_mdatbytesleft = 0;
1201 p_sys->context.p_fragment = NULL;
1202 for( unsigned int i_track = 0; i_track < p_sys->i_tracks; i_track++ )
1204 p_sys->track[i_track].i_time = i_mooftime / CLOCK_FREQ * p_sys->track[i_track].i_timescale;
1206 p_sys->i_time = i_mooftime / CLOCK_FREQ * p_sys->i_timescale;
1207 p_sys->i_pcr = VLC_TS_INVALID;
1211 msg_Warn( p_demux, "seek by index failed" );
1212 return VLC_EGENERIC;
1217 msg_Dbg( p_demux, "seeking to fragment data starting at %"PRIu64" for time %"PRId64,
1218 p_fragment->i_chunk_range_min_offset, i_nztime );
1219 if ( LeafSeekIntoFragment( p_demux, p_fragment ) != VLC_SUCCESS )
1220 return VLC_EGENERIC;
1223 /* And set next display time in that trun/fragment */
1224 es_out_Control( p_demux->out, ES_OUT_SET_NEXT_DISPLAY_TIME, VLC_TS_0 + i_nztime );
1228 static int LeafSeekToPos( demux_t *p_demux, double f )
1230 demux_sys_t *p_sys = p_demux->p_sys;
1231 if ( !p_sys->b_seekable )
1232 return VLC_EGENERIC;
1234 if ( p_sys->i_timescale && p_sys->i_overall_duration )
1236 return LeafSeekToTime( p_demux,
1237 (mtime_t)( f * CLOCK_FREQ * p_sys->i_overall_duration /
1238 p_sys->i_timescale ) );
1241 if ( !p_sys->b_fragments_probed && !p_sys->b_index_probed && p_sys->b_seekable )
1243 ProbeIndex( p_demux );
1244 p_sys->b_index_probed = true;
1247 /* Blind seek to pos only */
1248 uint64_t i64 = (uint64_t) stream_Size( p_demux->s ) * f;
1249 mp4_fragment_t *p_fragment = GetFragmentByPos( p_demux, i64, false );
1252 msg_Dbg( p_demux, "Seeking to fragment data starting at %"PRIu64" for pos %"PRIu64,
1253 p_fragment->i_chunk_range_min_offset, i64 );
1254 return LeafSeekIntoFragment( p_demux, p_fragment );
1258 msg_Dbg( p_demux, "Cant get fragment for data starting at %"PRIu64, i64 );
1259 return VLC_EGENERIC;
1263 static int MP4_frg_Seek( demux_t *p_demux, double f )
1265 demux_sys_t *p_sys = p_demux->p_sys;
1267 int64_t i64 = stream_Size( p_demux->s );
1268 if( stream_Seek( p_demux->s, (int64_t)(i64 * f) ) )
1270 return VLC_EGENERIC;
1274 /* update global time */
1275 p_sys->i_time = (uint64_t)(f * (double)p_sys->moovfragment.i_duration);
1276 p_sys->i_pcr = MP4_GetMoviePTS( p_sys );
1278 for( unsigned i_track = 0; i_track < p_sys->i_tracks; i_track++ )
1280 mp4_track_t *tk = &p_sys->track[i_track];
1282 /* We don't want the current chunk to be flushed */
1283 tk->cchunk->i_sample = tk->cchunk->i_sample_count;
1285 /* reset/update some values */
1286 tk->i_sample = tk->i_sample_first = 0;
1287 tk->i_first_dts = p_sys->i_time;
1289 /* We want to discard the current chunk and get the next one at once */
1290 tk->b_has_non_empty_cchunk = false;
1292 es_out_Control( p_demux->out, ES_OUT_SET_NEXT_DISPLAY_TIME, p_sys->i_pcr );
1297 /*****************************************************************************
1299 *****************************************************************************/
1300 static int Control( demux_t *p_demux, int i_query, va_list args )
1302 demux_sys_t *p_sys = p_demux->p_sys;
1309 case DEMUX_GET_POSITION:
1310 pf = (double*)va_arg( args, double * );
1311 if( p_sys->i_overall_duration > 0 )
1313 *pf = (double)p_sys->i_time / (double)p_sys->i_overall_duration;
1321 case DEMUX_SET_POSITION:
1322 f = (double)va_arg( args, double );
1323 if ( p_demux->pf_demux == DemuxAsLeaf )
1324 return LeafSeekToPos( p_demux, f );
1325 else if ( p_demux->pf_demux == DemuxFrg )
1326 return MP4_frg_Seek( p_demux, f );
1327 else if( p_sys->i_timescale > 0 )
1329 i64 = (int64_t)( f * CLOCK_FREQ *
1330 (double)p_sys->i_overall_duration /
1331 (double)p_sys->i_timescale );
1332 return Seek( p_demux, i64 );
1334 else return VLC_EGENERIC;
1336 case DEMUX_GET_TIME:
1337 pi64 = (int64_t*)va_arg( args, int64_t * );
1338 if( p_sys->i_timescale > 0 )
1340 *pi64 = CLOCK_FREQ *
1341 (mtime_t)p_sys->i_time /
1342 (mtime_t)p_sys->i_timescale;
1347 case DEMUX_SET_TIME:
1348 i64 = (int64_t)va_arg( args, int64_t );
1349 if ( p_demux->pf_demux == DemuxAsLeaf )
1350 return LeafSeekToTime( p_demux, i64 );
1352 return Seek( p_demux, i64 );
1354 case DEMUX_GET_LENGTH:
1355 pi64 = (int64_t*)va_arg( args, int64_t * );
1356 if( p_sys->i_timescale > 0 )
1358 *pi64 = CLOCK_FREQ *
1359 (mtime_t)p_sys->i_overall_duration /
1360 (mtime_t)p_sys->i_timescale;
1366 pf = (double*)va_arg( args, double* );
1370 case DEMUX_GET_ATTACHMENTS:
1372 input_attachment_t ***ppp_attach = va_arg( args, input_attachment_t*** );
1373 int *pi_int = va_arg( args, int * );
1375 MP4_Box_t *p_covr = MP4_BoxGet( p_sys->p_root, "/moov/udta/meta/ilst/covr" );
1376 if ( !p_covr ) return VLC_EGENERIC;
1380 for( p_box = p_covr->p_first; p_box != NULL; p_box = p_box->p_next )
1382 if ( p_box->i_type == ATOM_data && p_box->data.p_data->i_blob >= 16 )
1387 return VLC_EGENERIC;
1389 *ppp_attach = (input_attachment_t**)
1390 malloc( sizeof(input_attachment_t*) * i_count );
1391 if( !(*ppp_attach) ) return VLC_ENOMEM;
1395 for( p_box = p_covr->p_first; p_box != NULL; p_box = p_box->p_next )
1397 if ( p_box->i_type != ATOM_data || p_box->data.p_data->i_blob < 16 )
1400 if ( !memcmp( p_box->data.p_data->p_blob,
1401 "\x89\x50\x4E\x47\x0D\x0A\x1A\x0A", 8 ) )
1403 psz_mime = strdup( "image/png" );
1405 else if ( !memcmp( p_box->data.p_data->p_blob, "\xFF\xD8", 2 ) )
1407 psz_mime = strdup( "image/jpeg" );
1414 if ( asprintf( &psz_filename, "picture%u", i_count ) >= 0 )
1416 (*ppp_attach)[i_count++] =
1417 vlc_input_attachment_New( psz_filename, psz_mime, NULL,
1418 p_box->data.p_data->p_blob, p_box->data.p_data->i_blob );
1419 free( psz_filename );
1427 free( *ppp_attach );
1428 return VLC_EGENERIC;
1436 case DEMUX_GET_META:
1438 vlc_meta_t *p_meta = (vlc_meta_t *)va_arg( args, vlc_meta_t*);
1439 MP4_Box_t *p_0xa9xxx;
1441 MP4_Box_t *p_covr = MP4_BoxGet( p_sys->p_root, "/moov/udta/meta/ilst/covr/data[0]" );
1443 vlc_meta_SetArtURL( p_meta, "attachment://picture0" );
1445 MP4_Box_t *p_udta = MP4_BoxGet( p_sys->p_root, "/moov/udta/meta/ilst" );
1446 if( p_udta == NULL )
1448 p_udta = MP4_BoxGet( p_sys->p_root, "/moov/udta" );
1449 if( p_udta == NULL && p_covr == NULL )
1450 return VLC_EGENERIC;
1455 for( p_0xa9xxx = p_udta->p_first; p_0xa9xxx != NULL;
1456 p_0xa9xxx = p_0xa9xxx->p_next )
1459 if( !p_0xa9xxx || !BOXDATA(p_0xa9xxx) )
1462 /* FIXME FIXME: should convert from whatever the character
1463 * encoding of MP4 meta data is to UTF-8. */
1464 #define SET(fct) do { char *psz_utf = strdup( BOXDATA(p_0xa9xxx)->psz_text ? BOXDATA(p_0xa9xxx)->psz_text : "" ); \
1465 if( psz_utf ) { EnsureUTF8( psz_utf ); \
1466 fct( p_meta, psz_utf ); free( psz_utf ); } } while(0)
1468 /* XXX Becarefull p_udta can have box that are not 0xa9xx */
1469 switch( p_0xa9xxx->i_type )
1471 case ATOM_0xa9nam: /* Full name */
1472 SET( vlc_meta_SetTitle );
1475 SET( vlc_meta_SetArtist );
1478 SET( vlc_meta_SetArtist );
1481 SET( vlc_meta_SetCopyright );
1483 case ATOM_0xa9day: /* Creation Date */
1484 SET( vlc_meta_SetDate );
1486 case ATOM_0xa9des: /* Description */
1487 SET( vlc_meta_SetDescription );
1489 case ATOM_0xa9gen: /* Genre */
1490 SET( vlc_meta_SetGenre );
1494 if( p_0xa9xxx->data.p_gnre->i_genre <= NUM_GENRES )
1495 vlc_meta_SetGenre( p_meta, ppsz_genres[p_0xa9xxx->data.p_gnre->i_genre - 1] );
1498 case ATOM_0xa9alb: /* Album */
1499 SET( vlc_meta_SetAlbum );
1502 case ATOM_0xa9trk: /* Track */
1503 SET( vlc_meta_SetTrackNum );
1508 snprintf( psz_trck, sizeof( psz_trck ), "%i",
1509 p_0xa9xxx->data.p_trkn->i_track_number );
1510 vlc_meta_SetTrackNum( p_meta, psz_trck );
1511 if( p_0xa9xxx->data.p_trkn->i_track_total > 0 )
1513 snprintf( psz_trck, sizeof( psz_trck ), "%i",
1514 p_0xa9xxx->data.p_trkn->i_track_total );
1515 vlc_meta_Set( p_meta, vlc_meta_TrackTotal, psz_trck );
1519 case ATOM_0xa9cmt: /* Commment */
1520 SET( vlc_meta_SetDescription );
1523 case ATOM_0xa9url: /* URL */
1524 SET( vlc_meta_SetURL );
1527 case ATOM_0xa9too: /* Encoder Tool */
1528 case ATOM_0xa9enc: /* Encoded By */
1529 SET( vlc_meta_SetEncodedBy );
1533 SET( vlc_meta_SetPublisher );
1537 SET( vlc_meta_SetDirector );
1544 static const struct { uint32_t xa9_type; char metadata[25]; } xa9typetoextrameta[] =
1546 { ATOM_0xa9wrt, N_("Writer") },
1547 { ATOM_0xa9com, N_("Composer") },
1548 { ATOM_0xa9prd, N_("Producer") },
1549 { ATOM_0xa9inf, N_("Information") },
1550 { ATOM_0xa9dis, N_("Disclaimer") },
1551 { ATOM_0xa9req, N_("Requirements") },
1552 { ATOM_0xa9fmt, N_("Original Format") },
1553 { ATOM_0xa9dsa, N_("Display Source As") },
1554 { ATOM_0xa9hst, N_("Host Computer") },
1555 { ATOM_0xa9prf, N_("Performers") },
1556 { ATOM_0xa9ope, N_("Original Performer") },
1557 { ATOM_0xa9src, N_("Providers Source Content") },
1558 { ATOM_0xa9wrn, N_("Warning") },
1559 { ATOM_0xa9swr, N_("Software") },
1560 { ATOM_0xa9lyr, N_("Lyrics") },
1561 { ATOM_0xa9mak, N_("Record Company") },
1562 { ATOM_0xa9mod, N_("Model") },
1563 { ATOM_0xa9PRD, N_("Product") },
1564 { ATOM_0xa9grp, N_("Grouping") },
1565 { ATOM_0xa9gen, N_("Genre") },
1566 { ATOM_0xa9st3, N_("Sub-Title") },
1567 { ATOM_0xa9arg, N_("Arranger") },
1568 { ATOM_0xa9ard, N_("Art Director") },
1569 { ATOM_0xa9cak, N_("Copyright Acknowledgement") },
1570 { ATOM_0xa9con, N_("Conductor") },
1571 { ATOM_0xa9des, N_("Song Description") },
1572 { ATOM_0xa9lnt, N_("Liner Notes") },
1573 { ATOM_0xa9phg, N_("Phonogram Rights") },
1574 { ATOM_0xa9pub, N_("Publisher") },
1575 { ATOM_0xa9sne, N_("Sound Engineer") },
1576 { ATOM_0xa9sol, N_("Soloist") },
1577 { ATOM_0xa9thx, N_("Thanks") },
1578 { ATOM_0xa9xpd, N_("Executive Producer") },
1581 for( unsigned i = 0; xa9typetoextrameta[i].xa9_type; i++ )
1583 if( p_0xa9xxx->i_type == xa9typetoextrameta[i].xa9_type )
1585 char *psz_utf = strdup( BOXDATA(p_0xa9xxx)->psz_text ? BOXDATA(p_0xa9xxx)->psz_text : "" );
1588 EnsureUTF8( psz_utf );
1589 vlc_meta_AddExtra( p_meta, _(xa9typetoextrameta[i].metadata), psz_utf );
1599 case DEMUX_GET_TITLE_INFO:
1601 input_title_t ***ppp_title = (input_title_t***)va_arg( args, input_title_t*** );
1602 int *pi_int = (int*)va_arg( args, int* );
1603 int *pi_title_offset = (int*)va_arg( args, int* );
1604 int *pi_seekpoint_offset = (int*)va_arg( args, int* );
1606 if( !p_sys->p_title )
1607 return VLC_EGENERIC;
1610 *ppp_title = malloc( sizeof( input_title_t*) );
1611 (*ppp_title)[0] = vlc_input_title_Duplicate( p_sys->p_title );
1612 *pi_title_offset = 0;
1613 *pi_seekpoint_offset = 0;
1616 case DEMUX_SET_TITLE:
1618 const int i_title = (int)va_arg( args, int );
1619 if( !p_sys->p_title || i_title != 0 )
1620 return VLC_EGENERIC;
1623 case DEMUX_SET_SEEKPOINT:
1625 const int i_seekpoint = (int)va_arg( args, int );
1626 if( !p_sys->p_title )
1627 return VLC_EGENERIC;
1628 return Seek( p_demux, p_sys->p_title->seekpoint[i_seekpoint]->i_time_offset );
1631 case DEMUX_SET_NEXT_DEMUX_TIME:
1632 case DEMUX_SET_GROUP:
1633 case DEMUX_HAS_UNSUPPORTED_META:
1634 case DEMUX_GET_PTS_DELAY:
1635 case DEMUX_CAN_RECORD:
1636 return VLC_EGENERIC;
1639 msg_Warn( p_demux, "control query %u unimplemented", i_query );
1640 return VLC_EGENERIC;
1644 /*****************************************************************************
1645 * Close: frees unused data
1646 *****************************************************************************/
1647 static void Close ( vlc_object_t * p_this )
1649 demux_t * p_demux = (demux_t *)p_this;
1650 demux_sys_t *p_sys = p_demux->p_sys;
1651 unsigned int i_track;
1653 msg_Dbg( p_demux, "freeing all memory" );
1655 MP4_BoxFree( p_demux->s, p_sys->p_root );
1656 for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
1658 MP4_TrackDestroy( &p_sys->track[i_track] );
1660 FREENULL( p_sys->track );
1662 if( p_sys->p_title )
1663 vlc_input_title_Delete( p_sys->p_title );
1665 while( p_sys->moovfragment.p_next )
1667 mp4_fragment_t *p_fragment = p_sys->moovfragment.p_next->p_next;
1668 free( p_sys->moovfragment.p_next );
1669 p_sys->moovfragment.p_next = p_fragment;
1677 /****************************************************************************
1678 * Local functions, specific to vlc
1679 ****************************************************************************/
1681 static void LoadChapterGpac( demux_t *p_demux, MP4_Box_t *p_chpl )
1683 demux_sys_t *p_sys = p_demux->p_sys;
1686 p_sys->p_title = vlc_input_title_New();
1687 for( i = 0; i < BOXDATA(p_chpl)->i_chapter; i++ )
1689 seekpoint_t *s = vlc_seekpoint_New();
1691 s->psz_name = strdup( BOXDATA(p_chpl)->chapter[i].psz_name );
1692 EnsureUTF8( s->psz_name );
1693 s->i_time_offset = BOXDATA(p_chpl)->chapter[i].i_start / 10;
1694 TAB_APPEND( p_sys->p_title->i_seekpoint, p_sys->p_title->seekpoint, s );
1697 static void LoadChapterApple( demux_t *p_demux, mp4_track_t *tk )
1699 demux_sys_t *p_sys = p_demux->p_sys;
1701 for( tk->i_sample = 0; tk->i_sample < tk->i_sample_count; tk->i_sample++ )
1703 const int64_t i_dts = MP4_TrackGetDTS( p_demux, tk );
1704 const int64_t i_pts_delta = MP4_TrackGetPTSDelta( p_demux, tk );
1705 uint32_t i_nb_samples = 0;
1706 const uint32_t i_size = MP4_TrackGetReadSize( tk, &i_nb_samples );
1708 if( i_size > 0 && !stream_Seek( p_demux->s, MP4_TrackGetPos( tk ) ) )
1711 const uint32_t i_read = stream_ReadU32( p_demux->s, p_buffer,
1712 __MIN( sizeof(p_buffer), i_size ) );
1713 const uint32_t i_len = __MIN( GetWBE(p_buffer), i_read-2 );
1717 seekpoint_t *s = vlc_seekpoint_New();
1719 s->psz_name = strndup( &p_buffer[2], i_len );
1720 EnsureUTF8( s->psz_name );
1722 s->i_time_offset = i_dts + __MAX( i_pts_delta, 0 );
1724 if( !p_sys->p_title )
1725 p_sys->p_title = vlc_input_title_New();
1726 TAB_APPEND( p_sys->p_title->i_seekpoint, p_sys->p_title->seekpoint, s );
1729 if( tk->i_sample+1 >= tk->chunk[tk->i_chunk].i_sample_first +
1730 tk->chunk[tk->i_chunk].i_sample_count )
1734 static void LoadChapter( demux_t *p_demux )
1736 demux_sys_t *p_sys = p_demux->p_sys;
1739 if( ( p_chpl = MP4_BoxGet( p_sys->p_root, "/moov/udta/chpl" ) ) &&
1740 BOXDATA(p_chpl) && BOXDATA(p_chpl)->i_chapter > 0 )
1742 LoadChapterGpac( p_demux, p_chpl );
1744 else if( p_sys->p_tref_chap )
1746 MP4_Box_data_tref_generic_t *p_chap = p_sys->p_tref_chap->data.p_tref_generic;
1749 /* Load the first subtitle track like quicktime */
1750 for( i = 0; i < p_chap->i_entry_count; i++ )
1752 for( j = 0; j < p_sys->i_tracks; j++ )
1754 mp4_track_t *tk = &p_sys->track[j];
1755 if( tk->b_ok && tk->i_track_ID == p_chap->i_track_ID[i] &&
1756 tk->fmt.i_cat == SPU_ES && tk->fmt.i_codec == VLC_CODEC_SUBT )
1759 if( j < p_sys->i_tracks )
1761 LoadChapterApple( p_demux, &p_sys->track[j] );
1767 /* Add duration if titles are enabled */
1768 if( p_sys->p_title )
1770 p_sys->p_title->i_length = CLOCK_FREQ *
1771 (uint64_t)p_sys->i_overall_duration / (uint64_t)p_sys->i_timescale;
1775 /* now create basic chunk data, the rest will be filled by MP4_CreateSamplesIndex */
1776 static int TrackCreateChunksIndex( demux_t *p_demux,
1777 mp4_track_t *p_demux_track )
1779 demux_sys_t *p_sys = p_demux->p_sys;
1781 MP4_Box_t *p_co64; /* give offset for each chunk, same for stco and co64 */
1784 unsigned int i_chunk;
1785 unsigned int i_index, i_last;
1787 if( ( !(p_co64 = MP4_BoxGet( p_demux_track->p_stbl, "stco" ) )&&
1788 !(p_co64 = MP4_BoxGet( p_demux_track->p_stbl, "co64" ) ) )||
1789 ( !(p_stsc = MP4_BoxGet( p_demux_track->p_stbl, "stsc" ) ) ))
1791 return( VLC_EGENERIC );
1794 p_demux_track->i_chunk_count = BOXDATA(p_co64)->i_entry_count;
1795 if( !p_demux_track->i_chunk_count )
1797 msg_Warn( p_demux, "no chunk defined" );
1799 p_demux_track->chunk = calloc( p_demux_track->i_chunk_count,
1800 sizeof( mp4_chunk_t ) );
1801 if( p_demux_track->chunk == NULL )
1806 /* first we read chunk offset */
1807 for( i_chunk = 0; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
1809 mp4_chunk_t *ck = &p_demux_track->chunk[i_chunk];
1811 ck->i_offset = BOXDATA(p_co64)->i_chunk_offset[i_chunk];
1813 ck->i_first_dts = 0;
1814 ck->p_sample_count_dts = NULL;
1815 ck->p_sample_delta_dts = NULL;
1816 ck->p_sample_count_pts = NULL;
1817 ck->p_sample_offset_pts = NULL;
1820 /* now we read index for SampleEntry( soun vide mp4a mp4v ...)
1821 to be used for the sample XXX begin to 1
1822 We construct it begining at the end */
1823 i_last = p_demux_track->i_chunk_count; /* last chunk proceded */
1824 i_index = BOXDATA(p_stsc)->i_entry_count;
1826 while( i_index-- > 0 )
1828 for( i_chunk = BOXDATA(p_stsc)->i_first_chunk[i_index] - 1;
1829 i_chunk < i_last; i_chunk++ )
1831 if( i_chunk >= p_demux_track->i_chunk_count )
1833 msg_Warn( p_demux, "corrupted chunk table" );
1834 return VLC_EGENERIC;
1837 p_demux_track->chunk[i_chunk].i_sample_description_index =
1838 BOXDATA(p_stsc)->i_sample_description_index[i_index];
1839 p_demux_track->chunk[i_chunk].i_sample_count =
1840 BOXDATA(p_stsc)->i_samples_per_chunk[i_index];
1842 i_last = BOXDATA(p_stsc)->i_first_chunk[i_index] - 1;
1845 if ( p_demux_track->i_chunk_count )
1847 p_demux_track->chunk[0].i_sample_first = 0;
1848 for( i_chunk = 1; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
1850 p_demux_track->chunk[i_chunk].i_sample_first =
1851 p_demux_track->chunk[i_chunk-1].i_sample_first +
1852 p_demux_track->chunk[i_chunk-1].i_sample_count;
1856 msg_Dbg( p_demux, "track[Id 0x%x] read %d chunk",
1857 p_demux_track->i_track_ID, p_demux_track->i_chunk_count );
1859 if ( p_demux_track->i_chunk_count && (
1860 p_sys->moovfragment.i_chunk_range_min_offset == 0 ||
1861 p_sys->moovfragment.i_chunk_range_min_offset > p_demux_track->chunk[0].i_offset
1863 p_sys->moovfragment.i_chunk_range_min_offset = p_demux_track->chunk[0].i_offset;
1868 static int xTTS_CountEntries( demux_t *p_demux, uint32_t *pi_entry /* out */,
1869 const uint32_t i_index,
1870 uint32_t i_index_samples_left,
1871 uint32_t i_sample_count,
1872 const uint32_t *pi_index_sample_count,
1873 const uint32_t i_table_count )
1875 uint32_t i_array_offset;
1876 while( i_sample_count > 0 )
1878 if ( likely((UINT32_MAX - i_index) >= *pi_entry) )
1879 i_array_offset = i_index + *pi_entry;
1881 return VLC_EGENERIC;
1883 if ( i_array_offset >= i_table_count )
1885 msg_Err( p_demux, "invalid index counting total samples %u %u", i_array_offset, i_table_count );
1886 return VLC_EGENERIC;
1889 if ( i_index_samples_left )
1891 if ( i_index_samples_left > i_sample_count )
1893 i_index_samples_left -= i_sample_count;
1895 *pi_entry +=1; /* No samples left, go copy */
1900 i_sample_count -= i_index_samples_left;
1901 i_index_samples_left = 0;
1908 i_sample_count -= __MIN( i_sample_count, pi_index_sample_count[i_array_offset] );
1916 static int TrackCreateSamplesIndex( demux_t *p_demux,
1917 mp4_track_t *p_demux_track )
1919 demux_sys_t *p_sys = p_demux->p_sys;
1922 MP4_Box_data_stsz_t *stsz;
1923 /* TODO use also stss and stsh table for seeking */
1924 /* FIXME use edit table */
1927 * Gives the sample size for each samples. There is also a stz2 table
1928 * (compressed form) that we need to implement TODO */
1929 p_box = MP4_BoxGet( p_demux_track->p_stbl, "stsz" );
1932 /* FIXME and stz2 */
1933 msg_Warn( p_demux, "cannot find STSZ box" );
1934 return VLC_EGENERIC;
1936 stsz = p_box->data.p_stsz;
1938 /* Use stsz table to create a sample number -> sample size table */
1939 p_demux_track->i_sample_count = stsz->i_sample_count;
1940 if( stsz->i_sample_size )
1942 /* 1: all sample have the same size, so no need to construct a table */
1943 p_demux_track->i_sample_size = stsz->i_sample_size;
1944 p_demux_track->p_sample_size = NULL;
1948 /* 2: each sample can have a different size */
1949 p_demux_track->i_sample_size = 0;
1950 p_demux_track->p_sample_size =
1951 calloc( p_demux_track->i_sample_count, sizeof( uint32_t ) );
1952 if( p_demux_track->p_sample_size == NULL )
1955 for( uint32_t i_sample = 0; i_sample < p_demux_track->i_sample_count; i_sample++ )
1957 p_demux_track->p_sample_size[i_sample] =
1958 stsz->i_entry_size[i_sample];
1962 if ( p_demux_track->i_chunk_count )
1964 mp4_chunk_t *lastchunk = &p_demux_track->chunk[p_demux_track->i_chunk_count - 1];
1965 uint64_t i_total_size = lastchunk->i_offset;
1966 for( uint32_t i=0; i<lastchunk->i_sample_count; i++)
1968 if( p_demux_track->i_sample_size == 0 )
1969 i_total_size += stsz->i_entry_size[i];
1971 i_total_size += p_demux_track->i_sample_size;
1974 if ( i_total_size > p_sys->moovfragment.i_chunk_range_max_offset )
1975 p_sys->moovfragment.i_chunk_range_max_offset = i_total_size;
1978 /* Use stts table to create a sample number -> dts table.
1979 * XXX: if we don't want to waste too much memory, we can't expand
1980 * the box! so each chunk will contain an "extract" of this table
1981 * for fast research (problem with raw stream where a sample is sometime
1982 * just channels*bits_per_sample/8 */
1984 /* FIXME: refactor STTS & CTTS, STTS having now only few extra lines and
1985 * differing in 2/2 fields and 1 signedness */
1987 mtime_t i_next_dts = 0;
1989 * Gives mapping between sample and decoding time
1991 p_box = MP4_BoxGet( p_demux_track->p_stbl, "stts" );
1994 msg_Warn( p_demux, "cannot find STTS box" );
1995 return VLC_EGENERIC;
1999 MP4_Box_data_stts_t *stts = p_box->data.p_stts;
2001 msg_Warn( p_demux, "STTS table of %"PRIu32" entries", stts->i_entry_count );
2003 /* Create sample -> dts table per chunk */
2004 uint32_t i_index = 0;
2005 uint32_t i_current_index_samples_left = 0;
2007 for( uint32_t i_chunk = 0; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
2009 mp4_chunk_t *ck = &p_demux_track->chunk[i_chunk];
2010 uint32_t i_entry, i_sample_count;
2012 /* save first dts */
2013 ck->i_first_dts = i_next_dts;
2014 ck->i_last_dts = i_next_dts;
2016 /* count how many entries are needed for this chunk
2017 * for p_sample_delta_dts and p_sample_count_dts */
2020 int i_ret = xTTS_CountEntries( p_demux, &i_entry, i_index,
2021 i_current_index_samples_left,
2023 stts->pi_sample_count,
2024 stts->i_entry_count );
2025 if ( i_ret != VLC_SUCCESS )
2029 ck->p_sample_count_dts = calloc( i_entry, sizeof( uint32_t ) );
2030 ck->p_sample_delta_dts = calloc( i_entry, sizeof( uint32_t ) );
2031 if( !ck->p_sample_count_dts || !ck->p_sample_delta_dts )
2033 msg_Err( p_demux, "can't allocate memory for i_entry=%"PRIu32, i_entry );
2038 i_sample_count = ck->i_sample_count;
2040 for( uint32_t i = 0; i < i_entry; i++ )
2042 if ( i_current_index_samples_left )
2044 if ( i_current_index_samples_left > i_sample_count )
2046 if ( i_sample_count ) ck->i_last_dts = i_next_dts;
2047 ck->p_sample_count_dts[i] = i_sample_count;
2048 ck->p_sample_delta_dts[i] = stts->pi_sample_delta[i_index];
2049 i_next_dts += ck->p_sample_count_dts[i] * stts->pi_sample_delta[i_index];
2050 i_current_index_samples_left -= i_sample_count;
2052 assert( i == i_entry - 1 );
2057 if ( i_current_index_samples_left ) ck->i_last_dts = i_next_dts;
2058 ck->p_sample_count_dts[i] = i_current_index_samples_left;
2059 ck->p_sample_delta_dts[i] = stts->pi_sample_delta[i_index];
2060 i_next_dts += ck->p_sample_count_dts[i] * stts->pi_sample_delta[i_index];
2061 i_sample_count -= i_current_index_samples_left;
2062 i_current_index_samples_left = 0;
2068 if ( stts->pi_sample_count[i_index] > i_sample_count )
2070 if ( i_sample_count ) ck->i_last_dts = i_next_dts;
2071 ck->p_sample_count_dts[i] = i_sample_count;
2072 ck->p_sample_delta_dts[i] = stts->pi_sample_delta[i_index];
2073 i_next_dts += ck->p_sample_count_dts[i] * stts->pi_sample_delta[i_index];
2074 i_current_index_samples_left = stts->pi_sample_count[i_index] - i_sample_count;
2076 assert( i == i_entry - 1 );
2077 // keep building from same index
2081 if ( stts->pi_sample_count[i_index] ) ck->i_last_dts = i_next_dts;
2082 ck->p_sample_count_dts[i] = stts->pi_sample_count[i_index];
2083 ck->p_sample_delta_dts[i] = stts->pi_sample_delta[i_index];
2084 i_next_dts += ck->p_sample_count_dts[i] * stts->pi_sample_delta[i_index];
2085 i_sample_count -= stts->pi_sample_count[i_index];
2096 * Gives the delta between decoding time (dts) and composition table (pts)
2098 p_box = MP4_BoxGet( p_demux_track->p_stbl, "ctts" );
2099 if( p_box && p_box->data.p_ctts )
2101 MP4_Box_data_ctts_t *ctts = p_box->data.p_ctts;
2103 msg_Warn( p_demux, "CTTS table of %"PRIu32" entries", ctts->i_entry_count );
2105 /* Create pts-dts table per chunk */
2106 uint32_t i_index = 0;
2107 uint32_t i_current_index_samples_left = 0;
2109 for( uint32_t i_chunk = 0; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
2111 mp4_chunk_t *ck = &p_demux_track->chunk[i_chunk];
2112 uint32_t i_entry, i_sample_count;
2114 /* count how many entries are needed for this chunk
2115 * for p_sample_offset_pts and p_sample_count_pts */
2117 int i_ret = xTTS_CountEntries( p_demux, &i_entry, i_index,
2118 i_current_index_samples_left,
2120 ctts->pi_sample_count,
2121 ctts->i_entry_count );
2122 if ( i_ret != VLC_SUCCESS )
2126 ck->p_sample_count_pts = calloc( i_entry, sizeof( uint32_t ) );
2127 ck->p_sample_offset_pts = calloc( i_entry, sizeof( int32_t ) );
2128 if( !ck->p_sample_count_pts || !ck->p_sample_offset_pts )
2130 msg_Err( p_demux, "can't allocate memory for i_entry=%"PRIu32, i_entry );
2135 i_sample_count = ck->i_sample_count;
2137 for( uint32_t i = 0; i < i_entry; i++ )
2139 if ( i_current_index_samples_left )
2141 if ( i_current_index_samples_left > i_sample_count )
2143 ck->p_sample_count_pts[i] = i_sample_count;
2144 ck->p_sample_offset_pts[i] = ctts->pi_sample_offset[i_index];
2145 i_current_index_samples_left -= i_sample_count;
2147 assert( i == i_entry - 1 );
2152 ck->p_sample_count_pts[i] = i_current_index_samples_left;
2153 ck->p_sample_offset_pts[i] = ctts->pi_sample_offset[i_index];
2154 i_sample_count -= i_current_index_samples_left;
2155 i_current_index_samples_left = 0;
2161 if ( ctts->pi_sample_count[i_index] > i_sample_count )
2163 ck->p_sample_count_pts[i] = i_sample_count;
2164 ck->p_sample_offset_pts[i] = ctts->pi_sample_offset[i_index];
2165 i_current_index_samples_left = ctts->pi_sample_count[i_index] - i_sample_count;
2167 assert( i == i_entry - 1 );
2168 // keep building from same index
2172 ck->p_sample_count_pts[i] = ctts->pi_sample_count[i_index];
2173 ck->p_sample_offset_pts[i] = ctts->pi_sample_offset[i_index];
2174 i_sample_count -= ctts->pi_sample_count[i_index];
2184 msg_Dbg( p_demux, "track[Id 0x%x] read %"PRIu32" samples length:%"PRId64"s",
2185 p_demux_track->i_track_ID, p_demux_track->i_sample_count,
2186 i_next_dts / p_demux_track->i_timescale );
2193 * It computes the sample rate for a video track using the given sample
2196 static void TrackGetESSampleRate( demux_t *p_demux,
2197 unsigned *pi_num, unsigned *pi_den,
2198 const mp4_track_t *p_track,
2199 unsigned i_sd_index,
2205 MP4_Box_t *p_trak = MP4_GetTrakByTrackID( MP4_BoxGet( p_demux->p_sys->p_root, "/moov" ),
2206 p_track->i_track_ID );
2207 MP4_Box_t *p_mdhd = MP4_BoxGet( p_trak, "mdia/mdhd" );
2208 if ( p_mdhd && BOXDATA(p_mdhd) )
2210 vlc_ureduce( pi_num, pi_den,
2211 (uint64_t) BOXDATA(p_mdhd)->i_timescale * p_track->i_sample_count,
2212 (uint64_t) BOXDATA(p_mdhd)->i_duration,
2217 if( p_track->i_chunk_count <= 0 )
2221 const mp4_chunk_t *p_chunk = &p_track->chunk[i_chunk];
2222 while( p_chunk > &p_track->chunk[0] &&
2223 p_chunk[-1].i_sample_description_index == i_sd_index )
2228 uint64_t i_sample = 0;
2229 uint64_t i_first_dts = p_chunk->i_first_dts;
2230 uint64_t i_last_dts;
2233 i_sample += p_chunk->i_sample_count;
2234 i_last_dts = p_chunk->i_last_dts;
2237 while( p_chunk < &p_track->chunk[p_track->i_chunk_count] &&
2238 p_chunk->i_sample_description_index == i_sd_index );
2240 if( i_sample > 1 && i_first_dts < i_last_dts )
2241 vlc_ureduce( pi_num, pi_den,
2242 ( i_sample - 1) * p_track->i_timescale,
2243 i_last_dts - i_first_dts,
2249 * Create ES and PES to init decoder if needed, for a track starting at i_chunk
2251 static int TrackCreateES( demux_t *p_demux, mp4_track_t *p_track,
2252 unsigned int i_chunk, es_out_id_t **pp_es )
2254 demux_sys_t *p_sys = p_demux->p_sys;
2255 unsigned int i_sample_description_index;
2257 if( p_sys->b_fragmented )
2258 i_sample_description_index = 1; /* XXX */
2260 i_sample_description_index =
2261 p_track->chunk[i_chunk].i_sample_description_index;
2263 MP4_Box_t *p_sample;
2272 if( !i_sample_description_index )
2274 msg_Warn( p_demux, "invalid SampleEntry index (track[Id 0x%x])",
2275 p_track->i_track_ID );
2276 return VLC_EGENERIC;
2279 p_sample = MP4_BoxGet( p_track->p_stsd, "[%d]",
2280 i_sample_description_index - 1 );
2283 ( !p_sample->data.p_payload && p_track->fmt.i_cat != SPU_ES ) )
2285 msg_Warn( p_demux, "cannot find SampleEntry (track[Id 0x%x])",
2286 p_track->i_track_ID );
2287 return VLC_EGENERIC;
2290 p_track->p_sample = p_sample;
2292 if( ( p_frma = MP4_BoxGet( p_track->p_sample, "sinf/frma" ) ) && p_frma->data.p_frma )
2294 msg_Warn( p_demux, "Original Format Box: %4.4s", (char *)&p_frma->data.p_frma->i_type );
2296 p_sample->i_type = p_frma->data.p_frma->i_type;
2299 p_enda = MP4_BoxGet( p_sample, "wave/enda" );
2301 p_enda = MP4_BoxGet( p_sample, "enda" );
2303 p_pasp = MP4_BoxGet( p_sample, "pasp" );
2306 switch( p_track->fmt.i_cat )
2309 if ( !p_sample->data.p_sample_vide || p_sample->i_handler != ATOM_vide )
2311 p_track->fmt.video.i_width = p_sample->data.p_sample_vide->i_width;
2312 p_track->fmt.video.i_height = p_sample->data.p_sample_vide->i_height;
2313 p_track->fmt.video.i_bits_per_pixel =
2314 p_sample->data.p_sample_vide->i_depth;
2316 /* fall on display size */
2317 if( p_track->fmt.video.i_width <= 0 )
2318 p_track->fmt.video.i_width = p_track->i_width;
2319 if( p_track->fmt.video.i_height <= 0 )
2320 p_track->fmt.video.i_height = p_track->i_height;
2322 /* Find out apect ratio from display size */
2323 if( p_track->i_width > 0 && p_track->i_height > 0 &&
2324 /* Work-around buggy muxed files */
2325 p_sample->data.p_sample_vide->i_width != p_track->i_width )
2327 p_track->fmt.video.i_sar_num = p_track->i_width * p_track->fmt.video.i_height;
2328 p_track->fmt.video.i_sar_den = p_track->i_height * p_track->fmt.video.i_width;
2330 if( p_pasp && p_pasp->data.p_pasp->i_horizontal_spacing > 0 &&
2331 p_pasp->data.p_pasp->i_vertical_spacing > 0 )
2333 p_track->fmt.video.i_sar_num = p_pasp->data.p_pasp->i_horizontal_spacing;
2334 p_track->fmt.video.i_sar_den = p_pasp->data.p_pasp->i_vertical_spacing;
2337 /* Support for cropping (eg. in H263 files) */
2338 p_track->fmt.video.i_visible_width = p_track->fmt.video.i_width;
2339 p_track->fmt.video.i_visible_height = p_track->fmt.video.i_height;
2342 TrackGetESSampleRate( p_demux,
2343 &p_track->fmt.video.i_frame_rate,
2344 &p_track->fmt.video.i_frame_rate_base,
2345 p_track, i_sample_description_index, i_chunk );
2347 p_demux->p_sys->f_fps = (float)p_track->fmt.video.i_frame_rate /
2348 (float)p_track->fmt.video.i_frame_rate_base;
2351 switch( (int)p_track->f_rotation ) {
2353 p_track->fmt.video.orientation = ORIENT_ROTATED_90;
2356 p_track->fmt.video.orientation = ORIENT_ROTATED_180;
2359 p_track->fmt.video.orientation = ORIENT_ROTATED_270;
2366 if ( !p_sample->data.p_sample_soun || p_sample->i_handler != ATOM_soun )
2368 p_track->fmt.audio.i_channels =
2369 p_sample->data.p_sample_soun->i_channelcount;
2370 p_track->fmt.audio.i_rate =
2371 p_sample->data.p_sample_soun->i_sampleratehi;
2372 p_track->fmt.i_bitrate = p_sample->data.p_sample_soun->i_channelcount *
2373 p_sample->data.p_sample_soun->i_sampleratehi *
2374 p_sample->data.p_sample_soun->i_samplesize;
2375 p_track->fmt.audio.i_bitspersample =
2376 p_sample->data.p_sample_soun->i_samplesize;
2378 MP4_Box_data_sample_soun_t *p_soun = p_sample->data.p_sample_soun;
2380 p_track->fmt.i_original_fourcc = p_sample->i_type;
2382 if( ( p_track->i_sample_size == 1 || p_track->i_sample_size == 2 ) )
2384 if( p_soun->i_qt_version == 0 )
2386 switch( p_sample->i_type )
2388 case VLC_CODEC_ADPCM_IMA_QT:
2389 p_soun->i_qt_version = 1;
2390 p_soun->i_sample_per_packet = 64;
2391 p_soun->i_bytes_per_packet = 34;
2392 p_soun->i_bytes_per_frame = 34 * p_soun->i_channelcount;
2393 p_soun->i_bytes_per_sample = 2;
2395 case VLC_CODEC_MACE3:
2396 p_soun->i_qt_version = 1;
2397 p_soun->i_sample_per_packet = 6;
2398 p_soun->i_bytes_per_packet = 2;
2399 p_soun->i_bytes_per_frame = 2 * p_soun->i_channelcount;
2400 p_soun->i_bytes_per_sample = 2;
2402 case VLC_CODEC_MACE6:
2403 p_soun->i_qt_version = 1;
2404 p_soun->i_sample_per_packet = 12;
2405 p_soun->i_bytes_per_packet = 2;
2406 p_soun->i_bytes_per_frame = 2 * p_soun->i_channelcount;
2407 p_soun->i_bytes_per_sample = 2;
2409 case VLC_CODEC_ALAW:
2410 case VLC_FOURCC( 'u', 'l', 'a', 'w' ):
2411 p_soun->i_samplesize = 8;
2412 p_track->i_sample_size = p_soun->i_channelcount;
2414 case VLC_FOURCC( 'N', 'O', 'N', 'E' ):
2415 case VLC_FOURCC( 'r', 'a', 'w', ' ' ):
2416 case VLC_FOURCC( 't', 'w', 'o', 's' ):
2417 case VLC_FOURCC( 's', 'o', 'w', 't' ):
2418 /* What would be the fun if you could trust the .mov */
2419 p_track->i_sample_size = ((p_soun->i_samplesize+7)/8) * p_soun->i_channelcount;
2426 else if( p_soun->i_qt_version == 1 && p_soun->i_sample_per_packet <= 0 )
2428 p_soun->i_qt_version = 0;
2431 else if( p_sample->data.p_sample_soun->i_qt_version == 1 )
2433 switch( p_sample->i_type )
2435 case( VLC_FOURCC( '.', 'm', 'p', '3' ) ):
2436 case( VLC_FOURCC( 'm', 's', 0x00, 0x55 ) ):
2438 if( p_track->i_sample_size > 1 )
2439 p_soun->i_qt_version = 0;
2444 case( VLC_FOURCC( 'm', 's', 0x20, 0x00 ) ):
2445 p_soun->i_qt_version = 0;
2452 if( p_track->i_sample_size != 0 &&
2453 p_sample->data.p_sample_soun->i_qt_version == 1 &&
2454 p_sample->data.p_sample_soun->i_sample_per_packet <= 0 )
2456 msg_Err( p_demux, "Invalid sample per packet value for qt_version 1. Broken muxer!" );
2457 p_sample->data.p_sample_soun->i_qt_version = 0;
2460 /* Lookup for then channels extension */
2461 const MP4_Box_t *p_chan = MP4_BoxGet( p_sample, "chan" );
2464 if ( BOXDATA(p_chan)->layout.i_channels_layout_tag == MP4_CHAN_USE_CHANNELS_BITMAP )
2466 uint32_t rgi_chans_sequence[AOUT_CHAN_MAX + 1];
2467 uint16_t i_vlc_mapping = 0;
2468 uint8_t i_channels = 0;
2469 const uint32_t i_bitmap = BOXDATA(p_chan)->layout.i_channels_bitmap;
2470 for (uint8_t i=0;i<MP4_CHAN_BITMAP_MAPPING_COUNT;i++)
2472 if ( chan_bitmap_mapping[i].i_bitmap & i_bitmap )
2475 if ( (chan_bitmap_mapping[i].i_vlc & i_vlc_mapping) ||
2476 i_channels > AOUT_CHAN_MAX )
2478 /* double mapping or unsupported number of channels */
2480 msg_Warn( p_demux, "discarding chan mapping" );
2483 i_vlc_mapping |= chan_bitmap_mapping[i].i_vlc;
2484 rgi_chans_sequence[i_channels - 1] = chan_bitmap_mapping[i].i_vlc;
2487 rgi_chans_sequence[i_channels] = 0;
2488 p_track->b_chans_reorder = !!
2489 aout_CheckChannelReorder( rgi_chans_sequence, NULL, i_vlc_mapping,
2490 p_track->rgi_chans_reordering );
2501 /* It's a little ugly but .. there are special cases */
2502 switch( p_sample->i_type )
2504 case( VLC_FOURCC( '.', 'm', 'p', '3' ) ):
2505 case( VLC_FOURCC( 'm', 's', 0x00, 0x55 ) ):
2507 p_track->fmt.i_codec = VLC_CODEC_MPGA;
2512 MP4_Box_t *p_dec3_box = MP4_BoxGet( p_sample, "dec3", 0 );
2514 p_track->fmt.i_codec = VLC_CODEC_EAC3;
2517 MP4_Box_data_dec3_t *p_dec3 = p_dec3_box->data.p_dec3;
2518 p_track->fmt.audio.i_channels = 0;
2519 p_track->fmt.i_bitrate = p_dec3->i_data_rate * 1000;
2520 p_track->fmt.audio.i_bitspersample = 0;
2526 MP4_Box_t *p_dac3_box = MP4_BoxGet( p_sample, "dac3", 0 );
2528 p_track->fmt.i_codec = VLC_CODEC_A52;
2531 static const int pi_bitrate[] = {
2538 MP4_Box_data_dac3_t *p_dac3 = p_dac3_box->data.p_dac3;
2539 p_track->fmt.audio.i_channels = 0;
2540 p_track->fmt.i_bitrate = 0;
2541 if( p_dac3->i_bitrate_code < sizeof(pi_bitrate)/sizeof(*pi_bitrate) )
2542 p_track->fmt.i_bitrate = pi_bitrate[p_dac3->i_bitrate_code] * 1000;
2543 p_track->fmt.audio.i_bitspersample = 0;
2548 case( VLC_FOURCC( 'r', 'a', 'w', ' ' ) ):
2549 case( VLC_FOURCC( 'N', 'O', 'N', 'E' ) ):
2551 if ( p_sample->i_handler != ATOM_soun )
2553 MP4_Box_data_sample_soun_t *p_soun = p_sample->data.p_sample_soun;
2555 if(p_soun && (p_soun->i_samplesize+7)/8 == 1 )
2556 p_track->fmt.i_codec = VLC_CODEC_U8;
2558 p_track->fmt.i_codec = VLC_FOURCC( 't', 'w', 'o', 's' );
2560 /* Buggy files workaround */
2561 if( p_sample->data.p_sample_soun && (p_track->i_timescale !=
2562 p_sample->data.p_sample_soun->i_sampleratehi) )
2564 msg_Warn( p_demux, "i_timescale (%"PRId32") != i_sampleratehi "
2565 "(%u), making both equal (report any problem).",
2566 p_track->i_timescale, p_soun->i_sampleratehi );
2568 if( p_soun->i_sampleratehi != 0 )
2569 p_track->i_timescale = p_soun->i_sampleratehi;
2571 p_soun->i_sampleratehi = p_track->i_timescale;
2576 case( VLC_FOURCC( 's', '2', '6', '3' ) ):
2577 p_track->fmt.i_codec = VLC_CODEC_H263;
2580 case( ATOM_c608 ): /* EIA608 closed captions */
2581 //case( ATOM_c708 ): /* EIA708 closed captions */
2582 p_track->fmt.i_codec = VLC_CODEC_EIA608_1;
2583 p_track->fmt.i_cat = SPU_ES;
2586 case( VLC_FOURCC( 't', 'e', 'x', 't' ) ):
2587 case( VLC_FOURCC( 't', 'x', '3', 'g' ) ):
2589 if ( p_sample->i_handler != ATOM_text )
2591 p_track->fmt.i_codec = VLC_CODEC_TX3G;
2592 MP4_Box_data_sample_text_t *p_text = p_sample->data.p_sample_text;
2595 text_style_t *p_style = text_style_New();
2598 if ( p_text->i_font_size ) /* !WARN: % in absolute storage */
2599 p_style->i_font_size = p_text->i_font_size;
2600 if ( p_text->i_font_color )
2602 p_style->i_font_color = p_text->i_font_color >> 8;
2603 p_style->i_font_alpha = p_text->i_font_color & 0xFF;
2605 if ( p_text->i_background_color[3] >> 8 )
2607 p_style->i_background_color = p_text->i_background_color[0] >> 8;
2608 p_style->i_background_color |= p_text->i_background_color[1] >> 8;
2609 p_style->i_background_color |= p_text->i_background_color[2] >> 8;
2610 p_style->i_background_alpha = p_text->i_background_color[3] >> 8;
2613 p_track->fmt.subs.p_style = p_style;
2615 /* FIXME UTF-8 doesn't work here ? */
2616 if( p_track->b_mac_encoding )
2617 p_track->fmt.subs.psz_encoding = strdup( "MAC" );
2619 p_track->fmt.subs.psz_encoding = strdup( "UTF-8" );
2622 case VLC_FOURCC('y','v','1','2'):
2623 p_track->fmt.i_codec = VLC_CODEC_YV12;
2625 case VLC_FOURCC('y','u','v','2'):
2626 p_track->fmt.i_codec = VLC_FOURCC('Y','U','Y','2');
2629 case VLC_FOURCC('i','n','2','4'):
2630 p_track->fmt.i_codec = p_enda && BOXDATA(p_enda)->i_little_endian == 1 ?
2631 VLC_FOURCC('4','2','n','i') : VLC_FOURCC('i','n','2','4');
2633 case VLC_FOURCC('i','n','3','2'):
2634 p_track->fmt.i_codec = p_enda && BOXDATA(p_enda)->i_little_endian == 1 ?
2635 VLC_CODEC_S32L : VLC_CODEC_S32B;
2637 case VLC_FOURCC('f','l','3','2'):
2638 p_track->fmt.i_codec = p_enda && BOXDATA(p_enda)->i_little_endian == 1 ?
2639 VLC_CODEC_F32L : VLC_CODEC_F32B;
2641 case VLC_FOURCC('f','l','6','4'):
2642 p_track->fmt.i_codec = p_enda && BOXDATA(p_enda)->i_little_endian == 1 ?
2643 VLC_CODEC_F64L : VLC_CODEC_F64B;
2645 case VLC_CODEC_DVD_LPCM:
2647 if ( p_sample->i_handler != ATOM_soun )
2649 MP4_Box_data_sample_soun_t *p_soun = p_sample->data.p_sample_soun;
2650 if( p_soun->i_qt_version == 2 )
2657 static const struct {
2661 vlc_fourcc_t i_codec;
2663 { 0x01, 0x03, 32, VLC_CODEC_F32L },
2664 { 0x01, 0x03, 64, VLC_CODEC_F64L },
2665 { 0x01|0x02, 0x03, 32, VLC_CODEC_F32B },
2666 { 0x01|0x02, 0x03, 64, VLC_CODEC_F64B },
2668 { 0x00, 0x05, 8, VLC_CODEC_U8 },
2669 { 0x00| 0x04, 0x05, 8, VLC_CODEC_S8 },
2671 { 0x00, 0x07, 16, VLC_CODEC_U16L },
2672 { 0x00|0x02, 0x07, 16, VLC_CODEC_U16B },
2673 { 0x00 |0x04, 0x07, 16, VLC_CODEC_S16L },
2674 { 0x00|0x02|0x04, 0x07, 16, VLC_CODEC_S16B },
2676 { 0x00, 0x07, 24, VLC_CODEC_U24L },
2677 { 0x00|0x02, 0x07, 24, VLC_CODEC_U24B },
2678 { 0x00 |0x04, 0x07, 24, VLC_CODEC_S24L },
2679 { 0x00|0x02|0x04, 0x07, 24, VLC_CODEC_S24B },
2681 { 0x00, 0x07, 32, VLC_CODEC_U32L },
2682 { 0x00|0x02, 0x07, 32, VLC_CODEC_U32B },
2683 { 0x00 |0x04, 0x07, 32, VLC_CODEC_S32L },
2684 { 0x00|0x02|0x04, 0x07, 32, VLC_CODEC_S32B },
2689 for( int i = 0; p_formats[i].i_codec; i++ )
2691 if( p_formats[i].i_bits == p_soun->i_constbitsperchannel &&
2692 (p_soun->i_formatflags & p_formats[i].i_mask) == p_formats[i].i_flags )
2694 p_track->fmt.i_codec = p_formats[i].i_codec;
2695 p_track->fmt.audio.i_bitspersample = p_soun->i_constbitsperchannel;
2696 p_track->fmt.audio.i_blockalign =
2697 p_soun->i_channelcount * p_soun->i_constbitsperchannel / 8;
2698 p_track->i_sample_size = p_track->fmt.audio.i_blockalign;
2700 p_soun->i_qt_version = 0;
2708 p_track->fmt.i_codec = p_sample->i_type;
2712 /* now see if esds is present and if so create a data packet
2713 with decoder_specific_info */
2714 #define p_decconfig p_esds->data.p_esds->es_descriptor.p_decConfigDescr
2715 if( ( ( p_esds = MP4_BoxGet( p_sample, "esds" ) ) ||
2716 ( p_esds = MP4_BoxGet( p_sample, "wave/esds" ) ) )&&
2717 ( p_esds->data.p_esds )&&
2720 /* First update information based on i_objectTypeIndication */
2721 switch( p_decconfig->i_objectTypeIndication )
2723 case( 0x20 ): /* MPEG4 VIDEO */
2724 p_track->fmt.i_codec = VLC_CODEC_MP4V;
2726 case( 0x21 ): /* H.264 */
2727 p_track->fmt.i_codec = VLC_CODEC_H264;
2730 p_track->fmt.i_codec = VLC_CODEC_MP4A;
2731 if( p_decconfig->i_decoder_specific_info_len >= 2 &&
2732 p_decconfig->p_decoder_specific_info[0] == 0xF8 &&
2733 (p_decconfig->p_decoder_specific_info[1]&0xE0) == 0x80 )
2735 p_track->fmt.i_codec = VLC_CODEC_ALS;
2743 case( 0x65): /* MPEG2 video */
2744 p_track->fmt.i_codec = VLC_CODEC_MPGV;
2746 /* Theses are MPEG2-AAC */
2747 case( 0x66): /* main profile */
2748 case( 0x67): /* Low complexity profile */
2749 case( 0x68): /* Scaleable Sampling rate profile */
2750 p_track->fmt.i_codec = VLC_CODEC_MP4A;
2752 /* True MPEG 2 audio */
2754 p_track->fmt.i_codec = VLC_CODEC_MPGA;
2756 case( 0x6a): /* MPEG1 video */
2757 p_track->fmt.i_codec = VLC_CODEC_MPGV;
2759 case( 0x6b): /* MPEG1 audio */
2760 p_track->fmt.i_codec = VLC_CODEC_MPGA;
2762 case( 0x6c ): /* jpeg */
2763 p_track->fmt.i_codec = VLC_CODEC_JPEG;
2765 case( 0x6d ): /* png */
2766 p_track->fmt.i_codec = VLC_CODEC_PNG;
2768 case( 0x6e ): /* jpeg2000 */
2769 p_track->fmt.i_codec = VLC_FOURCC( 'M','J','2','C' );
2771 case( 0xa3 ): /* vc1 */
2772 p_track->fmt.i_codec = VLC_CODEC_VC1;
2775 p_track->fmt.i_codec = VLC_CODEC_DIRAC;
2778 p_track->fmt.i_codec = VLC_CODEC_A52;
2781 p_track->fmt.i_codec = VLC_CODEC_EAC3;
2783 case( 0xa9 ): /* dts */
2784 case( 0xaa ): /* DTS-HD HRA */
2785 case( 0xab ): /* DTS-HD Master Audio */
2786 p_track->fmt.i_codec = VLC_CODEC_DTS;
2789 p_track->fmt.i_codec = VLC_CODEC_VORBIS;
2793 case( 0xe0 ): /* NeroDigital: dvd subs */
2794 if( p_track->fmt.i_cat == SPU_ES )
2796 p_track->fmt.i_codec = VLC_CODEC_SPU;
2797 if( p_track->i_width > 0 )
2798 p_track->fmt.subs.spu.i_original_frame_width = p_track->i_width;
2799 if( p_track->i_height > 0 )
2800 p_track->fmt.subs.spu.i_original_frame_height = p_track->i_height;
2803 case( 0xe1 ): /* QCelp for 3gp */
2804 if( p_track->fmt.i_cat == AUDIO_ES )
2806 p_track->fmt.i_codec = VLC_CODEC_QCELP;
2812 /* Unknown entry, but don't touch i_fourcc */
2814 "unknown objectTypeIndication(0x%x) (Track[ID 0x%x])",
2815 p_decconfig->i_objectTypeIndication,
2816 p_track->i_track_ID );
2819 p_track->fmt.i_extra = p_decconfig->i_decoder_specific_info_len;
2820 if( p_track->fmt.i_extra > 0 )
2822 p_track->fmt.p_extra = malloc( p_track->fmt.i_extra );
2823 memcpy( p_track->fmt.p_extra, p_decconfig->p_decoder_specific_info,
2824 p_track->fmt.i_extra );
2826 if( p_track->fmt.i_codec == VLC_CODEC_SPU &&
2827 p_track->fmt.i_extra >= 16 * 4 )
2829 for( int i = 0; i < 16; i++ )
2831 p_track->fmt.subs.spu.palette[1 + i] =
2832 GetDWBE((char*)p_track->fmt.p_extra + i * 4);
2834 p_track->fmt.subs.spu.palette[0] = 0xBeef;
2839 switch( p_sample->i_type )
2841 /* qt decoder, send the complete chunk */
2842 case VLC_FOURCC ('h', 'd', 'v', '1'): // HDV 720p30
2843 case VLC_FOURCC ('h', 'd', 'v', '2'): // HDV 1080i60
2844 case VLC_FOURCC ('h', 'd', 'v', '3'): // HDV 1080i50
2845 case VLC_FOURCC ('h', 'd', 'v', '5'): // HDV 720p25
2846 case VLC_FOURCC ('m', 'x', '5', 'n'): // MPEG2 IMX NTSC 525/60 50mb/s produced by FCP
2847 case VLC_FOURCC ('m', 'x', '5', 'p'): // MPEG2 IMX PAL 625/60 50mb/s produced by FCP
2848 case VLC_FOURCC ('m', 'x', '4', 'n'): // MPEG2 IMX NTSC 525/60 40mb/s produced by FCP
2849 case VLC_FOURCC ('m', 'x', '4', 'p'): // MPEG2 IMX PAL 625/60 40mb/s produced by FCP
2850 case VLC_FOURCC ('m', 'x', '3', 'n'): // MPEG2 IMX NTSC 525/60 30mb/s produced by FCP
2851 case VLC_FOURCC ('m', 'x', '3', 'p'): // MPEG2 IMX PAL 625/50 30mb/s produced by FCP
2852 case VLC_FOURCC ('x', 'd', 'v', '2'): // XDCAM HD 1080i60
2853 case VLC_FOURCC ('A', 'V', 'm', 'p'): // AVID IMX PAL
2854 p_track->fmt.i_codec = VLC_CODEC_MPGV;
2856 /* qt decoder, send the complete chunk */
2857 case VLC_CODEC_SVQ1:
2858 case VLC_CODEC_SVQ3:
2859 case VLC_FOURCC( 'V', 'P', '3', '1' ):
2860 case VLC_FOURCC( '3', 'I', 'V', '1' ):
2861 case VLC_FOURCC( 'Z', 'y', 'G', 'o' ):
2863 if ( p_sample->i_handler != ATOM_vide )
2865 p_track->fmt.i_extra =
2866 p_sample->data.p_sample_vide->i_qt_image_description;
2867 if( p_track->fmt.i_extra > 0 )
2869 p_track->fmt.p_extra = malloc( p_track->fmt.i_extra );
2870 memcpy( p_track->fmt.p_extra,
2871 p_sample->data.p_sample_vide->p_qt_image_description,
2872 p_track->fmt.i_extra);
2877 case VLC_CODEC_AMR_NB:
2878 p_track->fmt.audio.i_rate = 8000;
2880 case VLC_CODEC_AMR_WB:
2881 p_track->fmt.audio.i_rate = 16000;
2883 case VLC_FOURCC( 'Q', 'D', 'M', 'C' ):
2884 case VLC_CODEC_QDM2:
2885 case VLC_CODEC_ALAC:
2887 if ( p_sample->i_handler != ATOM_soun )
2889 p_track->fmt.i_extra =
2890 p_sample->data.p_sample_soun->i_qt_description;
2891 if( p_track->fmt.i_extra > 0 )
2893 p_track->fmt.p_extra = malloc( p_track->fmt.i_extra );
2894 memcpy( p_track->fmt.p_extra,
2895 p_sample->data.p_sample_soun->p_qt_description,
2896 p_track->fmt.i_extra);
2898 if( p_track->fmt.i_extra == 56 && p_sample->i_type == VLC_CODEC_ALAC )
2900 p_track->fmt.audio.i_channels = *((uint8_t*)p_track->fmt.p_extra + 41);
2901 p_track->fmt.audio.i_rate = GetDWBE((uint8_t*)p_track->fmt.p_extra + 52);
2905 case VLC_FOURCC( 'v', 'c', '-', '1' ):
2907 MP4_Box_t *p_dvc1 = MP4_BoxGet( p_sample, "dvc1" );
2910 p_track->fmt.i_extra = BOXDATA(p_dvc1)->i_vc1;
2911 if( p_track->fmt.i_extra > 0 )
2913 p_track->fmt.p_extra = malloc( BOXDATA(p_dvc1)->i_vc1 );
2914 memcpy( p_track->fmt.p_extra, BOXDATA(p_dvc1)->p_vc1,
2915 p_track->fmt.i_extra );
2920 msg_Err( p_demux, "missing dvc1" );
2925 /* avc1: send avcC (h264 without annexe B, ie without start code)*/
2926 case VLC_FOURCC( 'a', 'v', 'c', '1' ):
2928 MP4_Box_t *p_avcC = MP4_BoxGet( p_sample, "avcC" );
2932 p_track->fmt.i_extra = BOXDATA(p_avcC)->i_avcC;
2933 if( p_track->fmt.i_extra > 0 )
2935 p_track->fmt.p_extra = malloc( BOXDATA(p_avcC)->i_avcC );
2936 memcpy( p_track->fmt.p_extra, BOXDATA(p_avcC)->p_avcC,
2937 p_track->fmt.i_extra );
2942 msg_Err( p_demux, "missing avcC" );
2946 case VLC_FOURCC( 'h', 'v', 'c', '1' ):
2947 case VLC_FOURCC( 'h', 'e', 'v', '1' ):
2949 MP4_Box_t *p_hvcC = MP4_BoxGet( p_sample, "hvcC" );
2953 p_track->fmt.i_extra = p_hvcC->data.p_hvcC->i_hvcC;
2954 if( p_track->fmt.i_extra > 0 )
2956 p_track->fmt.p_extra = malloc( p_hvcC->data.p_hvcC->i_hvcC );
2957 memcpy( p_track->fmt.p_extra, p_hvcC->data.p_hvcC->p_hvcC,
2958 p_track->fmt.i_extra );
2960 p_track->fmt.i_codec = VLC_CODEC_HEVC;
2964 msg_Err( p_demux, "missing hvcC" );
2970 case VLC_CODEC_ADPCM_MS:
2971 case VLC_CODEC_ADPCM_IMA_WAV:
2972 case VLC_CODEC_QCELP:
2974 if ( p_sample->i_handler == ATOM_soun )
2975 p_track->fmt.audio.i_blockalign = p_sample->data.p_sample_soun->i_bytes_per_frame;
2980 msg_Dbg( p_demux, "Unrecognized FourCC %4.4s", (char *)&p_sample->i_type );
2988 *pp_es = es_out_Add( p_demux->out, &p_track->fmt );
2993 /* given a time it return sample/chunk
2994 * it also update elst field of the track
2996 static int TrackTimeToSampleChunk( demux_t *p_demux, mp4_track_t *p_track,
2997 int64_t i_start, uint32_t *pi_chunk,
2998 uint32_t *pi_sample )
3000 demux_sys_t *p_sys = p_demux->p_sys;
3001 MP4_Box_t *p_box_stss;
3003 unsigned int i_sample;
3004 unsigned int i_chunk;
3007 /* FIXME see if it's needed to check p_track->i_chunk_count */
3008 if( p_track->i_chunk_count == 0 )
3009 return( VLC_EGENERIC );
3011 /* handle elst (find the correct one) */
3012 MP4_TrackSetELST( p_demux, p_track, i_start );
3013 if( p_track->p_elst && p_track->BOXDATA(p_elst)->i_entry_count > 0 )
3015 MP4_Box_data_elst_t *elst = p_track->BOXDATA(p_elst);
3016 int64_t i_mvt= i_start * p_sys->i_timescale / CLOCK_FREQ;
3018 /* now calculate i_start for this elst */
3020 i_start -= p_track->i_elst_time * CLOCK_FREQ / p_sys->i_timescale;
3028 /* to track time scale */
3029 i_start = i_start * p_track->i_timescale / CLOCK_FREQ;
3030 /* add elst offset */
3031 if( ( elst->i_media_rate_integer[p_track->i_elst] > 0 ||
3032 elst->i_media_rate_fraction[p_track->i_elst] > 0 ) &&
3033 elst->i_media_time[p_track->i_elst] > 0 )
3035 i_start += elst->i_media_time[p_track->i_elst];
3038 msg_Dbg( p_demux, "elst (%d) gives %"PRId64"ms (movie)-> %"PRId64
3039 "ms (track)", p_track->i_elst,
3040 i_mvt * 1000 / p_sys->i_timescale,
3041 i_start * 1000 / p_track->i_timescale );
3045 /* convert absolute time to in timescale unit */
3046 i_start = i_start * p_track->i_timescale / CLOCK_FREQ;
3049 /* we start from sample 0/chunk 0, hope it won't take too much time */
3050 /* *** find good chunk *** */
3051 for( i_chunk = 0; ; i_chunk++ )
3053 if( i_chunk + 1 >= p_track->i_chunk_count )
3055 /* at the end and can't check if i_start in this chunk,
3056 it will be check while searching i_sample */
3057 i_chunk = p_track->i_chunk_count - 1;
3061 if( (uint64_t)i_start >= p_track->chunk[i_chunk].i_first_dts &&
3062 (uint64_t)i_start < p_track->chunk[i_chunk + 1].i_first_dts )
3068 /* *** find sample in the chunk *** */
3069 i_sample = p_track->chunk[i_chunk].i_sample_first;
3070 i_dts = p_track->chunk[i_chunk].i_first_dts;
3071 for( i_index = 0; i_sample < p_track->chunk[i_chunk].i_sample_count; )
3074 p_track->chunk[i_chunk].p_sample_count_dts[i_index] *
3075 p_track->chunk[i_chunk].p_sample_delta_dts[i_index] < (uint64_t)i_start )
3078 p_track->chunk[i_chunk].p_sample_count_dts[i_index] *
3079 p_track->chunk[i_chunk].p_sample_delta_dts[i_index];
3081 i_sample += p_track->chunk[i_chunk].p_sample_count_dts[i_index];
3086 if( p_track->chunk[i_chunk].p_sample_delta_dts[i_index] <= 0 )
3090 i_sample += ( i_start - i_dts ) /
3091 p_track->chunk[i_chunk].p_sample_delta_dts[i_index];
3096 if( i_sample >= p_track->i_sample_count )
3098 msg_Warn( p_demux, "track[Id 0x%x] will be disabled "
3099 "(seeking too far) chunk=%d sample=%d",
3100 p_track->i_track_ID, i_chunk, i_sample );
3101 return( VLC_EGENERIC );
3105 /* *** Try to find nearest sync points *** */
3106 if( ( p_box_stss = MP4_BoxGet( p_track->p_stbl, "stss" ) ) )
3108 MP4_Box_data_stss_t *p_stss = p_box_stss->data.p_stss;
3109 msg_Dbg( p_demux, "track[Id 0x%x] using Sync Sample Box (stss)",
3110 p_track->i_track_ID );
3111 for( unsigned i_index = 0; i_index < p_stss->i_entry_count; i_index++ )
3113 if( i_index >= p_stss->i_entry_count - 1 ||
3114 i_sample < p_stss->i_sample_number[i_index+1] )
3116 unsigned i_sync_sample = p_stss->i_sample_number[i_index];
3117 msg_Dbg( p_demux, "stss gives %d --> %d (sample number)",
3118 i_sample, i_sync_sample );
3120 if( i_sync_sample <= i_sample )
3122 while( i_chunk > 0 &&
3123 i_sync_sample < p_track->chunk[i_chunk].i_sample_first )
3128 while( i_chunk < p_track->i_chunk_count - 1 &&
3129 i_sync_sample >= p_track->chunk[i_chunk].i_sample_first +
3130 p_track->chunk[i_chunk].i_sample_count )
3133 i_sample = i_sync_sample;
3140 msg_Dbg( p_demux, "track[Id 0x%x] does not provide Sync "
3141 "Sample Box (stss)", p_track->i_track_ID );
3144 *pi_chunk = i_chunk;
3145 *pi_sample = i_sample;
3150 static int TrackGotoChunkSample( demux_t *p_demux, mp4_track_t *p_track,
3151 unsigned int i_chunk, unsigned int i_sample )
3153 bool b_reselect = false;
3155 /* now see if actual es is ok */
3156 if( p_track->i_chunk >= p_track->i_chunk_count ||
3157 p_track->chunk[p_track->i_chunk].i_sample_description_index !=
3158 p_track->chunk[i_chunk].i_sample_description_index )
3160 msg_Warn( p_demux, "recreate ES for track[Id 0x%x]",
3161 p_track->i_track_ID );
3163 es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE,
3164 p_track->p_es, &b_reselect );
3166 es_out_Del( p_demux->out, p_track->p_es );
3168 p_track->p_es = NULL;
3170 if( TrackCreateES( p_demux, p_track, i_chunk, &p_track->p_es ) )
3172 msg_Err( p_demux, "cannot create es for track[Id 0x%x]",
3173 p_track->i_track_ID );
3175 p_track->b_ok = false;
3176 p_track->b_selected = false;
3177 return VLC_EGENERIC;
3181 /* select again the new decoder */
3184 es_out_Control( p_demux->out, ES_OUT_SET_ES, p_track->p_es );
3187 p_track->i_chunk = i_chunk;
3188 p_track->i_sample = i_sample;
3190 return p_track->b_selected ? VLC_SUCCESS : VLC_EGENERIC;
3193 /****************************************************************************
3195 ****************************************************************************
3196 * Parse track information and create all needed data to run a track
3197 * If it succeed b_ok is set to 1 else to 0
3198 ****************************************************************************/
3199 static void MP4_TrackCreate( demux_t *p_demux, mp4_track_t *p_track,
3200 MP4_Box_t *p_box_trak,
3201 bool b_force_enable )
3203 demux_sys_t *p_sys = p_demux->p_sys;
3205 MP4_Box_t *p_tkhd = MP4_BoxGet( p_box_trak, "tkhd" );
3206 MP4_Box_t *p_tref = MP4_BoxGet( p_box_trak, "tref" );
3216 char language[4] = { '\0' };
3218 /* hint track unsupported */
3220 /* set default value (-> track unusable) */
3221 p_track->b_ok = false;
3222 p_track->b_enable = false;
3223 p_track->b_selected = false;
3224 p_track->b_chapter = false;
3225 p_track->b_mac_encoding = false;
3227 es_format_Init( &p_track->fmt, UNKNOWN_ES, 0 );
3234 /* do we launch this track by default ? */
3236 ( ( BOXDATA(p_tkhd)->i_flags&MP4_TRACK_ENABLED ) != 0 );
3237 if( !p_track->b_enable )
3238 p_track->fmt.i_priority = ES_PRIORITY_NOT_DEFAULTABLE;
3240 p_track->i_track_ID = BOXDATA(p_tkhd)->i_track_ID;
3242 p_track->i_width = BOXDATA(p_tkhd)->i_width / BLOCK16x16;
3243 p_track->i_height = BOXDATA(p_tkhd)->i_height / BLOCK16x16;
3244 p_track->f_rotation = BOXDATA(p_tkhd)->f_rotation;
3248 /* msg_Warn( p_demux, "unhandled box: tref --> FIXME" ); */
3251 p_mdhd = MP4_BoxGet( p_box_trak, "mdia/mdhd" );
3252 p_hdlr = MP4_BoxGet( p_box_trak, "mdia/hdlr" );
3254 if( ( !p_mdhd )||( !p_hdlr ) )
3259 p_track->i_timescale = BOXDATA(p_mdhd)->i_timescale;
3260 if( p_track->i_timescale == 0 )
3263 memcpy( &language, BOXDATA(p_mdhd)->rgs_language, 3 );
3264 p_track->b_mac_encoding = BOXDATA(p_mdhd)->b_mac_encoding;
3266 switch( p_hdlr->data.p_hdlr->i_handler_type )
3269 if( !( p_smhd = MP4_BoxGet( p_box_trak, "mdia/minf/smhd" ) ) )
3273 p_track->fmt.i_cat = AUDIO_ES;
3277 if( !( p_vmhd = MP4_BoxGet( p_box_trak, "mdia/minf/vmhd" ) ) )
3281 p_track->fmt.i_cat = VIDEO_ES;
3288 p_track->fmt.i_codec = VLC_CODEC_TX3G;
3289 p_track->fmt.i_cat = SPU_ES;
3292 /* closed captions */
3294 p_track->fmt.i_cat = SPU_ES;
3301 p_track->i_elst = 0;
3302 p_track->i_elst_time = 0;
3303 if( ( p_track->p_elst = p_elst = MP4_BoxGet( p_box_trak, "edts/elst" ) ) )
3305 MP4_Box_data_elst_t *elst = BOXDATA(p_elst);
3308 msg_Warn( p_demux, "elst box found" );
3309 for( i = 0; i < elst->i_entry_count; i++ )
3311 msg_Dbg( p_demux, " - [%d] duration=%"PRId64"ms media time=%"PRId64
3312 "ms) rate=%d.%d", i,
3313 elst->i_segment_duration[i] * 1000 / p_sys->i_timescale,
3314 elst->i_media_time[i] >= 0 ?
3315 (int64_t)(elst->i_media_time[i] * 1000 / p_track->i_timescale) :
3317 elst->i_media_rate_integer[i],
3318 elst->i_media_rate_fraction[i] );
3325 p_dinf = MP4_BoxGet( p_minf, "dinf" );
3327 if( !( p_track->p_stbl = MP4_BoxGet( p_box_trak,"mdia/minf/stbl" ) ) ||
3328 !( p_track->p_stsd = MP4_BoxGet( p_box_trak,"mdia/minf/stbl/stsd") ) )
3334 if( *language && strcmp( language, "```" ) && strcmp( language, "und" ) )
3336 p_track->fmt.psz_language = strdup( language );
3339 p_udta = MP4_BoxGet( p_box_trak, "udta" );
3342 MP4_Box_t *p_box_iter;
3343 for( p_box_iter = p_udta->p_first; p_box_iter != NULL;
3344 p_box_iter = p_box_iter->p_next )
3346 switch( p_box_iter->i_type )
3349 p_track->fmt.psz_description =
3350 strdup( p_box_iter->data.p_0xa9xxx->psz_text );
3353 p_track->fmt.psz_description =
3354 strdup( p_box_iter->data.p_name->psz_text );
3360 /* Create chunk index table and sample index table */
3361 if( TrackCreateChunksIndex( p_demux,p_track ) ||
3362 TrackCreateSamplesIndex( p_demux, p_track ) )
3364 msg_Err( p_demux, "cannot create chunks index" );
3365 return; /* cannot create chunks index */
3368 p_track->i_chunk = 0;
3369 p_track->i_sample = 0;
3371 /* Mark chapter only track */
3372 if( p_sys->p_tref_chap )
3374 MP4_Box_data_tref_generic_t *p_chap = p_sys->p_tref_chap->data.p_tref_generic;
3377 for( i = 0; i < p_chap->i_entry_count; i++ )
3379 if( p_track->i_track_ID == p_chap->i_track_ID[i] &&
3380 p_track->fmt.i_cat == UNKNOWN_ES )
3382 p_track->b_chapter = true;
3383 p_track->b_enable = false;
3390 if( b_force_enable &&
3391 ( p_track->fmt.i_cat == VIDEO_ES || p_track->fmt.i_cat == AUDIO_ES ) )
3393 msg_Warn( p_demux, "Enabling track[Id 0x%x] (buggy file without enabled track)",
3394 p_track->i_track_ID );
3395 p_track->b_enable = true;
3396 p_track->fmt.i_priority = ES_PRIORITY_SELECTABLE_MIN;
3399 p_track->p_es = NULL;
3400 if( TrackCreateES( p_demux,
3401 p_track, p_track->i_chunk,
3402 p_track->b_chapter ? NULL : &p_track->p_es ) )
3404 msg_Err( p_demux, "cannot create es for track[Id 0x%x]",
3405 p_track->i_track_ID );
3408 p_track->b_ok = true;
3412 for( i = 0; i < p_track->i_chunk_count; i++ )
3414 fprintf( stderr, "%-5d sample_count=%d pts=%lld\n",
3415 i, p_track->chunk[i].i_sample_count,
3416 p_track->chunk[i].i_first_dts );
3423 static void FreeAndResetChunk( mp4_chunk_t *ck )
3425 free( ck->p_sample_count_dts );
3426 free( ck->p_sample_delta_dts );
3427 free( ck->p_sample_count_pts );
3428 free( ck->p_sample_offset_pts );
3429 free( ck->p_sample_size );
3430 for( uint32_t i = 0; i < ck->i_sample_count; i++ )
3431 free( ck->p_sample_data[i] );
3432 free( ck->p_sample_data );
3433 memset( ck, 0, sizeof( mp4_chunk_t ) );
3436 /****************************************************************************
3438 ****************************************************************************
3439 * Destroy a track created by MP4_TrackCreate.
3440 ****************************************************************************/
3441 static void MP4_TrackDestroy( mp4_track_t *p_track )
3443 unsigned int i_chunk;
3445 p_track->b_ok = false;
3446 p_track->b_enable = false;
3447 p_track->b_selected = false;
3449 es_format_Clean( &p_track->fmt );
3451 for( i_chunk = 0; i_chunk < p_track->i_chunk_count; i_chunk++ )
3453 if( p_track->chunk )
3455 FREENULL(p_track->chunk[i_chunk].p_sample_count_dts);
3456 FREENULL(p_track->chunk[i_chunk].p_sample_delta_dts );
3458 FREENULL(p_track->chunk[i_chunk].p_sample_count_pts);
3459 FREENULL(p_track->chunk[i_chunk].p_sample_offset_pts );
3462 FREENULL( p_track->chunk );
3463 if( p_track->cchunk ) {
3464 FreeAndResetChunk( p_track->cchunk );
3465 FREENULL( p_track->cchunk );
3468 if( !p_track->i_sample_size )
3470 FREENULL( p_track->p_sample_size );
3474 static int MP4_TrackSelect( demux_t *p_demux, mp4_track_t *p_track,
3477 if( !p_track->b_ok || p_track->b_chapter )
3479 return VLC_EGENERIC;
3482 if( p_track->b_selected )
3484 msg_Warn( p_demux, "track[Id 0x%x] already selected",
3485 p_track->i_track_ID );
3489 return MP4_TrackSeek( p_demux, p_track, i_start );
3492 static void MP4_TrackUnselect( demux_t *p_demux, mp4_track_t *p_track )
3494 if( !p_track->b_ok || p_track->b_chapter )
3499 if( !p_track->b_selected )
3501 msg_Warn( p_demux, "track[Id 0x%x] already unselected",
3502 p_track->i_track_ID );
3507 es_out_Control( p_demux->out, ES_OUT_SET_ES_STATE,
3508 p_track->p_es, false );
3511 p_track->b_selected = false;
3514 static int MP4_TrackSeek( demux_t *p_demux, mp4_track_t *p_track,
3520 if( !p_track->b_ok || p_track->b_chapter )
3521 return VLC_EGENERIC;
3523 p_track->b_selected = false;
3525 if( TrackTimeToSampleChunk( p_demux, p_track, i_start,
3526 &i_chunk, &i_sample ) )
3528 msg_Warn( p_demux, "cannot select track[Id 0x%x]",
3529 p_track->i_track_ID );
3530 return VLC_EGENERIC;
3533 p_track->b_selected = true;
3534 if( !TrackGotoChunkSample( p_demux, p_track, i_chunk, i_sample ) )
3535 p_track->b_selected = true;
3537 return p_track->b_selected ? VLC_SUCCESS : VLC_EGENERIC;
3542 * 3 types: for audio
3545 #define QT_V0_MAX_SAMPLES 1024
3546 static uint32_t MP4_TrackGetReadSize( mp4_track_t *p_track, uint32_t *pi_nb_samples )
3548 uint32_t i_size = 0;
3551 if ( p_track->i_sample == p_track->i_sample_count )
3554 if ( p_track->fmt.i_cat != AUDIO_ES )
3558 if( p_track->i_sample_size == 0 ) /* all sizes are different */
3559 return p_track->p_sample_size[p_track->i_sample];
3561 return p_track->i_sample_size;
3565 const MP4_Box_data_sample_soun_t *p_soun = p_track->p_sample->data.p_sample_soun;
3566 const mp4_chunk_t *p_chunk = &p_track->chunk[p_track->i_chunk];
3567 uint32_t i_max_samples = p_chunk->i_sample_count - p_chunk->i_sample + 1;
3569 /* Group audio packets so we don't call demux for single sample unit */
3570 if( p_track->fmt.i_original_fourcc == VLC_CODEC_DVD_LPCM &&
3571 p_soun->i_constLPCMframesperaudiopacket &&
3572 p_soun->i_constbytesperaudiopacket )
3574 /* uncompressed case */
3575 uint32_t i_packets = i_max_samples / p_soun->i_constLPCMframesperaudiopacket;
3576 if ( UINT32_MAX / p_soun->i_constbytesperaudiopacket < i_packets )
3577 i_packets = UINT32_MAX / p_soun->i_constbytesperaudiopacket;
3578 *pi_nb_samples = i_packets * p_soun->i_constLPCMframesperaudiopacket;
3579 return i_packets * p_soun->i_constbytesperaudiopacket;
3582 /* all samples have a different size */
3583 if( p_track->i_sample_size == 0 )
3586 return p_track->p_sample_size[p_track->i_sample];
3589 if( p_soun->i_qt_version == 1 )
3591 if ( p_soun->i_compressionid != 0 || p_soun->i_bytes_per_sample > 1 ) /* compressed */
3593 /* in this case we are dealing with compressed data
3594 -2 in V1: additional fields are meaningless (VBR and such) */
3595 *pi_nb_samples = i_max_samples;//p_track->chunk[p_track->i_chunk].i_sample_count;
3596 if( p_track->fmt.audio.i_blockalign > 1 )
3597 *pi_nb_samples = p_soun->i_sample_per_packet;
3598 i_size = *pi_nb_samples / p_soun->i_sample_per_packet * p_soun->i_bytes_per_frame;
3601 else /* uncompressed case */
3604 if( p_track->fmt.audio.i_blockalign > 1 )
3607 i_packets = i_max_samples / p_soun->i_sample_per_packet;
3609 if ( UINT32_MAX / p_soun->i_bytes_per_frame < i_packets )
3610 i_packets = UINT32_MAX / p_soun->i_bytes_per_frame;
3612 *pi_nb_samples = i_packets * p_soun->i_sample_per_packet;
3613 i_size = i_packets * p_soun->i_bytes_per_frame;
3618 /* uncompressed v0 */
3620 for( uint32_t i=p_track->i_sample;
3621 i<p_chunk->i_sample_first+p_chunk->i_sample_count &&
3622 i<p_track->i_sample_count;
3626 if ( p_track->i_sample_size == 0 )
3627 i_size += p_track->p_sample_size[i];
3629 i_size += p_track->i_sample_size;
3630 if ( *pi_nb_samples == QT_V0_MAX_SAMPLES )
3635 //fprintf( stderr, "size=%d\n", i_size );
3639 static uint64_t MP4_TrackGetPos( mp4_track_t *p_track )
3641 unsigned int i_sample;
3644 i_pos = p_track->chunk[p_track->i_chunk].i_offset;
3646 if( p_track->i_sample_size )
3648 MP4_Box_data_sample_soun_t *p_soun =
3649 p_track->p_sample->data.p_sample_soun;
3651 if( p_track->fmt.i_cat != AUDIO_ES || p_soun->i_qt_version == 0 )
3653 i_pos += ( p_track->i_sample -
3654 p_track->chunk[p_track->i_chunk].i_sample_first ) *
3655 p_track->i_sample_size;
3659 /* we read chunk by chunk unless a blockalign is requested */
3660 if( p_track->fmt.audio.i_blockalign > 1 )
3661 i_pos += ( p_track->i_sample - p_track->chunk[p_track->i_chunk].i_sample_first ) /
3662 p_soun->i_sample_per_packet * p_soun->i_bytes_per_frame;
3667 for( i_sample = p_track->chunk[p_track->i_chunk].i_sample_first;
3668 i_sample < p_track->i_sample; i_sample++ )
3670 i_pos += p_track->p_sample_size[i_sample];
3677 static int MP4_TrackNextSample( demux_t *p_demux, mp4_track_t *p_track, uint32_t i_samples )
3679 if ( UINT32_MAX - p_track->i_sample < i_samples )
3681 p_track->i_sample = UINT32_MAX;
3682 return VLC_EGENERIC;
3685 p_track->i_sample += i_samples;
3687 if( p_track->i_sample >= p_track->i_sample_count )
3688 return VLC_EGENERIC;
3690 /* Have we changed chunk ? */
3691 if( p_track->i_sample >=
3692 p_track->chunk[p_track->i_chunk].i_sample_first +
3693 p_track->chunk[p_track->i_chunk].i_sample_count )
3695 if( TrackGotoChunkSample( p_demux, p_track, p_track->i_chunk + 1,
3696 p_track->i_sample ) )
3698 msg_Warn( p_demux, "track[0x%x] will be disabled "
3699 "(cannot restart decoder)", p_track->i_track_ID );
3700 MP4_TrackUnselect( p_demux, p_track );
3701 return VLC_EGENERIC;
3705 /* Have we changed elst */
3706 if( p_track->p_elst && p_track->BOXDATA(p_elst)->i_entry_count > 0 )
3708 demux_sys_t *p_sys = p_demux->p_sys;
3709 MP4_Box_data_elst_t *elst = p_track->BOXDATA(p_elst);
3710 uint64_t i_mvt = MP4_TrackGetDTS( p_demux, p_track ) *
3711 p_sys->i_timescale / CLOCK_FREQ;
3713 if( (unsigned int)p_track->i_elst < elst->i_entry_count &&
3714 i_mvt >= p_track->i_elst_time +
3715 elst->i_segment_duration[p_track->i_elst] )
3717 MP4_TrackSetELST( p_demux, p_track,
3718 MP4_TrackGetDTS( p_demux, p_track ) );
3725 static void MP4_TrackSetELST( demux_t *p_demux, mp4_track_t *tk,
3728 demux_sys_t *p_sys = p_demux->p_sys;
3729 int i_elst_last = tk->i_elst;
3731 /* handle elst (find the correct one) */
3733 tk->i_elst_time = 0;
3734 if( tk->p_elst && tk->BOXDATA(p_elst)->i_entry_count > 0 )
3736 MP4_Box_data_elst_t *elst = tk->BOXDATA(p_elst);
3737 int64_t i_mvt= i_time * p_sys->i_timescale / CLOCK_FREQ;
3739 for( tk->i_elst = 0; (unsigned int)tk->i_elst < elst->i_entry_count; tk->i_elst++ )
3741 mtime_t i_dur = elst->i_segment_duration[tk->i_elst];
3743 if( tk->i_elst_time <= i_mvt && i_mvt < tk->i_elst_time + i_dur )
3747 tk->i_elst_time += i_dur;
3750 if( (unsigned int)tk->i_elst >= elst->i_entry_count )
3752 /* msg_Dbg( p_demux, "invalid number of entry in elst" ); */
3753 tk->i_elst = elst->i_entry_count - 1;
3754 tk->i_elst_time -= elst->i_segment_duration[tk->i_elst];
3757 if( elst->i_media_time[tk->i_elst] < 0 )
3760 tk->i_elst_time += elst->i_segment_duration[tk->i_elst];
3763 if( i_elst_last != tk->i_elst )
3765 msg_Warn( p_demux, "elst old=%d new=%d", i_elst_last, tk->i_elst );
3769 /******************************************************************************
3770 * Here are the functions used for fragmented MP4
3771 *****************************************************************************/
3774 * It computes the sample rate for a video track using current video chunk
3776 static void ChunkGetESSampleRate( unsigned *pi_num, unsigned *pi_den,
3777 const mp4_track_t *p_track )
3779 if( p_track->cchunk->i_last_dts == 0 )
3786 const mp4_chunk_t *p_chunk = p_track->cchunk;
3788 uint32_t i_sample = p_chunk->i_sample_count;
3789 uint64_t i_first_dts = p_chunk->i_first_dts;
3790 uint64_t i_last_dts = p_chunk->i_last_dts;
3792 if( i_sample > 1 && i_first_dts < i_last_dts )
3793 vlc_ureduce( pi_num, pi_den,
3794 ( i_sample - 1) * p_track->i_timescale,
3795 i_last_dts - i_first_dts,
3800 * Build raw avcC box (without the 8 bytes header)
3801 * \return The size of the box.
3803 static int build_raw_avcC( uint8_t **p_extra, const uint8_t *CodecPrivateData,
3804 const unsigned cpd_len )
3807 unsigned sps_len = 0, pps_len = 0;
3808 const uint32_t mark = 0x00000001;
3810 assert( CodecPrivateData[0] == 0 );
3811 assert( CodecPrivateData[1] == 0 );
3812 assert( CodecPrivateData[2] == 0 );
3813 assert( CodecPrivateData[3] == 1 );
3815 uint32_t length = cpd_len + 3;
3816 avcC = calloc( length, 1 );
3817 if( unlikely( avcC == NULL ) )
3820 uint8_t *sps = avcC + 8;
3822 uint32_t candidate = ~mark;
3823 CodecPrivateData += 4;
3824 for( unsigned i = 0; i < cpd_len - 4; i++ )
3826 sps[i] = CodecPrivateData[i];
3827 candidate = (candidate << 8) | CodecPrivateData[i];
3828 if( candidate == mark )
3839 uint8_t *pps = sps + sps_len + 3;
3840 pps_len = cpd_len - sps_len - 4 * 2;
3841 memcpy( pps, CodecPrivateData + sps_len + 4, pps_len );
3844 uint8_t AVCProfileIndication = 0x64;
3845 uint8_t profile_compatibility = 0x40;
3846 uint8_t AVCLevelIndication = 0x1f;
3847 uint8_t lengthSizeMinusOne = 0x03;
3850 avcC[1] = AVCProfileIndication;
3851 avcC[2] = profile_compatibility;
3852 avcC[3] = AVCLevelIndication;
3853 avcC[4] = 0xfc + lengthSizeMinusOne;
3855 avcC[6] = (sps_len & 0xff00)>>8;
3856 avcC[7] = sps_len & 0xff;
3858 avcC[8+sps_len] = 1;
3859 avcC[9+sps_len] = (pps_len & 0xff00) >> 8;
3860 avcC[10+sps_len] = pps_len & 0xff;
3867 * Build a mp4_track_t from a StraBox
3870 static inline int MP4_SetCodecExtraData( es_format_t *fmt, MP4_Box_data_stra_t *p_data )
3872 fmt->i_extra = p_data->cpd_len;
3873 fmt->p_extra = malloc( p_data->cpd_len );
3874 if( unlikely( !fmt->p_extra ) )
3876 memcpy( fmt->p_extra, p_data->CodecPrivateData, p_data->cpd_len );
3880 static int MP4_frg_TrackCreate( demux_t *p_demux, mp4_track_t *p_track, MP4_Box_t *p_stra )
3882 demux_sys_t *p_sys = p_demux->p_sys;
3884 MP4_Box_data_stra_t *p_data = BOXDATA(p_stra);
3886 return VLC_EGENERIC;
3888 p_track->b_ok = true;
3889 p_track->b_selected = false;
3890 p_track->i_sample_count = UINT32_MAX;
3892 p_track->i_timescale = p_sys->i_timescale;
3893 p_track->i_width = p_data->MaxWidth;
3894 p_track->i_height = p_data->MaxHeight;
3895 p_track->i_track_ID = p_data->i_track_ID;
3897 es_format_t *fmt = &p_track->fmt;
3899 return VLC_EGENERIC;
3901 es_format_Init( fmt, p_data->i_es_cat, 0 );
3903 /* Set language FIXME */
3904 fmt->psz_language = strdup( "en" );
3906 fmt->i_original_fourcc = p_data->FourCC;
3907 fmt->i_codec = vlc_fourcc_GetCodec( fmt->i_cat, p_data->FourCC );
3909 uint8_t **p_extra = (uint8_t **)&fmt->p_extra;
3910 /* See http://msdn.microsoft.com/en-us/library/ff728116%28v=vs.90%29.aspx
3911 * for MS weird use of FourCC*/
3912 switch( fmt->i_cat )
3915 if( p_data->FourCC == VLC_FOURCC( 'A', 'V', 'C', '1' ) ||
3916 p_data->FourCC == VLC_FOURCC( 'A', 'V', 'C', 'B' ) ||
3917 p_data->FourCC == VLC_FOURCC( 'H', '2', '6', '4' ) )
3919 fmt->i_extra = build_raw_avcC( p_extra,
3920 p_data->CodecPrivateData, p_data->cpd_len );
3924 ret = MP4_SetCodecExtraData( fmt, p_data );
3925 if( ret != VLC_SUCCESS )
3929 fmt->video.i_width = p_data->MaxWidth;
3930 fmt->video.i_height = p_data->MaxHeight;
3931 fmt->video.i_bits_per_pixel = 0x18;
3932 fmt->video.i_visible_width = p_data->MaxWidth;
3933 fmt->video.i_visible_height = p_data->MaxHeight;
3936 ChunkGetESSampleRate( &fmt->video.i_frame_rate,
3937 &fmt->video.i_frame_rate_base, p_track );
3939 if( fmt->video.i_frame_rate_base != 0 )
3941 p_demux->p_sys->f_fps = (float)fmt->video.i_frame_rate /
3942 (float)fmt->video.i_frame_rate_base;
3945 p_demux->p_sys->f_fps = 24;
3950 fmt->audio.i_channels = p_data->Channels;
3951 fmt->audio.i_rate = p_data->SamplingRate;
3952 fmt->audio.i_bitspersample = p_data->BitsPerSample;
3953 fmt->audio.i_blockalign = p_data->nBlockAlign;
3955 fmt->i_bitrate = p_data->Bitrate;
3957 ret = MP4_SetCodecExtraData( fmt, p_data );
3958 if( ret != VLC_SUCCESS )
3971 * Return the track identified by tid
3973 static mp4_track_t *MP4_frg_GetTrackByID( demux_t *p_demux, const uint32_t tid )
3975 demux_sys_t *p_sys = p_demux->p_sys;
3977 mp4_track_t *ret = NULL;
3978 for( unsigned i = 0; i < p_sys->i_tracks; i++ )
3980 ret = &p_sys->track[i];
3981 if( ret->i_track_ID == tid )
3984 msg_Err( p_demux, "MP4_frg_GetTrack: track %"PRIu32" not found!", tid );
3988 static void FlushChunk( demux_t *p_demux, mp4_track_t *tk )
3990 msg_Dbg( p_demux, "Flushing chunk for track id %u", tk->i_track_ID );
3991 mp4_chunk_t *ck = tk->cchunk;
3992 while( ck->i_sample < ck->i_sample_count )
3997 if( ck->p_sample_size == NULL || ck->p_sample_data == NULL )
4000 uint32_t sample_size = ck->p_sample_size[ck->i_sample];
4001 assert( sample_size > 0 );
4002 p_block = block_Alloc( sample_size );
4003 if( unlikely( !p_block ) )
4006 uint8_t *src = ck->p_sample_data[ck->i_sample];
4007 memcpy( p_block->p_buffer, src, sample_size );
4011 p_block->i_dts = VLC_TS_0 + MP4_TrackGetDTS( p_demux, tk );
4013 i_delta = MP4_TrackGetPTSDelta( p_demux, tk );
4015 p_block->i_pts = p_block->i_dts + i_delta;
4016 else if( tk->fmt.i_cat != VIDEO_ES )
4017 p_block->i_pts = p_block->i_dts;
4019 p_block->i_pts = VLC_TS_INVALID;
4021 MP4_Block_Send( p_demux, tk, p_block );
4029 * \Note If we call that function too soon,
4030 * before the track has been selected by MP4_TrackSelect
4031 * (during the first execution of Demux), then the track gets disabled
4033 static int ReInitDecoder( demux_t *p_demux, mp4_track_t *p_track )
4035 demux_sys_t *p_sys = p_demux->p_sys;
4037 uint32_t i_sample = 0;
4038 bool b_smooth = false;
4039 MP4_Box_t *p_stra = NULL, *p_trak = NULL;
4041 if( !CmpUUID( &p_sys->p_root->p_first->i_uuid, &SmooBoxUUID ) )
4046 p_stra = MP4_BoxGet( p_sys->p_root, "uuid/uuid[0]" );
4047 if( !p_stra || CmpUUID( &p_stra->i_uuid, &StraBoxUUID ) )
4048 return VLC_EGENERIC;
4052 p_trak = MP4_BoxGet( p_sys->p_root, "/moov/trak[0]" );
4054 return VLC_EGENERIC;
4057 i_sample = p_track->i_sample;
4058 es_out_Del( p_demux->out, p_track->p_es );
4059 es_format_Clean( &p_track->fmt );
4062 MP4_frg_TrackCreate( p_demux, p_track, p_stra );
4064 MP4_TrackCreate( p_demux, p_track, p_trak, true );
4066 p_track->i_sample = i_sample;
4068 /* Temporary hack until we support track selection */
4069 p_track->b_selected = true;
4070 p_track->b_ok = true;
4071 p_track->b_enable = true;
4073 p_track->p_es = es_out_Add( p_demux->out, &p_track->fmt );
4074 p_track->b_codec_need_restart = false;
4080 * This function fills a mp4_chunk_t structure from a MP4_Box_t (p_chunk).
4081 * The 'i_tk_id' argument returns the ID of the track the chunk belongs to.
4082 * \note p_chunk usually contains a 'moof' and a 'mdat', and might contain a 'sidx'.
4083 * \return VLC_SUCCESS, VLC_EGENERIC or VLC_ENOMEM.
4085 static int MP4_frg_GetChunk( demux_t *p_demux, MP4_Box_t *p_chunk, unsigned *i_tk_id )
4087 MP4_Box_t *p_sidx = MP4_BoxGet( p_chunk, "sidx" );
4088 MP4_Box_t *p_moof = MP4_BoxGet( p_chunk, "moof" );
4091 msg_Warn( p_demux, "no moof box found!" );
4092 return VLC_EGENERIC;
4095 MP4_Box_t *p_traf = MP4_BoxGet( p_moof, "traf" );
4098 msg_Warn( p_demux, "no traf box found!" );
4099 return VLC_EGENERIC;
4102 MP4_Box_t *p_tfhd = MP4_BoxGet( p_traf, "tfhd" );
4105 msg_Warn( p_demux, "no tfhd box found!" );
4106 return VLC_EGENERIC;
4109 uint32_t i_track_ID = BOXDATA(p_tfhd)->i_track_ID;
4110 *i_tk_id = i_track_ID;
4111 assert( i_track_ID > 0 );
4112 msg_Dbg( p_demux, "GetChunk: track ID is %"PRIu32"", i_track_ID );
4114 mp4_track_t *p_track = MP4_frg_GetTrackByID( p_demux, i_track_ID );
4116 return VLC_EGENERIC;
4118 mp4_chunk_t *ret = p_track->cchunk;
4120 if( BOXDATA(p_tfhd)->b_empty )
4121 msg_Warn( p_demux, "No samples in this chunk!" );
4123 /* Usually we read 100 ms of each track. However, suppose we have two tracks,
4124 * Ta and Tv (audio and video). Suppose also that Ta is the first track to be
4125 * read, i.e. we read 100 ms of Ta, then 100 ms of Tv, then 100 ms of Ta,
4126 * and so on. Finally, suppose that we get the chunks the other way around,
4127 * i.e. first a chunk of Tv, then a chunk of Ta, then a chunk of Tv, and so on.
4128 * In that case, it is very likely that at some point, Ta->cchunk or Tv->cchunk
4129 * is not emptied when MP4_frg_GetChunks is called. It is therefore necessary to
4130 * flush it, i.e. send to the decoder the samples not yet sent.
4131 * Note that all the samples to be flushed should worth less than 100 ms,
4132 * (though I did not do the formal proof) and thus this flushing mechanism
4133 * should not cause A/V sync issues, or delays or whatever.
4135 if( ret->i_sample < ret->i_sample_count )
4136 FlushChunk( p_demux, p_track );
4138 if( ret->i_sample_count )
4139 FreeAndResetChunk( ret );
4141 uint32_t default_duration = 0;
4142 if( BOXDATA(p_tfhd)->i_flags & MP4_TFHD_DFLT_SAMPLE_DURATION )
4143 default_duration = BOXDATA(p_tfhd)->i_default_sample_duration;
4145 uint32_t default_size = 0;
4146 if( BOXDATA(p_tfhd)->i_flags & MP4_TFHD_DFLT_SAMPLE_SIZE )
4147 default_size = BOXDATA(p_tfhd)->i_default_sample_size;
4149 MP4_Box_t *p_trun = MP4_BoxGet( p_traf, "trun");
4152 msg_Warn( p_demux, "no trun box found!" );
4153 return VLC_EGENERIC;
4155 MP4_Box_data_trun_t *p_trun_data = p_trun->data.p_trun;
4157 ret->i_sample_count = p_trun_data->i_sample_count;
4158 assert( ret->i_sample_count > 0 );
4159 ret->i_sample_description_index = 1; /* seems to be always 1, is it? */
4160 ret->i_sample_first = p_track->i_sample_first;
4161 p_track->i_sample_first += ret->i_sample_count;
4163 ret->i_first_dts = p_track->i_first_dts;
4165 /* XXX I already saw DASH content with no default_duration and no
4166 * MP4_TRUN_SAMPLE_DURATION flag, but a sidx box was present.
4167 * This chunk of code might be buggy with segments having
4168 * more than one subsegment. */
4169 if( !default_duration )
4171 MP4_Box_t *p_trex = MP4_GetTrexByTrackID( p_moof, i_track_ID );
4173 default_duration = BOXDATA(p_trex)->i_default_sample_duration;
4176 MP4_Box_data_sidx_t *p_sidx_data = BOXDATA(p_sidx);
4177 assert( p_sidx_data->i_reference_count == 1 );
4179 if( p_sidx_data->i_timescale == 0 )
4180 return VLC_EGENERIC;
4182 unsigned i_chunk_duration = p_sidx_data->p_items[0].i_subsegment_duration /
4183 p_sidx_data->i_timescale;
4184 default_duration = i_chunk_duration * p_track->i_timescale / ret->i_sample_count;
4189 msg_Dbg( p_demux, "Default sample duration is %"PRIu32, default_duration );
4191 ret->p_sample_count_dts = calloc( ret->i_sample_count, sizeof( uint32_t ) );
4192 ret->p_sample_delta_dts = calloc( ret->i_sample_count, sizeof( uint32_t ) );
4194 if( !ret->p_sample_count_dts || !ret->p_sample_delta_dts )
4197 ret->p_sample_count_pts = calloc( ret->i_sample_count, sizeof( uint32_t ) );
4198 if( !ret->p_sample_count_pts )
4201 if( p_trun_data->i_flags & MP4_TRUN_SAMPLE_TIME_OFFSET )
4203 ret->p_sample_offset_pts = calloc( ret->i_sample_count, sizeof( int32_t ) );
4204 if( !ret->p_sample_offset_pts )
4208 ret->p_sample_size = calloc( ret->i_sample_count, sizeof( uint32_t ) );
4209 if( !ret->p_sample_size )
4212 ret->p_sample_data = calloc( ret->i_sample_count, sizeof( uint8_t * ) );
4213 if( !ret->p_sample_data )
4216 uint32_t dur = 0, i_mdatlen = 0, len;
4217 uint32_t chunk_duration = 0, chunk_size = 0;
4219 /* Skip header of mdat */
4221 int i_read = stream_Read( p_demux->s, &mdat, 8 );
4222 i_mdatlen = GetDWBE( mdat );
4223 if ( i_read < 8 || i_mdatlen < 8 ||
4224 VLC_FOURCC( mdat[4], mdat[5], mdat[6], mdat[7] ) != ATOM_mdat )
4225 return VLC_EGENERIC;
4227 for( uint32_t i = 0; i < ret->i_sample_count; i++)
4229 if( p_trun_data->i_flags & MP4_TRUN_SAMPLE_DURATION )
4230 dur = p_trun_data->p_samples[i].i_duration;
4232 dur = default_duration;
4233 ret->p_sample_delta_dts[i] = dur;
4234 chunk_duration += dur;
4236 ret->p_sample_count_dts[i] = ret->p_sample_count_pts[i] = 1;
4238 if( ret->p_sample_offset_pts )
4240 if ( p_trun_data->i_version == 0 )
4241 ret->p_sample_offset_pts[i] = (int32_t) p_trun_data->p_samples[i].i_composition_time_offset;
4243 ret->p_sample_offset_pts[i] = __MIN( INT32_MAX, p_trun_data->p_samples[i].i_composition_time_offset );
4246 if( p_trun_data->i_flags & MP4_TRUN_SAMPLE_SIZE )
4247 len = ret->p_sample_size[i] = p_trun_data->p_samples[i].i_size;
4249 len = ret->p_sample_size[i] = default_size;
4251 if ( chunk_size + len > ( i_mdatlen - 8 ) )
4252 return VLC_EGENERIC;
4254 ret->p_sample_data[i] = malloc( len );
4255 if( ret->p_sample_data[i] == NULL )
4257 uint32_t i_read = stream_ReadU32( p_demux->s, ret->p_sample_data[i], len );
4259 return VLC_EGENERIC;
4262 ret->i_last_dts = ret->i_first_dts + chunk_duration - dur;
4263 p_track->i_first_dts = chunk_duration + ret->i_first_dts;
4265 if( p_track->b_codec_need_restart &&
4266 p_track->fmt.i_cat == VIDEO_ES )
4267 ReInitDecoder( p_demux, p_track );
4269 /* Skip if we didn't reach the end of mdat box */
4270 if ( chunk_size < (i_mdatlen - 8) )
4271 stream_ReadU32( p_demux->s, NULL, i_mdatlen - chunk_size - 8 );
4273 p_track->b_has_non_empty_cchunk = true;
4279 * Get the next chunk of the track identified by i_tk_id.
4280 * \Note We don't want to seek all the time, so if the first chunk given by the
4281 * input method doesn't belong to the right track, we don't throw it away,
4282 * and so, in general, this function fetch more than one chunk.
4283 * Not to mention that a new init fragment might be put everywhere
4284 * between two chunks by the input method.
4286 static int MP4_frg_GetChunks( demux_t *p_demux, const unsigned i_tk_id )
4288 demux_sys_t *p_sys = p_demux->p_sys;
4289 mp4_track_t *p_track;
4291 for( unsigned i = 0; i < p_sys->i_tracks; i++ )
4293 MP4_Box_t *p_chunk = MP4_BoxGetNextChunk( p_demux->s );
4295 return VLC_EGENERIC;
4297 if( !p_chunk->p_first )
4298 goto MP4_frg_GetChunks_Error;
4299 uint32_t i_type = p_chunk->p_first->i_type;
4301 if( i_type == ATOM_uuid || i_type == ATOM_ftyp )
4303 MP4_BoxFree( p_demux->s, p_sys->p_root );
4304 p_sys->p_root = p_chunk;
4306 if( i_type == ATOM_ftyp ) /* DASH */
4308 MP4_Box_t *p_tkhd = MP4_BoxGet( p_chunk, "/moov/trak[0]/tkhd" );
4311 msg_Warn( p_demux, "No tkhd found!" );
4312 goto MP4_frg_GetChunks_Error;
4314 tid = p_tkhd->data.p_tkhd->i_track_ID;
4316 else /* Smooth Streaming */
4318 assert( !CmpUUID( &p_chunk->p_first->i_uuid, &SmooBoxUUID ) );
4319 MP4_Box_t *p_stra = MP4_BoxGet( p_chunk, "/uuid/uuid[0]" );
4320 if( !p_stra || CmpUUID( &p_stra->i_uuid, &StraBoxUUID ) )
4322 msg_Warn( p_demux, "No StraBox found!" );
4323 goto MP4_frg_GetChunks_Error;
4325 tid = p_stra->data.p_stra->i_track_ID;
4328 p_track = MP4_frg_GetTrackByID( p_demux, tid );
4330 goto MP4_frg_GetChunks_Error;
4331 p_track->b_codec_need_restart = true;
4333 return MP4_frg_GetChunks( p_demux, i_tk_id );
4336 if( MP4_frg_GetChunk( p_demux, p_chunk, &tid ) != VLC_SUCCESS )
4337 goto MP4_frg_GetChunks_Error;
4339 MP4_BoxFree( p_demux->s, p_chunk );
4341 if( tid == i_tk_id )
4346 MP4_frg_GetChunks_Error:
4347 MP4_BoxFree( p_demux->s, p_chunk );
4348 return VLC_EGENERIC;
4354 static int MP4_frg_TrackSelect( demux_t *p_demux, mp4_track_t *p_track )
4356 if( !p_track->b_ok || p_track->b_chapter )
4358 return VLC_EGENERIC;
4361 if( p_track->b_selected )
4363 msg_Warn( p_demux, "track[Id 0x%x] already selected", p_track->i_track_ID );
4367 msg_Dbg( p_demux, "Select track id %u", p_track->i_track_ID );
4368 p_track->b_selected = true;
4373 * DemuxFrg: read packet and send them to decoders
4374 * \return 1 on success, 0 on error.
4375 * TODO check for newly selected track
4377 int DemuxFrg( demux_t *p_demux )
4379 demux_sys_t *p_sys = p_demux->p_sys;
4381 unsigned i_track_selected;
4383 /* check for newly selected/unselected track */
4384 for( i_track = 0, i_track_selected = 0; i_track < p_sys->i_tracks; i_track++ )
4386 mp4_track_t *tk = &p_sys->track[i_track];
4389 if( !tk->b_ok || tk->b_chapter )
4392 es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
4393 msg_Dbg( p_demux, "track %u %s!", tk->i_track_ID, b ? "enabled" : "disabled" );
4395 if( tk->b_selected && !b )
4397 MP4_TrackUnselect( p_demux, tk );
4399 else if( !tk->b_selected && b)
4401 MP4_frg_TrackSelect( p_demux, tk );
4404 if( tk->b_selected )
4408 if( i_track_selected <= 0 )
4410 p_sys->i_time += __MAX( p_sys->i_timescale / 10 , 1 );
4411 if( p_sys->i_timescale > 0 )
4413 int64_t i_length = CLOCK_FREQ *
4414 (mtime_t)p_sys->moovfragment.i_duration /
4415 (mtime_t)p_sys->i_timescale;
4416 if( MP4_GetMoviePTS( p_sys ) >= i_length )
4421 msg_Warn( p_demux, "no track selected, exiting..." );
4425 /* first wait for the good time to read a packet */
4426 es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + p_sys->i_pcr );
4428 p_sys->i_pcr = MP4_GetMoviePTS( p_sys );
4430 /* we will read 100ms for each stream so ...*/
4431 p_sys->i_time += __MAX( p_sys->i_timescale / 10, 1 );
4433 for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
4435 mp4_track_t *tk = &p_sys->track[i_track];
4437 if( !tk->b_ok || tk->b_chapter || !tk->b_selected )
4439 msg_Warn( p_demux, "Skipping track id %u", tk->i_track_ID );
4443 if( !tk->b_has_non_empty_cchunk )
4445 if( MP4_frg_GetChunks( p_demux, tk->i_track_ID ) != VLC_SUCCESS )
4447 msg_Info( p_demux, "MP4_frg_GetChunks returned error. End of stream?" );
4452 while( MP4_TrackGetDTS( p_demux, tk ) < MP4_GetMoviePTS( p_sys ) )
4457 mp4_chunk_t *ck = tk->cchunk;
4458 if( ck->i_sample >= ck->i_sample_count )
4460 msg_Err( p_demux, "sample %"PRIu32" of %"PRIu32"",
4461 ck->i_sample, ck->i_sample_count );
4465 uint32_t sample_size = ck->p_sample_size[ck->i_sample];
4466 p_block = block_Alloc( sample_size );
4467 uint8_t *src = ck->p_sample_data[ck->i_sample];
4468 memcpy( p_block->p_buffer, src, sample_size );
4471 if( ck->i_sample == ck->i_sample_count )
4472 tk->b_has_non_empty_cchunk = false;
4475 p_block->i_dts = VLC_TS_0 + MP4_TrackGetDTS( p_demux, tk );
4477 i_delta = MP4_TrackGetPTSDelta( p_demux, tk );
4479 p_block->i_pts = p_block->i_dts + i_delta;
4480 else if( tk->fmt.i_cat != VIDEO_ES )
4481 p_block->i_pts = p_block->i_dts;
4483 p_block->i_pts = VLC_TS_INVALID;
4485 MP4_Block_Send( p_demux, tk, p_block );
4489 if( !tk->b_has_non_empty_cchunk )
4496 static MP4_Box_t * LoadNextChunk( demux_t *p_demux )
4498 /* Read Next Chunk */
4499 MP4_Box_t *p_chunk = MP4_BoxGetNextChunk( p_demux->s );
4502 msg_Warn( p_demux, "no next chunk" );
4506 if( !p_chunk->p_first )
4508 msg_Warn( p_demux, "no next chunk child" );
4515 static bool BoxExistsInRootTree( MP4_Box_t *p_root, uint32_t i_type, off_t i_pos )
4519 if ( p_root->i_pos == i_pos )
4521 assert( i_type == p_root->i_type );
4524 p_root = p_root->p_next;
4526 return (p_root != NULL);
4529 /* Keeps an ordered chain of all fragments */
4530 static bool AddFragment( demux_t *p_demux, MP4_Box_t *p_moox )
4532 demux_sys_t *p_sys = p_demux->p_sys;
4533 mp4_fragment_t *p_base_fragment = & p_sys->moovfragment;
4537 if( p_moox->i_type == ATOM_moov )
4539 if ( !p_sys->moovfragment.p_moox )
4541 p_sys->moovfragment.p_moox = p_moox;
4543 if( (p_mvhd = MP4_BoxGet( p_moox, "mvhd" )) )
4545 p_sys->i_timescale = BOXDATA(p_mvhd)->i_timescale;
4546 p_sys->i_overall_duration = BOXDATA(p_mvhd)->i_duration;
4549 if ( MP4_BoxCount( p_moox, "mvex" ) || !p_mvhd )
4550 { /* duration might be wrong an be set to whole duration :/ */
4551 p_sys->moovfragment.i_duration = 0;
4553 MP4_Box_t *p_trak = MP4_BoxGet( p_moox, "trak" );
4556 if ( p_trak->i_type == ATOM_trak && (p_tkhd = MP4_BoxGet( p_trak, "tkhd" )) )
4558 if ( BOXDATA(p_tkhd)->i_duration > p_sys->moovfragment.i_duration )
4559 p_sys->moovfragment.i_duration = BOXDATA(p_tkhd)->i_duration;
4561 p_trak = p_trak->p_next;
4565 msg_Dbg( p_demux, "added fragment %4.4s", (char*) &p_moox->i_type );
4570 else // p_moox->i_type == ATOM_moof
4572 assert(p_moox->i_type == ATOM_moof);
4573 mp4_fragment_t *p_fragment = p_sys->moovfragment.p_next;
4574 while ( p_fragment )
4576 if ( !p_base_fragment->p_moox || p_moox->i_pos > p_base_fragment->p_moox->i_pos )
4578 p_base_fragment = p_fragment;
4579 p_fragment = p_fragment->p_next;
4581 else if ( p_moox->i_pos == p_base_fragment->p_moox->i_pos )
4583 /* already exists */
4589 /* Add the moof fragment */
4590 mp4_fragment_t *p_new = malloc(sizeof(mp4_fragment_t));
4591 if ( !p_new ) return false;
4592 p_new->p_moox = p_moox;
4593 p_new->i_duration = 0;
4594 p_new->p_next = p_base_fragment->p_next;
4595 p_base_fragment->p_next = p_new;
4596 msg_Dbg( p_demux, "added fragment %4.4s", (char*) &p_moox->i_type );
4598 /* we have to probe all fragments :/ */
4599 uint64_t i_traf_base_data_offset = 0;
4600 uint64_t i_traf_min_offset = 0;
4601 uint32_t i_traf = 0;
4602 uint32_t i_traf_total_size = 0;
4603 uint32_t i_trafs_total_size = 0;
4605 MP4_Box_t *p_traf = MP4_BoxGet( p_new->p_moox, "traf" );
4608 if ( p_traf->i_type != ATOM_traf )
4610 p_traf = p_traf->p_next;
4613 const MP4_Box_t *p_tfhd = MP4_BoxGet( p_traf, "tfhd" );
4614 const MP4_Box_t *p_trun = MP4_BoxGet( p_traf, "trun" );
4615 if ( !p_tfhd || !p_trun )
4617 p_traf = p_traf->p_next;
4621 uint32_t i_track_timescale = 0;
4622 uint32_t i_track_defaultsamplesize = 0;
4623 uint32_t i_track_defaultsampleduration = 0;
4624 if ( p_sys->b_smooth )
4626 /* stra sets identical timescales */
4627 i_track_timescale = p_sys->i_timescale;
4628 i_track_defaultsamplesize = 1;
4629 i_track_defaultsampleduration = 1;
4633 /* set trex for defaults */
4634 MP4_Box_t *p_trex = MP4_GetTrexByTrackID( p_sys->moovfragment.p_moox, BOXDATA(p_tfhd)->i_track_ID );
4637 i_track_defaultsamplesize = BOXDATA(p_trex)->i_default_sample_size;
4638 i_track_defaultsampleduration = BOXDATA(p_trex)->i_default_sample_duration;
4641 MP4_Box_t *p_trak = MP4_GetTrakByTrackID( p_sys->moovfragment.p_moox, BOXDATA(p_tfhd)->i_track_ID );
4644 MP4_Box_t *p_mdhd = MP4_BoxGet( p_trak, "mdia/mdhd" );
4645 if ( p_mdhd ) i_track_timescale = BOXDATA(p_mdhd)->i_timescale;
4649 if ( !i_track_timescale )
4651 p_traf = p_traf->p_next;
4655 if ( BOXDATA(p_tfhd)->i_flags & MP4_TFHD_BASE_DATA_OFFSET )
4657 i_traf_base_data_offset = BOXDATA(p_tfhd)->i_base_data_offset;
4659 else if ( BOXDATA(p_tfhd)->i_flags & MP4_TFHD_DEFAULT_BASE_IS_MOOF )
4661 i_traf_base_data_offset = p_new->p_moox->i_pos /* + 8*/;
4666 i_traf_base_data_offset = p_new->p_moox->i_pos /*+ 8*/;
4668 i_traf_base_data_offset += i_traf_total_size;
4671 i_traf_total_size = 0;
4673 uint64_t i_trun_data_offset = i_traf_base_data_offset;
4674 uint64_t i_traf_duration = 0;
4675 uint32_t i_trun_size = 0;
4676 while ( p_trun && p_tfhd )
4678 if ( p_trun->i_type != ATOM_trun )
4680 p_trun = p_trun->p_next;
4683 const MP4_Box_data_trun_t *p_trundata = p_trun->data.p_trun;
4685 /* Get data offset */
4686 if ( p_trundata->i_flags & MP4_TRUN_DATA_OFFSET )
4687 i_trun_data_offset += __MAX( p_trundata->i_data_offset, 0 );
4689 i_trun_data_offset += i_trun_size;
4693 /* Sum total time */
4694 if ( p_trundata->i_flags & MP4_TRUN_SAMPLE_DURATION )
4696 for( uint32_t i=0; i< p_trundata->i_sample_count; i++ )
4697 i_traf_duration += p_trundata->p_samples[i].i_duration;
4699 else if ( BOXDATA(p_tfhd)->i_flags & MP4_TFHD_DFLT_SAMPLE_DURATION )
4701 i_traf_duration += p_trundata->i_sample_count *
4702 BOXDATA(p_tfhd)->i_default_sample_duration;
4706 i_traf_duration += p_trundata->i_sample_count *
4707 i_track_defaultsampleduration;
4710 /* Get total traf size */
4711 if ( p_trundata->i_flags & MP4_TRUN_SAMPLE_SIZE )
4713 for( uint32_t i=0; i< p_trundata->i_sample_count; i++ )
4714 i_trun_size += p_trundata->p_samples[i].i_size;
4716 else if ( BOXDATA(p_tfhd)->i_flags & MP4_TFHD_DFLT_SAMPLE_SIZE )
4718 i_trun_size += p_trundata->i_sample_count *
4719 BOXDATA(p_tfhd)->i_default_sample_size;
4723 i_trun_size += p_trundata->i_sample_count *
4724 i_track_defaultsamplesize;
4727 i_traf_total_size += i_trun_size;
4729 if ( i_traf_min_offset )
4730 i_traf_min_offset = __MIN( i_trun_data_offset, i_traf_min_offset );
4732 i_traf_min_offset = i_trun_data_offset;
4734 p_trun = p_trun->p_next;
4737 i_trafs_total_size += i_traf_total_size;
4738 p_new->i_duration = __MAX( p_new->i_duration, i_traf_duration * p_sys->i_timescale / i_track_timescale );
4740 p_traf = p_traf->p_next;
4744 p_new->i_chunk_range_min_offset = i_traf_min_offset;
4745 p_new->i_chunk_range_max_offset = i_traf_min_offset + i_trafs_total_size;
4747 msg_Dbg( p_demux, "new fragment is %"PRId64" %"PRId64, p_new->i_chunk_range_min_offset, p_new->i_chunk_range_max_offset );
4749 /* compute total duration with that new fragment if no overall provided */
4750 MP4_Box_t *p_mehd = MP4_BoxGet( p_sys->moovfragment.p_moox, "mvex/mehd");
4753 p_sys->i_overall_duration = 0;
4754 if ( p_sys->b_fragments_probed )
4756 p_new = &p_sys->moovfragment;
4759 p_sys->i_overall_duration += p_new->i_duration;
4760 p_new = p_new->p_next;
4765 p_sys->i_overall_duration = BOXDATA(p_mehd)->i_fragment_duration;
4767 msg_Dbg( p_demux, "total fragments duration %"PRId64, CLOCK_FREQ * p_sys->i_overall_duration / p_sys->i_timescale);
4771 static int ProbeIndex( demux_t *p_demux )
4773 demux_sys_t *p_sys = p_demux->p_sys;
4774 uint64_t i_backup_pos, i_stream_size;
4775 uint8_t mfro[MP4_MFRO_BOXSIZE];
4776 assert( p_sys->b_seekable );
4778 if ( MP4_BoxCount( p_sys->p_root, "/mfra" ) )
4781 i_stream_size = stream_Size( p_demux->s );
4782 if ( ( i_stream_size >> 62 ) ||
4783 ( i_stream_size < MP4_MFRO_BOXSIZE ) ||
4784 ( !MP4_stream_Tell( p_demux->s, &i_backup_pos ) ) ||
4785 ( stream_Seek( p_demux->s, i_stream_size - MP4_MFRO_BOXSIZE ) != VLC_SUCCESS )
4788 msg_Dbg( p_demux, "Probing tail for mfro has failed" );
4789 return VLC_EGENERIC;
4792 if ( stream_Read( p_demux->s, &mfro, MP4_MFRO_BOXSIZE ) == MP4_MFRO_BOXSIZE &&
4793 VLC_FOURCC(mfro[4],mfro[5],mfro[6],mfro[7]) == ATOM_mfro &&
4794 GetDWBE( &mfro ) == MP4_MFRO_BOXSIZE )
4796 uint32_t i_offset = GetDWBE( &mfro[12] );
4797 msg_Dbg( p_demux, "will read mfra index at %"PRIu64, i_stream_size - i_offset );
4798 if ( i_stream_size > i_offset &&
4799 stream_Seek( p_demux->s, i_stream_size - i_offset ) == VLC_SUCCESS )
4801 msg_Dbg( p_demux, "reading mfra index at %"PRIu64, i_stream_size - i_offset );
4802 MP4_ReadBoxContainerChildren( p_demux->s, p_sys->p_root, ATOM_mfra );
4806 return stream_Seek( p_demux->s, i_backup_pos );
4809 static int ProbeFragments( demux_t *p_demux, bool b_force )
4811 demux_sys_t *p_sys = p_demux->p_sys;
4812 uint64_t i_current_pos;
4814 if ( MP4_stream_Tell( p_demux->s, &i_current_pos ) )
4815 msg_Dbg( p_demux, "probing fragments from %"PRId64, i_current_pos );
4817 assert( p_sys->p_root );
4819 if ( p_sys->b_fastseekable || b_force )
4821 MP4_ReadBoxContainerChildren( p_demux->s, p_sys->p_root, 0 ); /* Get the rest of the file */
4822 p_sys->b_fragments_probed = true;
4826 /* We stop at first moof, which validates our fragmentation condition
4827 * and we'll find others while reading. */
4828 MP4_ReadBoxContainerChildren( p_demux->s, p_sys->p_root, ATOM_moof );
4831 if ( !p_sys->moovfragment.p_moox )
4833 MP4_Box_t *p_moov = MP4_BoxGet( p_sys->p_root, "/moov" );
4836 /* moov/mvex before probing should be present anyway */
4837 MP4_BoxDumpStructure( p_demux->s, p_sys->p_root );
4838 return VLC_EGENERIC;
4840 AddFragment( p_demux, p_moov );
4843 MP4_Box_t *p_moof = MP4_BoxGet( p_sys->p_root, "moof" );
4846 if ( p_moof->i_type == ATOM_moof )
4847 AddFragment( p_demux, p_moof );
4848 p_moof = p_moof->p_next;
4851 MP4_Box_t *p_mdat = MP4_BoxGet( p_sys->p_root, "mdat" );
4854 stream_Seek( p_demux->s, p_mdat->i_pos );
4855 msg_Dbg( p_demux, "rewinding to mdat %"PRId64, p_mdat->i_pos );
4861 static mp4_fragment_t * GetFragmentByPos( demux_t *p_demux, uint64_t i_pos, bool b_exact )
4863 mp4_fragment_t *p_fragment = &p_demux->p_sys->moovfragment;
4864 while ( p_fragment )
4866 if ( i_pos <= p_fragment->i_chunk_range_max_offset &&
4867 ( !b_exact || i_pos >= p_fragment->i_chunk_range_min_offset ) )
4869 msg_Dbg( p_demux, "fragment matched %"PRIu64" << %"PRIu64" << %"PRIu64,
4870 p_fragment->i_chunk_range_min_offset, i_pos,
4871 p_fragment->i_chunk_range_max_offset );
4876 p_fragment = p_fragment->p_next;
4882 /* Get a matching fragment data start by clock time */
4883 static mp4_fragment_t * GetFragmentByTime( demux_t *p_demux, const mtime_t i_time )
4885 mp4_fragment_t *p_fragment = &p_demux->p_sys->moovfragment;
4886 mtime_t i_base_time = 0;
4887 while ( p_fragment )
4889 mtime_t i_length = CLOCK_FREQ * p_fragment->i_duration / p_demux->p_sys->i_timescale;
4890 if ( i_time >= i_base_time &&
4891 i_time <= i_base_time + i_length )
4897 i_base_time += i_length;
4898 p_fragment = p_fragment->p_next;
4901 if ( !p_demux->p_sys->b_fragments_probed )
4902 return NULL; /* We have no way to guess missing fragments time */
4907 /* Returns fragment scaled time offset */
4908 static mtime_t LeafGetFragmentTimeOffset( demux_t *p_demux, mp4_fragment_t *p_fragment )
4910 mtime_t i_base_scaledtime = 0;
4911 mp4_fragment_t *p_current = &p_demux->p_sys->moovfragment;
4912 while ( p_current != p_fragment )
4914 i_base_scaledtime += p_current->i_duration;
4915 p_current = p_current->p_next;
4917 return i_base_scaledtime;
4920 static int LeafParseTRUN( demux_t *p_demux, mp4_track_t *p_track,
4921 const uint32_t i_defaultduration, const uint32_t i_defaultsize,
4922 const MP4_Box_data_trun_t *p_trun, uint32_t * const pi_mdatlen )
4924 assert( p_trun->i_sample_count );
4925 msg_Dbg( p_demux, "Default sample duration %"PRIu32" size %"PRIu32" firstdts %"PRIu64,
4926 i_defaultduration, i_defaultsize, p_track->i_first_dts );
4928 uint32_t dur = 0, len;
4929 uint32_t chunk_size = 0;
4930 mtime_t i_nzdts = CLOCK_FREQ * p_track->i_time / p_track->i_timescale;
4934 for( uint32_t i = 0; i < p_trun->i_sample_count; i++)
4936 i_nzdts += CLOCK_FREQ * dur / p_track->i_timescale;
4939 if( p_trun->i_flags & MP4_TRUN_SAMPLE_DURATION )
4940 dur = p_trun->p_samples[i].i_duration;
4942 dur = i_defaultduration;
4944 p_track->i_time += dur;
4946 if( p_trun->i_flags & MP4_TRUN_SAMPLE_TIME_OFFSET )
4948 if ( p_trun->i_version == 0 )
4949 i_nzpts += CLOCK_FREQ * (int32_t) p_trun->p_samples[i].i_composition_time_offset / p_track->i_timescale;
4951 i_nzpts += CLOCK_FREQ * p_trun->p_samples[i].i_composition_time_offset / p_track->i_timescale;
4954 if( p_trun->i_flags & MP4_TRUN_SAMPLE_SIZE )
4955 len = p_trun->p_samples[i].i_size;
4957 len = i_defaultsize;
4959 assert( dur ); /* dur, dur ! */
4962 if ( chunk_size + len > *pi_mdatlen )
4964 /* update data left in mdat */
4965 *pi_mdatlen -= chunk_size;
4966 return VLC_EGENERIC;
4969 block_t *p_block = MP4_Block_Read( p_demux, p_track, __MIN( len, INT32_MAX ) );
4970 uint32_t i_read = ( p_block ) ? p_block->i_buffer : 0;
4973 /* update data left in mdat */
4974 *pi_mdatlen -= chunk_size;
4975 *pi_mdatlen -= i_read;
4977 return VLC_EGENERIC;
4980 if ( p_demux->p_sys->i_pcr < VLC_TS_0 )
4982 p_demux->p_sys->i_pcr = i_nzdts;
4983 es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + i_nzdts );
4986 if ( p_track->p_es )
4988 p_block->i_dts = VLC_TS_0 + i_nzdts;
4989 p_block->i_pts = VLC_TS_0 + i_nzpts;
4990 p_block->i_length = CLOCK_FREQ * dur / p_track->i_timescale;
4991 MP4_Block_Send( p_demux, p_track, p_block );
4993 else free( p_block );
4998 /* update data left in mdat */
4999 *pi_mdatlen -= chunk_size;
5003 static int LeafGetTrackAndChunkByMOOVPos( demux_t *p_demux, uint64_t *pi_pos,
5004 mp4_track_t **pp_tk, unsigned int *pi_chunk )
5006 const demux_sys_t *p_sys = p_demux->p_sys;
5008 mp4_track_t *p_tk_closest = NULL;
5009 uint64_t i_closest = UINT64_MAX;
5010 unsigned int i_chunk_closest;
5014 for ( unsigned int i_track = 0; i_track < p_sys->i_tracks; i_track++ )
5016 for( unsigned int i_chunk = 0; i_chunk < p_sys->track[i_track].i_chunk_count; i_chunk++ )
5018 if ( p_sys->track[i_track].chunk[i_chunk].i_offset > *pi_pos )
5020 i_closest = __MIN( i_closest, p_sys->track[i_track].chunk[i_chunk].i_offset );
5021 p_tk_closest = &p_sys->track[i_track];
5022 i_chunk_closest = i_chunk;
5025 if ( *pi_pos == p_sys->track[i_track].chunk[i_chunk].i_offset )
5027 *pp_tk = &p_sys->track[i_track];
5028 *pi_chunk = i_chunk;
5034 if ( i_closest != UINT64_MAX )
5036 *pi_pos = i_closest;
5037 *pp_tk = p_tk_closest;
5038 *pi_chunk = i_chunk_closest;
5041 else return VLC_EGENERIC;
5044 static int LeafMOOVGetSamplesSize( const mp4_track_t *p_track, const uint32_t i_sample,
5045 uint32_t *pi_samplestoread, uint32_t *pi_samplessize,
5046 const uint32_t i_maxbytes, const uint32_t i_maxsamples )
5048 MP4_Box_t *p_stsz = MP4_BoxGet( p_track->p_stbl, "stsz" );
5050 return VLC_EGENERIC;
5052 if ( BOXDATA(p_stsz)->i_sample_size == 0 )
5054 uint32_t i_entry = i_sample;
5055 uint32_t i_totalbytes = 0;
5056 *pi_samplestoread = 1;
5058 if ( i_sample >= BOXDATA(p_stsz)->i_sample_count )
5059 return VLC_EGENERIC;
5061 *pi_samplessize = BOXDATA(p_stsz)->i_entry_size[i_sample];
5062 i_totalbytes += *pi_samplessize;
5064 if ( *pi_samplessize > i_maxbytes )
5065 return VLC_EGENERIC;
5068 while( i_entry < BOXDATA(p_stsz)->i_sample_count &&
5069 *pi_samplessize == BOXDATA(p_stsz)->i_entry_size[i_entry] &&
5070 i_totalbytes + *pi_samplessize < i_maxbytes &&
5071 *pi_samplestoread < i_maxsamples
5074 i_totalbytes += *pi_samplessize;
5075 (*pi_samplestoread)++;
5078 *pi_samplessize = i_totalbytes;
5082 /* all samples have same size */
5083 *pi_samplessize = BOXDATA(p_stsz)->i_sample_size;
5084 *pi_samplestoread = __MIN( i_maxsamples, BOXDATA(p_stsz)->i_sample_count );
5085 *pi_samplestoread = __MIN( i_maxbytes / *pi_samplessize, *pi_samplestoread );
5086 *pi_samplessize = *pi_samplessize * *pi_samplestoread;
5092 static inline mtime_t LeafGetMOOVTimeInChunk( const mp4_chunk_t *p_chunk, uint32_t i_sample )
5095 uint32_t i_index = 0;
5097 while( i_sample > 0 )
5099 if( i_sample > p_chunk->p_sample_count_dts[i_index] )
5101 i_time += p_chunk->p_sample_count_dts[i_index] *
5102 p_chunk->p_sample_delta_dts[i_index];
5103 i_sample -= p_chunk->p_sample_count_dts[i_index];
5108 i_time += i_sample * p_chunk->p_sample_delta_dts[i_index];
5116 static int LeafParseMDATwithMOOV( demux_t *p_demux )
5118 demux_sys_t *p_sys = p_demux->p_sys;
5120 assert( p_sys->context.i_current_box_type == ATOM_mdat );
5121 assert( p_sys->context.p_fragment->p_moox->i_type == ATOM_moov );
5123 uint64_t i_current_pos;
5124 if ( !MP4_stream_Tell( p_demux->s, &i_current_pos ) )
5125 return VLC_EGENERIC;
5127 if ( p_sys->context.i_mdatbytesleft == 0 ) /* Start parsing new mdat */
5129 /* Ready mdat section */
5131 int i_read = stream_Read( p_demux->s, &mdat, 8 );
5132 p_sys->context.i_mdatbytesleft = GetDWBE( mdat );
5133 if ( i_read < 8 || p_sys->context.i_mdatbytesleft < 8 ||
5134 VLC_FOURCC( mdat[4], mdat[5], mdat[6], mdat[7] ) != ATOM_mdat )
5137 if ( !MP4_stream_Tell( p_demux->s, &i_pos ) )
5138 msg_Err( p_demux, "No mdat atom at %"PRIu64, i_pos - __MAX( 0, i_read ) );
5139 return VLC_EGENERIC;
5142 p_sys->context.i_mdatbytesleft -= 8;
5145 while( p_sys->context.i_mdatbytesleft > 0 )
5147 mp4_track_t *p_track;
5148 unsigned int i_chunk;
5151 uint64_t i_pos = i_current_pos;
5152 int i_ret = LeafGetTrackAndChunkByMOOVPos( p_demux, &i_pos, &p_track, &i_chunk );
5153 if ( i_ret == VLC_EGENERIC )
5155 msg_Err(p_demux, "can't find referenced chunk for start at %"PRIu64, i_current_pos );
5158 else if( i_ret == VLC_ENOOBJ )
5160 assert( i_pos - i_current_pos > p_sys->context.i_mdatbytesleft );
5161 int i_read = stream_Read( p_demux->s, NULL, i_pos - i_current_pos );
5162 i_current_pos += i_read;
5163 p_sys->context.i_mdatbytesleft -= i_read;
5164 if ( i_read == 0 ) goto error;
5169 mp4_chunk_t *p_chunk = &p_track->chunk[i_chunk];
5171 uint32_t i_nb_samples_at_chunk_start = p_chunk->i_sample_first;
5172 uint32_t i_nb_samples_in_chunk = p_chunk->i_sample_count;
5174 assert(i_nb_samples_in_chunk);
5176 uint32_t i_nb_samples = 0;
5177 while ( i_nb_samples < i_nb_samples_in_chunk )
5179 uint32_t i_samplessize = 0;
5180 uint32_t i_samplescounttoread = 0;
5181 i_ret = LeafMOOVGetSamplesSize( p_track,
5182 i_nb_samples_at_chunk_start + i_nb_samples,
5183 &i_samplescounttoread, &i_samplessize,
5184 p_sys->context.i_mdatbytesleft,
5185 /*i_nb_samples_in_chunk - i_nb_samples*/ 1 );
5186 if ( i_ret != VLC_SUCCESS )
5189 if( p_sys->context.i_mdatbytesleft &&
5190 p_sys->context.i_mdatbytesleft >= i_samplessize )
5196 if( !(p_block = MP4_Block_Read( p_demux, p_track, i_samplessize )) )
5199 if ( MP4_stream_Tell( p_demux->s, &i_pos ) )
5201 p_sys->context.i_mdatbytesleft -= ( i_pos - i_current_pos );
5202 msg_Err( p_demux, "stream block error %"PRId64" %"PRId64, i_pos, i_pos - i_current_pos );
5207 i_nb_samples += i_samplescounttoread;
5208 i_current_pos += i_samplessize;
5209 p_sys->context.i_mdatbytesleft -= i_samplessize;
5212 mtime_t i_time = LeafGetMOOVTimeInChunk( p_chunk, i_nb_samples );
5213 i_time += p_chunk->i_first_dts;
5214 p_track->i_time = i_time;
5215 p_block->i_dts = VLC_TS_0 + CLOCK_FREQ * i_time / p_track->i_timescale;
5218 int64_t i_delta = MP4_TrackGetPTSDelta( p_demux, p_track );
5220 p_block->i_pts = p_block->i_dts + i_delta;
5221 else if( p_track->fmt.i_cat != VIDEO_ES )
5222 p_block->i_pts = p_block->i_dts;
5224 p_block->i_pts = VLC_TS_INVALID;
5226 MP4_Block_Send( p_demux, p_track, p_block );
5228 if ( p_demux->p_sys->i_pcr < VLC_TS_0 )
5230 p_sys->i_time = p_track->i_time * p_sys->i_timescale / p_track->i_timescale;
5231 p_demux->p_sys->i_pcr = MP4_GetMoviePTS( p_demux->p_sys );
5232 es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + p_demux->p_sys->i_pcr );
5238 // sample size > left bytes
5242 p_track->i_sample += i_samplescounttoread;
5245 /* flag end of mdat section if needed */
5246 if ( p_sys->context.i_mdatbytesleft == 0 )
5247 p_sys->context.i_current_box_type = 0;
5254 /* Skip if we didn't reach the end of mdat box */
5255 if ( p_sys->context.i_mdatbytesleft > 0 )
5257 msg_Err( p_demux, "mdat had still %"PRIu32" bytes unparsed as samples",
5258 p_sys->context.i_mdatbytesleft );
5259 stream_ReadU32( p_demux->s, NULL, p_sys->context.i_mdatbytesleft );
5261 p_sys->context.i_current_box_type = 0;
5266 static mp4_track_t * LeafGetTrackByTrunPos( demux_t *p_demux, const uint64_t i_pos, const uint64_t i_moofpos )
5268 demux_sys_t *p_sys = p_demux->p_sys;
5270 for ( uint32_t i=0; i<p_sys->i_tracks; i++ )
5272 mp4_track_t *p_track = &p_sys->track[i];
5273 if ( !p_track->context.p_trun || !p_track->context.p_tfhd )
5275 const MP4_Box_data_trun_t *p_trun_data = p_track->context.BOXDATA(p_trun);
5276 uint64_t i_offset = 0;
5278 if ( p_track->context.BOXDATA(p_tfhd)->i_flags & MP4_TFHD_BASE_DATA_OFFSET )
5279 i_offset = p_track->context.BOXDATA(p_tfhd)->i_base_data_offset;
5281 i_offset = i_moofpos;
5283 //if ( p_track->context.BOXDATA(p_tfhd)->i_flags & MP4_TFHD_DEFAULT_BASE_IS_MOOF )
5284 // i_offset += i_moofpos;
5286 if (p_trun_data->i_flags & MP4_TRUN_DATA_OFFSET)
5287 i_offset += p_trun_data->i_data_offset;
5291 if ( i_offset == i_pos )
5298 static int LeafMapTrafTrunContextes( demux_t *p_demux, MP4_Box_t *p_moof )
5300 demux_sys_t *p_sys = p_demux->p_sys;
5303 for ( uint32_t i=0; i<p_sys->i_tracks; i++ )
5305 mp4_track_t *p_track = &p_sys->track[i];
5306 p_track->context.p_tfhd = NULL;
5307 p_track->context.p_traf = NULL;
5308 p_track->context.p_trun = NULL;
5311 if ( p_moof->i_type == ATOM_moov )
5314 MP4_Box_t *p_traf = MP4_BoxGet( p_moof, "traf" );
5317 msg_Warn( p_demux, "no traf box found!" );
5318 return VLC_EGENERIC;
5324 if ( p_traf->i_type == ATOM_traf )
5326 MP4_Box_t *p_tfhd = MP4_BoxGet( p_traf, "tfhd" );
5327 for ( uint32_t i=0; p_tfhd && i<p_sys->i_tracks; i++ )
5329 mp4_track_t *p_track = &p_sys->track[i];
5330 if ( BOXDATA(p_tfhd)->i_track_ID == p_track->i_track_ID )
5332 MP4_Box_t *p_trun = MP4_BoxGet( p_traf, "trun" );
5335 p_track->context.p_tfhd = p_tfhd;
5336 p_track->context.p_traf = p_traf;
5337 p_track->context.p_trun = p_trun;
5339 p_tfhd = NULL; /* break loop */
5343 p_traf = p_traf->p_next;
5349 static int LeafIndexGetMoofPosByTime( demux_t *p_demux, const mtime_t i_target_time,
5350 uint64_t *pi_pos, mtime_t *pi_mooftime )
5352 MP4_Box_t *p_tfra = MP4_BoxGet( p_demux->p_sys->p_root, "mfra/tfra" );
5355 if ( p_tfra->i_type == ATOM_tfra )
5358 const MP4_Box_data_tfra_t *p_data = BOXDATA(p_tfra);
5359 mp4_track_t *p_track = MP4_frg_GetTrackByID( p_demux, p_data->i_track_ID );
5360 if ( p_track && (p_track->fmt.i_cat == AUDIO_ES || p_track->fmt.i_cat == VIDEO_ES) )
5362 for ( uint32_t i = 0; i<p_data->i_number_of_entries; i += ( p_data->i_version == 1 ) ? 2 : 1 )
5366 if ( p_data->i_version == 1 )
5368 i_time = *((uint64_t *)(p_data->p_time + i));
5369 i_offset = *((uint64_t *)(p_data->p_moof_offset + i));
5373 i_time = p_data->p_time[i];
5374 i_offset = p_data->p_moof_offset[i];
5377 if ( CLOCK_FREQ * i_time / p_track->i_timescale >= i_target_time )
5379 if ( i_pos == -1 ) /* Not in this traf */
5382 *pi_pos = (uint64_t) i_pos;
5383 *pi_mooftime = CLOCK_FREQ * i_time / p_track->i_timescale;
5384 if ( p_track->fmt.i_cat == AUDIO_ES )
5385 *pi_mooftime -= CLOCK_FREQ / p_track->fmt.audio.i_rate * p_data->p_sample_number[i];
5387 *pi_mooftime -= CLOCK_FREQ / p_demux->p_sys->f_fps * p_data->p_sample_number[i];
5395 p_tfra = p_tfra->p_next;
5397 return VLC_EGENERIC;
5400 static int LeafParseMDATwithMOOF( demux_t *p_demux, MP4_Box_t *p_moof )
5402 demux_sys_t *p_sys = p_demux->p_sys;
5404 assert( p_moof->i_type == ATOM_moof );
5405 assert( p_sys->context.i_current_box_type == ATOM_mdat );
5407 if ( p_sys->context.i_mdatbytesleft == 0 )
5409 int i_ret = LeafMapTrafTrunContextes( p_demux, p_moof );
5410 if ( i_ret != VLC_SUCCESS )
5413 /* Ready mdat section */
5415 int i_read = stream_Read( p_demux->s, &mdat, 8 );
5416 p_sys->context.i_mdatbytesleft = GetDWBE( mdat );
5417 if ( i_read < 8 || p_sys->context.i_mdatbytesleft < 8 ||
5418 VLC_FOURCC( mdat[4], mdat[5], mdat[6], mdat[7] ) != ATOM_mdat )
5420 if ( MP4_stream_Tell( p_demux->s, &i_pos ) )
5421 msg_Err(p_demux, "No mdat atom at %"PRIu64, i_pos - i_read );
5422 return VLC_EGENERIC;
5424 p_sys->context.i_mdatbytesleft -= 8;
5427 if ( !MP4_stream_Tell( p_demux->s, &i_pos ) )
5428 return VLC_EGENERIC;
5429 if ( p_sys->b_smooth )
5430 i_pos -= p_moof->i_pos;
5431 mp4_track_t *p_track = LeafGetTrackByTrunPos( p_demux, i_pos, p_moof->i_pos );
5434 MP4_Box_data_tfhd_t *p_tfhd_data = p_track->context.BOXDATA(p_tfhd);
5435 uint32_t i_trun_sample_default_duration = 0;
5436 uint32_t i_trun_sample_default_size = 0;
5438 if ( p_track->context.p_trun )
5440 /* Get defaults for this/these RUN */
5441 if( p_tfhd_data->i_flags & MP4_TFHD_DFLT_SAMPLE_DURATION )
5442 i_trun_sample_default_duration = p_tfhd_data->i_default_sample_duration;
5444 if( p_tfhd_data->i_flags & MP4_TFHD_DFLT_SAMPLE_SIZE )
5445 i_trun_sample_default_size = p_tfhd_data->i_default_sample_size;
5447 if( !i_trun_sample_default_duration || !i_trun_sample_default_size )
5449 MP4_Box_t *p_trex = MP4_BoxGet( p_demux->p_sys->p_root, "moov/mvex/trex");
5452 while( p_trex && BOXDATA(p_trex)->i_track_ID != p_tfhd_data->i_track_ID )
5453 p_trex = p_trex->p_next;
5454 if ( p_trex && !i_trun_sample_default_duration )
5455 i_trun_sample_default_duration = BOXDATA(p_trex)->i_default_sample_duration;
5456 if ( p_trex && !i_trun_sample_default_size )
5457 i_trun_sample_default_size = BOXDATA(p_trex)->i_default_sample_size;
5461 const MP4_Box_data_trun_t *p_trun_data = p_track->context.BOXDATA(p_trun);
5463 /* NOW PARSE TRUN WITH MDAT */
5464 int i_ret = LeafParseTRUN( p_demux, p_track,
5465 i_trun_sample_default_duration, i_trun_sample_default_size,
5466 p_trun_data, & p_sys->context.i_mdatbytesleft );
5467 if ( i_ret != VLC_SUCCESS )
5470 p_track->context.p_trun = p_track->context.p_trun->p_next;
5473 if ( p_sys->context.i_mdatbytesleft == 0 )
5474 p_sys->context.i_current_box_type = 0;
5479 /* Skip if we didn't reach the end of mdat box */
5480 if ( p_sys->context.i_mdatbytesleft > 0 )
5482 msg_Warn( p_demux, "mdat had still %"PRIu32" bytes unparsed as samples", p_sys->context.i_mdatbytesleft - 8 );
5483 stream_ReadU32( p_demux->s, NULL, p_sys->context.i_mdatbytesleft );
5486 p_sys->context.i_current_box_type = 0;
5491 static int DemuxAsLeaf( demux_t *p_demux )
5493 demux_sys_t *p_sys = p_demux->p_sys;
5494 unsigned i_track_selected = 0;
5496 /* check for newly selected/unselected track */
5497 for( unsigned i_track = 0; i_track < p_sys->i_tracks; i_track++ )
5499 mp4_track_t *tk = &p_sys->track[i_track];
5502 if( !tk->b_ok || tk->b_chapter )
5505 es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
5506 msg_Dbg( p_demux, "track %u %s!", tk->i_track_ID, b ? "enabled" : "disabled" );
5508 if( tk->b_selected && !b )
5509 MP4_TrackUnselect( p_demux, tk );
5510 else if( !tk->b_selected && b)
5511 MP4_frg_TrackSelect( p_demux, tk );
5513 if( tk->b_selected )
5517 if( i_track_selected <= 0 )
5519 msg_Warn( p_demux, "no track selected, exiting..." );
5523 if ( p_sys->context.i_current_box_type != ATOM_mdat )
5525 /* Othewise mdat is skipped. FIXME: mdat reading ! */
5526 const uint8_t *p_peek;
5527 int i_read = stream_Peek( p_demux->s, &p_peek, 8 );
5531 p_sys->context.i_current_box_type = VLC_FOURCC( p_peek[4], p_peek[5], p_peek[6], p_peek[7] );
5533 if ( p_sys->context.i_current_box_type != ATOM_mdat )
5535 if ( ! BoxExistsInRootTree( p_sys->p_root, p_sys->context.i_current_box_type, stream_Tell( p_demux->s ) ) )
5536 {// only if !b_probed ??
5537 MP4_Box_t *p_vroot = LoadNextChunk( p_demux );
5538 switch( p_sys->context.i_current_box_type )
5542 /* create fragment */
5543 AddFragment( p_demux, p_vroot->p_first );
5549 /* Append to root */
5550 p_sys->p_root->p_last->p_next = p_vroot->p_first;
5551 p_sys->p_root->p_last = p_vroot->p_first;
5552 p_vroot->p_last = NULL;
5553 p_vroot->p_next = NULL;
5554 p_vroot->p_first = NULL;
5555 MP4_BoxFree( p_demux->s, p_vroot );
5560 msg_Err( p_demux, "skipping known chunk type %4.4s size %"PRIu32, (char*)& p_sys->context.i_current_box_type, GetDWBE( p_peek ) );
5561 stream_Read( p_demux->s, NULL, GetDWBE( p_peek ) );
5566 /* skip mdat header */
5567 p_sys->context.p_fragment = GetFragmentByPos( p_demux,
5568 stream_Tell( p_demux->s ) + 8, true );
5573 if ( p_sys->context.i_current_box_type == ATOM_mdat )
5575 assert(p_sys->context.p_fragment);
5576 if ( p_sys->context.p_fragment )
5577 switch( p_sys->context.p_fragment->p_moox->i_type )
5579 case ATOM_moov://[ftyp/moov, mdat]+ -> [moof, mdat]+
5580 LeafParseMDATwithMOOV( p_demux );
5583 LeafParseMDATwithMOOF( p_demux, p_sys->context.p_fragment->p_moox ); // BACKUP CHUNK!
5586 msg_Err( p_demux, "fragment type %4.4s", (char*) &p_sys->context.p_fragment->p_moox->i_type );
5591 /* Get current time */
5592 mtime_t i_lowest_dts = VLC_TS_INVALID;
5593 mtime_t i_lowest_time = INT64_MAX;
5594 for( unsigned int i_track = 0; i_track < p_sys->i_tracks; i_track++ )
5596 const mp4_track_t *p_track = &p_sys->track[i_track];
5597 if( !p_track->b_selected || ( p_track->fmt.i_cat != VIDEO_ES && p_track->fmt.i_cat != AUDIO_ES ) )
5600 i_lowest_time = __MIN( i_lowest_time, p_track->i_time * p_sys->i_timescale / p_track->i_timescale );
5602 if ( i_lowest_dts == VLC_TS_INVALID )
5603 i_lowest_dts = CLOCK_FREQ * p_track->i_time / p_track->i_timescale;
5605 i_lowest_dts = __MIN( i_lowest_dts, CLOCK_FREQ * p_track->i_time / p_track->i_timescale );
5608 p_sys->i_time = i_lowest_time;
5609 p_sys->i_pcr = i_lowest_dts;
5610 es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + p_sys->i_pcr );