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 void MP4_Block_Send( demux_t *, mp4_track_t *, block_t * );
120 static int MP4_TrackSelect ( demux_t *, mp4_track_t *, mtime_t );
121 static void MP4_TrackUnselect(demux_t *, mp4_track_t * );
123 static int MP4_TrackSeek ( demux_t *, mp4_track_t *, mtime_t );
125 static uint64_t MP4_TrackGetPos ( mp4_track_t * );
126 static uint32_t MP4_TrackGetReadSize( mp4_track_t *, uint32_t * );
127 static int MP4_TrackNextSample( demux_t *, mp4_track_t *, uint32_t );
128 static void MP4_TrackSetELST( demux_t *, mp4_track_t *, int64_t );
130 static void MP4_UpdateSeekpoint( demux_t * );
131 static const char *MP4_ConvertMacCode( uint16_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 void MP4_Block_Send( demux_t *p_demux, mp4_track_t *p_track, block_t *p_block )
396 if ( p_track->b_chans_reorder && aout_BitsPerSample( p_track->fmt.i_codec ) )
398 aout_ChannelReorder( p_block->p_buffer, p_block->i_buffer,
399 p_track->fmt.audio.i_channels,
400 p_track->rgi_chans_reordering,
401 p_track->fmt.i_codec );
403 es_out_Send( p_demux->out, p_track->p_es, p_block );
406 /*****************************************************************************
407 * Open: check file and initializes MP4 structures
408 *****************************************************************************/
409 static int Open( vlc_object_t * p_this )
411 demux_t *p_demux = (demux_t *)p_this;
414 const uint8_t *p_peek;
424 /* A little test to see if it could be a mp4 */
425 if( stream_Peek( p_demux->s, &p_peek, 11 ) < 11 ) return VLC_EGENERIC;
427 switch( VLC_FOURCC( p_peek[4], p_peek[5], p_peek[6], p_peek[7] ) )
438 case VLC_FOURCC( 'p', 'n', 'o', 't' ):
441 /* We don't yet support f4v, but avformat does. */
442 if( p_peek[8] == 'f' && p_peek[9] == '4' && p_peek[10] == 'v' )
449 /* create our structure that will contains all data */
450 p_sys = calloc( 1, sizeof( demux_sys_t ) );
455 stream_Control( p_demux->s, STREAM_CAN_SEEK, &p_sys->b_seekable );
456 if( !p_sys->b_seekable )
458 msg_Warn( p_demux, "MP4 plugin discarded (not seekable)" );
462 stream_Control( p_demux->s, STREAM_CAN_FASTSEEK, &p_sys->b_fastseekable );
463 p_sys->b_seekmode = p_sys->b_fastseekable;
465 /*Set exported functions */
466 p_demux->pf_demux = Demux;
467 p_demux->pf_control = Control;
469 p_demux->p_sys = p_sys;
471 if( stream_Peek( p_demux->s, &p_peek, 24 ) < 24 ) return VLC_EGENERIC;
472 if( !CmpUUID( (UUID_t *)(p_peek + 8), &SmooBoxUUID ) )
474 p_sys->b_smooth = true;
475 p_sys->b_fragmented = true;
478 if( LoadInitFrag( p_demux ) != VLC_SUCCESS )
481 if( MP4_BoxCount( p_sys->p_root, "/moov/mvex" ) > 0 )
483 if ( p_sys->b_seekable )
485 /* Probe remaining to check if there's really fragments
486 or if that file is just ready to append fragments */
487 ProbeFragments( p_demux, false );
488 p_sys->b_fragmented = !!MP4_BoxCount( p_sys->p_root, "/moof" );
491 p_sys->b_fragmented = true;
493 if ( p_sys->b_fragmented && !p_sys->i_overall_duration )
494 ProbeFragments( p_demux, true );
497 if ( !p_sys->moovfragment.p_moox )
498 AddFragment( p_demux, MP4_BoxGet( p_sys->p_root, "/moov" ) );
500 /* we always need a moov entry, but smooth has a workaround */
501 if ( !p_sys->moovfragment.p_moox && !p_sys->b_smooth )
504 if ( p_sys->b_smooth )
506 p_demux->pf_demux = DemuxFrg;
508 else if( p_sys->b_fragmented )
510 p_demux->pf_demux = DemuxAsLeaf;
513 if( p_sys->b_smooth )
515 if( InitTracks( p_demux ) != VLC_SUCCESS )
517 CreateTracksFromSmooBox( p_demux );
521 MP4_BoxDumpStructure( p_demux->s, p_sys->p_root );
523 if( ( p_ftyp = MP4_BoxGet( p_sys->p_root, "/ftyp" ) ) )
525 switch( BOXDATA(p_ftyp)->i_major_brand )
529 "ISO Media file (isom) version %d.",
530 BOXDATA(p_ftyp)->i_minor_version );
533 case( VLC_FOURCC( '3', 'g', 'p', '5' ) ):
534 case( VLC_FOURCC( '3', 'g', 'p', '6' ) ):
535 case( VLC_FOURCC( '3', 'g', 'p', '7' ) ):
536 msg_Dbg( p_demux, "3GPP Media file Release: %c",
537 #ifdef WORDS_BIGENDIAN
538 BOXDATA(p_ftyp)->i_major_brand
540 BOXDATA(p_ftyp)->i_major_brand >> 24
544 case( VLC_FOURCC( 'q', 't', ' ', ' ') ):
545 msg_Dbg( p_demux, "Apple QuickTime file" );
547 case( VLC_FOURCC( 'i', 's', 'm', 'l') ):
548 msg_Dbg( p_demux, "PIFF (= isml = fMP4) file" );
552 "unrecognized major file specification (%4.4s).",
553 (char*)&BOXDATA(p_ftyp)->i_major_brand );
559 msg_Dbg( p_demux, "file type box missing (assuming ISO Media file)" );
562 /* the file need to have one moov box */
563 p_sys->moovfragment.p_moox = MP4_BoxGet( p_sys->p_root, "/moov", 0 );
564 if( !p_sys->moovfragment.p_moox )
566 MP4_Box_t *p_foov = MP4_BoxGet( p_sys->p_root, "/foov" );
570 msg_Err( p_demux, "MP4 plugin discarded (no moov,foov,moof box)" );
573 /* we have a free box as a moov, rename it */
574 p_foov->i_type = ATOM_moov;
575 p_sys->moovfragment.p_moox = p_foov;
578 if( ( p_rmra = MP4_BoxGet( p_sys->p_root, "/moov/rmra" ) ) )
580 int i_count = MP4_BoxCount( p_rmra, "rmda" );
583 msg_Dbg( p_demux, "detected playlist mov file (%d ref)", i_count );
585 input_thread_t *p_input = demux_GetParentInput( p_demux );
586 input_item_t *p_current = input_GetItem( p_input );
588 input_item_node_t *p_subitems = input_item_node_Create( p_current );
590 for( i = 0; i < i_count; i++ )
592 MP4_Box_t *p_rdrf = MP4_BoxGet( p_rmra, "rmda[%d]/rdrf", i );
596 if( !p_rdrf || !BOXDATA(p_rdrf) || !( psz_ref = strdup( BOXDATA(p_rdrf)->psz_ref ) ) )
600 i_ref_type = BOXDATA(p_rdrf)->i_ref_type;
602 msg_Dbg( p_demux, "new ref=`%s' type=%4.4s",
603 psz_ref, (char*)&i_ref_type );
605 if( i_ref_type == VLC_FOURCC( 'u', 'r', 'l', ' ' ) )
607 if( strstr( psz_ref, "qt5gateQT" ) )
609 msg_Dbg( p_demux, "ignoring pseudo ref =`%s'", psz_ref );
612 if( !strncmp( psz_ref, "http://", 7 ) ||
613 !strncmp( psz_ref, "rtsp://", 7 ) )
620 char *psz_path = strdup( p_demux->psz_location );
621 char *end = strrchr( psz_path, '/' );
622 if( end ) end[1] = '\0';
623 else *psz_path = '\0';
625 if( asprintf( &psz_absolute, "%s://%s%s",
626 p_demux->psz_access, psz_path, psz_ref ) < 0 )
630 input_item_node_Delete( p_subitems );
631 vlc_object_release( p_input) ;
636 psz_ref = psz_absolute;
639 msg_Dbg( p_demux, "adding ref = `%s'", psz_ref );
640 input_item_t *p_item = input_item_New( psz_ref, NULL );
641 input_item_CopyOptions( p_current, p_item );
642 input_item_node_AppendItem( p_subitems, p_item );
643 vlc_gc_decref( p_item );
647 msg_Err( p_demux, "unknown ref type=%4.4s FIXME (send a bug report)",
648 (char*)&BOXDATA(p_rdrf)->i_ref_type );
652 input_item_node_PostAndDelete( p_subitems );
653 vlc_object_release( p_input );
656 if( !(p_mvhd = MP4_BoxGet( p_sys->p_root, "/moov/mvhd" ) ) )
660 msg_Err( p_demux, "cannot find /moov/mvhd" );
665 msg_Warn( p_demux, "cannot find /moov/mvhd (pure ref file)" );
666 p_demux->pf_demux = DemuxRef;
672 p_sys->i_timescale = BOXDATA(p_mvhd)->i_timescale;
673 if( p_sys->i_timescale == 0 )
675 msg_Err( p_this, "bad timescale" );
680 if ( p_sys->i_overall_duration == 0 )
682 /* Try in mehd if fragmented */
683 MP4_Box_t *p_mehd = MP4_BoxGet( p_demux->p_sys->p_root, "moov/mvex/mehd");
684 if ( p_mehd && p_mehd->data.p_mehd )
685 p_sys->i_overall_duration = p_mehd->data.p_mehd->i_fragment_duration;
687 p_sys->i_overall_duration = p_sys->moovfragment.i_duration;
690 if( !( p_sys->i_tracks = MP4_BoxCount( p_sys->p_root, "/moov/trak" ) ) )
692 msg_Err( p_demux, "cannot find any /moov/trak" );
695 msg_Dbg( p_demux, "found %d track%c",
697 p_sys->i_tracks ? 's':' ' );
699 if( InitTracks( p_demux ) != VLC_SUCCESS )
702 /* Search the first chap reference (like quicktime) and
703 * check that at least 1 stream is enabled */
704 p_sys->p_tref_chap = NULL;
705 b_enabled_es = false;
706 for( i = 0; i < p_sys->i_tracks; i++ )
708 MP4_Box_t *p_trak = MP4_BoxGet( p_sys->p_root, "/moov/trak[%d]", i );
711 MP4_Box_t *p_tkhd = MP4_BoxGet( p_trak, "tkhd" );
712 if( p_tkhd && BOXDATA(p_tkhd) && (BOXDATA(p_tkhd)->i_flags&MP4_TRACK_ENABLED) )
715 MP4_Box_t *p_chap = MP4_BoxGet( p_trak, "tref/chap", i );
716 if( p_chap && p_chap->data.p_tref_generic &&
717 p_chap->data.p_tref_generic->i_entry_count > 0 && !p_sys->p_tref_chap )
718 p_sys->p_tref_chap = p_chap;
721 /* now process each track and extract all useful information */
722 for( i = 0; i < p_sys->i_tracks; i++ )
724 p_trak = MP4_BoxGet( p_sys->p_root, "/moov/trak[%d]", i );
725 MP4_TrackCreate( p_demux, &p_sys->track[i], p_trak, !b_enabled_es );
727 if( p_sys->track[i].b_ok && !p_sys->track[i].b_chapter )
730 switch( p_sys->track[i].fmt.i_cat )
739 psz_cat = "subtitle";
747 msg_Dbg( p_demux, "adding track[Id 0x%x] %s (%s) language %s",
748 p_sys->track[i].i_track_ID, psz_cat,
749 p_sys->track[i].b_enable ? "enable":"disable",
750 p_sys->track[i].fmt.psz_language ?
751 p_sys->track[i].fmt.psz_language : "undef" );
753 else if( p_sys->track[i].b_ok && p_sys->track[i].b_chapter )
755 msg_Dbg( p_demux, "using track[Id 0x%x] for chapter language %s",
756 p_sys->track[i].i_track_ID,
757 p_sys->track[i].fmt.psz_language ?
758 p_sys->track[i].fmt.psz_language : "undef" );
762 msg_Dbg( p_demux, "ignoring track[Id 0x%x]",
763 p_sys->track[i].i_track_ID );
767 mp4_fragment_t *p_fragment = &p_sys->moovfragment;
770 msg_Dbg( p_demux, "fragment offset %"PRId64", data %"PRIu64"<->%"PRIu64", duration %"PRId64,
771 p_fragment->p_moox->i_pos, p_fragment->i_chunk_range_min_offset,
772 p_fragment->i_chunk_range_max_offset, CLOCK_FREQ * p_fragment->i_duration / p_sys->i_timescale );
773 p_fragment = p_fragment->p_next;
777 LoadChapter( p_demux );
784 MP4_BoxFree( p_demux->s, p_sys->p_root );
790 /*****************************************************************************
791 * Demux: read packet and send them to decoders
792 *****************************************************************************
793 * TODO check for newly selected track (ie audio upt to now )
794 *****************************************************************************/
795 static int Demux( demux_t *p_demux )
797 demux_sys_t *p_sys = p_demux->p_sys;
798 unsigned int i_track;
801 unsigned int i_track_selected;
803 /* check for newly selected/unselected track */
804 for( i_track = 0, i_track_selected = 0; i_track < p_sys->i_tracks;
807 mp4_track_t *tk = &p_sys->track[i_track];
810 if( !tk->b_ok || tk->b_chapter ||
811 ( tk->b_selected && tk->i_sample >= tk->i_sample_count ) )
816 es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
818 if( tk->b_selected && !b )
820 MP4_TrackUnselect( p_demux, tk );
822 else if( !tk->b_selected && b)
824 MP4_TrackSelect( p_demux, tk, MP4_GetMoviePTS( p_sys ) );
833 if( i_track_selected <= 0 )
835 p_sys->i_time += __MAX( p_sys->i_timescale / 10 , 1 );
836 if( p_sys->i_timescale > 0 )
838 int64_t i_length = CLOCK_FREQ *
839 (mtime_t)p_sys->moovfragment.i_duration /
840 (mtime_t)p_sys->i_timescale;
841 if( MP4_GetMoviePTS( p_sys ) >= i_length )
846 msg_Warn( p_demux, "no track selected, exiting..." );
851 MP4_UpdateSeekpoint( p_demux );
853 /* first wait for the good time to read a packet */
854 p_sys->i_pcr = MP4_GetMoviePTS( p_sys );
856 bool b_data_sent = false;
858 /* Find next track matching contiguous data */
859 mp4_track_t *tk = NULL;
860 uint64_t i_candidate_pos = UINT64_MAX;
861 mtime_t i_candidate_dts = INT64_MAX;
862 for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
864 mp4_track_t *tk_tmp = &p_sys->track[i_track];
865 if( !tk_tmp->b_ok || tk_tmp->b_chapter || !tk_tmp->b_selected || tk_tmp->i_sample >= tk_tmp->i_sample_count )
868 if ( p_sys->b_seekmode )
870 mtime_t i_dts = MP4_TrackGetDTS( p_demux, tk_tmp );
871 if ( i_dts <= i_candidate_dts )
874 i_candidate_dts = i_dts;
875 i_candidate_pos = MP4_TrackGetPos( tk_tmp );
880 /* Try to avoid seeking on non fastseekable. Will fail with non interleaved content */
881 uint64_t i_pos = MP4_TrackGetPos( tk_tmp );
882 if ( i_pos <= i_candidate_pos )
884 i_candidate_pos = i_pos;
892 msg_Dbg( p_demux, "Could not select track by data position" );
895 else if ( p_sys->b_seekmode )
897 if( stream_Seek( p_demux->s, i_candidate_pos ) )
899 msg_Warn( p_demux, "track[0x%x] will be disabled (eof?)",
901 MP4_TrackUnselect( p_demux, tk );
907 msg_Dbg( p_demux, "tk(%i)=%"PRId64" mv=%"PRId64" pos=%"PRIu64, i_track,
908 MP4_TrackGetDTS( p_demux, tk ),
909 MP4_GetMoviePTS( p_sys ), i_candidate_pos );
912 uint32_t i_nb_samples = 0;
913 uint32_t i_samplessize = MP4_TrackGetReadSize( tk, &i_nb_samples );
914 if( i_samplessize > 0 )
918 uint64_t i_current_pos;
921 if ( !MP4_stream_Tell( p_demux->s, &i_current_pos ) )
924 if( i_current_pos != i_candidate_pos )
926 if( stream_Seek( p_demux->s, i_candidate_pos ) )
928 msg_Warn( p_demux, "track[0x%x] will be disabled (eof?)",
930 MP4_TrackUnselect( p_demux, tk );
936 if( !(p_block = stream_Block( p_demux->s, i_samplessize )) )
938 msg_Warn( p_demux, "track[0x%x] will be disabled (eof?)",
940 MP4_TrackUnselect( p_demux, tk );
943 else if( tk->fmt.i_cat == SPU_ES )
945 if ( tk->fmt.i_codec != VLC_CODEC_TX3G &&
946 tk->fmt.i_codec != VLC_CODEC_SPU )
947 p_block->i_buffer = 0;
951 p_block->i_dts = VLC_TS_0 + MP4_TrackGetDTS( p_demux, tk );
953 i_delta = MP4_TrackGetPTSDelta( p_demux, tk );
955 p_block->i_pts = p_block->i_dts + i_delta;
956 else if( tk->fmt.i_cat != VIDEO_ES )
957 p_block->i_pts = p_block->i_dts;
959 p_block->i_pts = VLC_TS_INVALID;
963 es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + p_sys->i_pcr );
966 MP4_Block_Send( p_demux, tk, p_block );
970 if ( i_nb_samples ) /* sample size could be 0, need to go fwd. see return */
971 MP4_TrackNextSample( p_demux, tk, i_nb_samples );
976 p_sys->i_pcr = INT64_MAX;
977 for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
979 mp4_track_t *tk = &p_sys->track[i_track];
980 if ( !tk->b_ok || !tk->b_selected ||
981 (tk->fmt.i_cat != AUDIO_ES && tk->fmt.i_cat != VIDEO_ES) )
984 mtime_t i_dts = MP4_TrackGetDTS( p_demux, tk );
985 if ( !p_sys->b_seekmode && i_dts > p_sys->i_pcr + 2*CLOCK_FREQ )
987 msg_Dbg( p_demux, "that media doesn't look interleaved, will need to seek");
988 p_sys->b_seekmode = true;
991 p_sys->i_pcr = __MIN( i_dts, p_sys->i_pcr );
992 p_sys->i_time = p_sys->i_pcr * p_sys->i_timescale / CLOCK_FREQ;
996 return b_data_sent || ( i_samplessize == 0 && i_nb_samples );
999 static void MP4_UpdateSeekpoint( demux_t *p_demux )
1001 demux_sys_t *p_sys = p_demux->p_sys;
1004 if( !p_sys->p_title )
1006 i_time = MP4_GetMoviePTS( p_sys );
1007 for( i = 0; i < p_sys->p_title->i_seekpoint; i++ )
1009 if( i_time < p_sys->p_title->seekpoint[i]->i_time_offset )
1014 if( i != p_demux->info.i_seekpoint && i >= 0 )
1016 p_demux->info.i_seekpoint = i;
1017 p_demux->info.i_update |= INPUT_UPDATE_SEEKPOINT;
1020 /*****************************************************************************
1021 * Seek: Go to i_date
1022 ******************************************************************************/
1023 static int Seek( demux_t *p_demux, mtime_t i_date )
1025 demux_sys_t *p_sys = p_demux->p_sys;
1026 unsigned int i_track;
1028 /* First update global time */
1029 p_sys->i_time = i_date * p_sys->i_timescale / CLOCK_FREQ;
1030 p_sys->i_pcr = VLC_TS_INVALID;
1032 /* Now for each stream try to go to this time */
1033 for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
1035 mp4_track_t *tk = &p_sys->track[i_track];
1036 MP4_TrackSeek( p_demux, tk, i_date );
1038 MP4_UpdateSeekpoint( p_demux );
1040 es_out_Control( p_demux->out, ES_OUT_SET_NEXT_DISPLAY_TIME, i_date );
1045 static int LeafSeekIntoFragment( demux_t *p_demux, mp4_fragment_t *p_fragment )
1047 demux_sys_t *p_sys = p_demux->p_sys;
1048 uint64_t i64 = p_fragment->i_chunk_range_min_offset;
1050 if ( p_fragment->p_moox->i_type == ATOM_moov )
1052 mp4_track_t *p_track;
1053 unsigned int i_chunk;
1054 int i_ret = LeafGetTrackAndChunkByMOOVPos( p_demux, &i64, &p_track, &i_chunk );
1055 if ( i_ret == VLC_EGENERIC )
1057 msg_Dbg( p_demux, "moov seek failed to identify %"PRIu64, i64 );
1060 msg_Dbg( p_demux, "moov seeking to %"PRIu64, i64 );
1064 i64 = p_fragment->i_chunk_range_min_offset;
1065 msg_Dbg( p_demux, "moof seeking to %"PRIu64, i64 );
1068 if( stream_Seek( p_demux->s, i64 ) )
1070 msg_Err( p_demux, "seek failed to %"PRIu64, i64 );
1071 return VLC_EGENERIC;
1075 p_sys->context.p_fragment = p_fragment;
1076 p_sys->context.i_current_box_type = ATOM_mdat;
1077 LeafMapTrafTrunContextes( p_demux, p_fragment->p_moox );
1078 p_sys->context.i_mdatbytesleft = p_fragment->i_chunk_range_max_offset - i64;
1080 mtime_t i_time_base = LeafGetFragmentTimeOffset( p_demux, p_fragment );
1081 for( unsigned int i_track = 0; i_track < p_sys->i_tracks; i_track++ )
1083 p_sys->track[i_track].i_time = i_time_base * p_sys->track[i_track].i_timescale / p_sys->i_timescale;
1085 p_sys->i_time = i_time_base;
1086 p_sys->i_pcr = VLC_TS_INVALID;
1091 static int LeafSeekToTime( demux_t *p_demux, mtime_t i_nztime )
1093 demux_sys_t *p_sys = p_demux->p_sys;
1094 mp4_fragment_t *p_fragment;
1096 if ( !p_sys->i_timescale || !p_sys->i_overall_duration || !p_sys->b_seekable )
1097 return VLC_EGENERIC;
1099 if ( !p_sys->b_fragments_probed && !p_sys->b_index_probed && p_sys->b_seekable )
1101 ProbeIndex( p_demux );
1102 p_sys->b_index_probed = true;
1105 p_fragment = GetFragmentByTime( p_demux, i_nztime );
1109 msg_Dbg( p_demux, "seek can't find matching fragment for %"PRId64", trying index", i_nztime );
1110 if ( LeafIndexGetMoofPosByTime( p_demux, i_nztime, &i64, &i_mooftime ) == VLC_SUCCESS )
1112 msg_Dbg( p_demux, "seek trying to go to unknown but indexed fragment at %"PRId64, i64 );
1113 if( stream_Seek( p_demux->s, i64 ) )
1115 msg_Err( p_demux, "seek to moof failed %"PRId64, i64 );
1116 return VLC_EGENERIC;
1118 p_sys->context.i_current_box_type = 0;
1119 p_sys->context.i_mdatbytesleft = 0;
1120 p_sys->context.p_fragment = NULL;
1121 for( unsigned int i_track = 0; i_track < p_sys->i_tracks; i_track++ )
1123 p_sys->track[i_track].i_time = i_mooftime / CLOCK_FREQ * p_sys->track[i_track].i_timescale;
1125 p_sys->i_time = i_mooftime / CLOCK_FREQ * p_sys->i_timescale;
1126 p_sys->i_pcr = VLC_TS_INVALID;
1130 msg_Warn( p_demux, "seek by index failed" );
1131 return VLC_EGENERIC;
1136 msg_Dbg( p_demux, "seeking to fragment data starting at %"PRIu64" for time %"PRId64,
1137 p_fragment->i_chunk_range_min_offset, i_nztime );
1138 if ( LeafSeekIntoFragment( p_demux, p_fragment ) != VLC_SUCCESS )
1139 return VLC_EGENERIC;
1142 /* And set next display time in that trun/fragment */
1143 es_out_Control( p_demux->out, ES_OUT_SET_NEXT_DISPLAY_TIME, VLC_TS_0 + i_nztime );
1147 static int LeafSeekToPos( demux_t *p_demux, double f )
1149 demux_sys_t *p_sys = p_demux->p_sys;
1150 if ( !p_sys->b_seekable )
1151 return VLC_EGENERIC;
1153 if ( p_sys->i_timescale && p_sys->i_overall_duration )
1155 return LeafSeekToTime( p_demux,
1156 (mtime_t)( f * CLOCK_FREQ * p_sys->i_overall_duration /
1157 p_sys->i_timescale ) );
1160 if ( !p_sys->b_fragments_probed && !p_sys->b_index_probed && p_sys->b_seekable )
1162 ProbeIndex( p_demux );
1163 p_sys->b_index_probed = true;
1166 /* Blind seek to pos only */
1167 uint64_t i64 = (uint64_t) stream_Size( p_demux->s ) * f;
1168 mp4_fragment_t *p_fragment = GetFragmentByPos( p_demux, i64, false );
1171 msg_Dbg( p_demux, "Seeking to fragment data starting at %"PRIu64" for pos %"PRIu64,
1172 p_fragment->i_chunk_range_min_offset, i64 );
1173 return LeafSeekIntoFragment( p_demux, p_fragment );
1177 msg_Dbg( p_demux, "Cant get fragment for data starting at %"PRIu64, i64 );
1178 return VLC_EGENERIC;
1182 static int MP4_frg_Seek( demux_t *p_demux, double f )
1184 demux_sys_t *p_sys = p_demux->p_sys;
1186 int64_t i64 = stream_Size( p_demux->s );
1187 if( stream_Seek( p_demux->s, (int64_t)(i64 * f) ) )
1189 return VLC_EGENERIC;
1193 /* update global time */
1194 p_sys->i_time = (uint64_t)(f * (double)p_sys->moovfragment.i_duration);
1195 p_sys->i_pcr = MP4_GetMoviePTS( p_sys );
1197 for( unsigned i_track = 0; i_track < p_sys->i_tracks; i_track++ )
1199 mp4_track_t *tk = &p_sys->track[i_track];
1201 /* We don't want the current chunk to be flushed */
1202 tk->cchunk->i_sample = tk->cchunk->i_sample_count;
1204 /* reset/update some values */
1205 tk->i_sample = tk->i_sample_first = 0;
1206 tk->i_first_dts = p_sys->i_time;
1208 /* We want to discard the current chunk and get the next one at once */
1209 tk->b_has_non_empty_cchunk = false;
1211 es_out_Control( p_demux->out, ES_OUT_SET_NEXT_DISPLAY_TIME, p_sys->i_pcr );
1216 /*****************************************************************************
1218 *****************************************************************************/
1219 static int Control( demux_t *p_demux, int i_query, va_list args )
1221 demux_sys_t *p_sys = p_demux->p_sys;
1228 case DEMUX_GET_POSITION:
1229 pf = (double*)va_arg( args, double * );
1230 if( p_sys->i_overall_duration > 0 )
1232 *pf = (double)p_sys->i_time / (double)p_sys->i_overall_duration;
1240 case DEMUX_SET_POSITION:
1241 f = (double)va_arg( args, double );
1242 if ( p_demux->pf_demux == DemuxAsLeaf )
1243 return LeafSeekToPos( p_demux, f );
1244 else if ( p_demux->pf_demux == DemuxFrg )
1245 return MP4_frg_Seek( p_demux, f );
1246 else if( p_sys->i_timescale > 0 )
1248 i64 = (int64_t)( f * CLOCK_FREQ *
1249 (double)p_sys->i_overall_duration /
1250 (double)p_sys->i_timescale );
1251 return Seek( p_demux, i64 );
1253 else return VLC_EGENERIC;
1255 case DEMUX_GET_TIME:
1256 pi64 = (int64_t*)va_arg( args, int64_t * );
1257 if( p_sys->i_timescale > 0 )
1259 *pi64 = CLOCK_FREQ *
1260 (mtime_t)p_sys->i_time /
1261 (mtime_t)p_sys->i_timescale;
1266 case DEMUX_SET_TIME:
1267 i64 = (int64_t)va_arg( args, int64_t );
1268 if ( p_demux->pf_demux == DemuxAsLeaf )
1269 return LeafSeekToTime( p_demux, i64 );
1271 return Seek( p_demux, i64 );
1273 case DEMUX_GET_LENGTH:
1274 pi64 = (int64_t*)va_arg( args, int64_t * );
1275 if( p_sys->i_timescale > 0 )
1277 *pi64 = CLOCK_FREQ *
1278 (mtime_t)p_sys->i_overall_duration /
1279 (mtime_t)p_sys->i_timescale;
1285 pf = (double*)va_arg( args, double* );
1289 case DEMUX_GET_ATTACHMENTS:
1291 input_attachment_t ***ppp_attach = va_arg( args, input_attachment_t*** );
1292 int *pi_int = va_arg( args, int * );
1294 MP4_Box_t *p_covr = MP4_BoxGet( p_sys->p_root, "/moov/udta/meta/ilst/covr" );
1295 if ( !p_covr ) return VLC_EGENERIC;
1299 for( p_box = p_covr->p_first; p_box != NULL; p_box = p_box->p_next )
1301 if ( p_box->i_type == ATOM_data && p_box->data.p_data->i_blob >= 16 )
1306 return VLC_EGENERIC;
1308 *ppp_attach = (input_attachment_t**)
1309 malloc( sizeof(input_attachment_t*) * i_count );
1310 if( !(*ppp_attach) ) return VLC_ENOMEM;
1314 for( p_box = p_covr->p_first; p_box != NULL; p_box = p_box->p_next )
1316 if ( p_box->i_type != ATOM_data || p_box->data.p_data->i_blob < 16 )
1319 if ( !memcmp( p_box->data.p_data->p_blob,
1320 "\x89\x50\x4E\x47\x0D\x0A\x1A\x0A", 8 ) )
1322 psz_mime = strdup( "image/png" );
1324 else if ( !memcmp( p_box->data.p_data->p_blob, "\xFF\xD8", 2 ) )
1326 psz_mime = strdup( "image/jpeg" );
1333 if ( asprintf( &psz_filename, "picture%u", i_count ) >= 0 )
1335 (*ppp_attach)[i_count++] =
1336 vlc_input_attachment_New( psz_filename, psz_mime, NULL,
1337 p_box->data.p_data->p_blob, p_box->data.p_data->i_blob );
1338 free( psz_filename );
1346 free( *ppp_attach );
1347 return VLC_EGENERIC;
1355 case DEMUX_GET_META:
1357 vlc_meta_t *p_meta = (vlc_meta_t *)va_arg( args, vlc_meta_t*);
1358 MP4_Box_t *p_0xa9xxx;
1360 MP4_Box_t *p_covr = MP4_BoxGet( p_sys->p_root, "/moov/udta/meta/ilst/covr/data[0]" );
1362 vlc_meta_SetArtURL( p_meta, "attachment://picture0" );
1364 MP4_Box_t *p_udta = MP4_BoxGet( p_sys->p_root, "/moov/udta/meta/ilst" );
1365 if( p_udta == NULL )
1367 p_udta = MP4_BoxGet( p_sys->p_root, "/moov/udta" );
1368 if( p_udta == NULL && p_covr == NULL )
1369 return VLC_EGENERIC;
1374 for( p_0xa9xxx = p_udta->p_first; p_0xa9xxx != NULL;
1375 p_0xa9xxx = p_0xa9xxx->p_next )
1378 if( !p_0xa9xxx || !BOXDATA(p_0xa9xxx) )
1381 /* FIXME FIXME: should convert from whatever the character
1382 * encoding of MP4 meta data is to UTF-8. */
1383 #define SET(fct) do { char *psz_utf = strdup( BOXDATA(p_0xa9xxx)->psz_text ? BOXDATA(p_0xa9xxx)->psz_text : "" ); \
1384 if( psz_utf ) { EnsureUTF8( psz_utf ); \
1385 fct( p_meta, psz_utf ); free( psz_utf ); } } while(0)
1387 /* XXX Becarefull p_udta can have box that are not 0xa9xx */
1388 switch( p_0xa9xxx->i_type )
1390 case ATOM_0xa9nam: /* Full name */
1391 SET( vlc_meta_SetTitle );
1394 SET( vlc_meta_SetArtist );
1397 SET( vlc_meta_SetArtist );
1400 SET( vlc_meta_SetCopyright );
1402 case ATOM_0xa9day: /* Creation Date */
1403 SET( vlc_meta_SetDate );
1405 case ATOM_0xa9des: /* Description */
1406 SET( vlc_meta_SetDescription );
1408 case ATOM_0xa9gen: /* Genre */
1409 SET( vlc_meta_SetGenre );
1413 if( p_0xa9xxx->data.p_gnre->i_genre <= NUM_GENRES )
1414 vlc_meta_SetGenre( p_meta, ppsz_genres[p_0xa9xxx->data.p_gnre->i_genre - 1] );
1417 case ATOM_0xa9alb: /* Album */
1418 SET( vlc_meta_SetAlbum );
1421 case ATOM_0xa9trk: /* Track */
1422 SET( vlc_meta_SetTrackNum );
1427 snprintf( psz_trck, sizeof( psz_trck ), "%i",
1428 p_0xa9xxx->data.p_trkn->i_track_number );
1429 vlc_meta_SetTrackNum( p_meta, psz_trck );
1430 if( p_0xa9xxx->data.p_trkn->i_track_total > 0 )
1432 snprintf( psz_trck, sizeof( psz_trck ), "%i",
1433 p_0xa9xxx->data.p_trkn->i_track_total );
1434 vlc_meta_Set( p_meta, vlc_meta_TrackTotal, psz_trck );
1438 case ATOM_0xa9cmt: /* Commment */
1439 SET( vlc_meta_SetDescription );
1442 case ATOM_0xa9url: /* URL */
1443 SET( vlc_meta_SetURL );
1446 case ATOM_0xa9too: /* Encoder Tool */
1447 case ATOM_0xa9enc: /* Encoded By */
1448 SET( vlc_meta_SetEncodedBy );
1452 SET( vlc_meta_SetPublisher );
1456 SET( vlc_meta_SetDirector );
1463 static const struct { uint32_t xa9_type; char metadata[25]; } xa9typetoextrameta[] =
1465 { ATOM_0xa9wrt, N_("Writer") },
1466 { ATOM_0xa9com, N_("Composer") },
1467 { ATOM_0xa9prd, N_("Producer") },
1468 { ATOM_0xa9inf, N_("Information") },
1469 { ATOM_0xa9dis, N_("Disclaimer") },
1470 { ATOM_0xa9req, N_("Requirements") },
1471 { ATOM_0xa9fmt, N_("Original Format") },
1472 { ATOM_0xa9dsa, N_("Display Source As") },
1473 { ATOM_0xa9hst, N_("Host Computer") },
1474 { ATOM_0xa9prf, N_("Performers") },
1475 { ATOM_0xa9ope, N_("Original Performer") },
1476 { ATOM_0xa9src, N_("Providers Source Content") },
1477 { ATOM_0xa9wrn, N_("Warning") },
1478 { ATOM_0xa9swr, N_("Software") },
1479 { ATOM_0xa9lyr, N_("Lyrics") },
1480 { ATOM_0xa9mak, N_("Record Company") },
1481 { ATOM_0xa9mod, N_("Model") },
1482 { ATOM_0xa9PRD, N_("Product") },
1483 { ATOM_0xa9grp, N_("Grouping") },
1484 { ATOM_0xa9gen, N_("Genre") },
1485 { ATOM_0xa9st3, N_("Sub-Title") },
1486 { ATOM_0xa9arg, N_("Arranger") },
1487 { ATOM_0xa9ard, N_("Art Director") },
1488 { ATOM_0xa9cak, N_("Copyright Acknowledgement") },
1489 { ATOM_0xa9con, N_("Conductor") },
1490 { ATOM_0xa9des, N_("Song Description") },
1491 { ATOM_0xa9lnt, N_("Liner Notes") },
1492 { ATOM_0xa9phg, N_("Phonogram Rights") },
1493 { ATOM_0xa9pub, N_("Publisher") },
1494 { ATOM_0xa9sne, N_("Sound Engineer") },
1495 { ATOM_0xa9sol, N_("Soloist") },
1496 { ATOM_0xa9thx, N_("Thanks") },
1497 { ATOM_0xa9xpd, N_("Executive Producer") },
1500 for( unsigned i = 0; xa9typetoextrameta[i].xa9_type; i++ )
1502 if( p_0xa9xxx->i_type == xa9typetoextrameta[i].xa9_type )
1504 char *psz_utf = strdup( BOXDATA(p_0xa9xxx)->psz_text ? BOXDATA(p_0xa9xxx)->psz_text : "" );
1507 EnsureUTF8( psz_utf );
1508 vlc_meta_AddExtra( p_meta, _(xa9typetoextrameta[i].metadata), psz_utf );
1518 case DEMUX_GET_TITLE_INFO:
1520 input_title_t ***ppp_title = (input_title_t***)va_arg( args, input_title_t*** );
1521 int *pi_int = (int*)va_arg( args, int* );
1522 int *pi_title_offset = (int*)va_arg( args, int* );
1523 int *pi_seekpoint_offset = (int*)va_arg( args, int* );
1525 if( !p_sys->p_title )
1526 return VLC_EGENERIC;
1529 *ppp_title = malloc( sizeof( input_title_t*) );
1530 (*ppp_title)[0] = vlc_input_title_Duplicate( p_sys->p_title );
1531 *pi_title_offset = 0;
1532 *pi_seekpoint_offset = 0;
1535 case DEMUX_SET_TITLE:
1537 const int i_title = (int)va_arg( args, int );
1538 if( !p_sys->p_title || i_title != 0 )
1539 return VLC_EGENERIC;
1542 case DEMUX_SET_SEEKPOINT:
1544 const int i_seekpoint = (int)va_arg( args, int );
1545 if( !p_sys->p_title )
1546 return VLC_EGENERIC;
1547 return Seek( p_demux, p_sys->p_title->seekpoint[i_seekpoint]->i_time_offset );
1550 case DEMUX_SET_NEXT_DEMUX_TIME:
1551 case DEMUX_SET_GROUP:
1552 case DEMUX_HAS_UNSUPPORTED_META:
1553 case DEMUX_GET_PTS_DELAY:
1554 case DEMUX_CAN_RECORD:
1555 return VLC_EGENERIC;
1558 msg_Warn( p_demux, "control query %u unimplemented", i_query );
1559 return VLC_EGENERIC;
1563 /*****************************************************************************
1564 * Close: frees unused data
1565 *****************************************************************************/
1566 static void Close ( vlc_object_t * p_this )
1568 demux_t * p_demux = (demux_t *)p_this;
1569 demux_sys_t *p_sys = p_demux->p_sys;
1570 unsigned int i_track;
1572 msg_Dbg( p_demux, "freeing all memory" );
1574 MP4_BoxFree( p_demux->s, p_sys->p_root );
1575 for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
1577 MP4_TrackDestroy( &p_sys->track[i_track] );
1579 FREENULL( p_sys->track );
1581 if( p_sys->p_title )
1582 vlc_input_title_Delete( p_sys->p_title );
1584 while( p_sys->moovfragment.p_next )
1586 mp4_fragment_t *p_fragment = p_sys->moovfragment.p_next->p_next;
1587 free( p_sys->moovfragment.p_next );
1588 p_sys->moovfragment.p_next = p_fragment;
1596 /****************************************************************************
1597 * Local functions, specific to vlc
1598 ****************************************************************************/
1600 static void LoadChapterGpac( demux_t *p_demux, MP4_Box_t *p_chpl )
1602 demux_sys_t *p_sys = p_demux->p_sys;
1605 p_sys->p_title = vlc_input_title_New();
1606 for( i = 0; i < BOXDATA(p_chpl)->i_chapter; i++ )
1608 seekpoint_t *s = vlc_seekpoint_New();
1610 s->psz_name = strdup( BOXDATA(p_chpl)->chapter[i].psz_name );
1611 EnsureUTF8( s->psz_name );
1612 s->i_time_offset = BOXDATA(p_chpl)->chapter[i].i_start / 10;
1613 TAB_APPEND( p_sys->p_title->i_seekpoint, p_sys->p_title->seekpoint, s );
1616 static void LoadChapterApple( demux_t *p_demux, mp4_track_t *tk )
1618 demux_sys_t *p_sys = p_demux->p_sys;
1620 for( tk->i_sample = 0; tk->i_sample < tk->i_sample_count; tk->i_sample++ )
1622 const int64_t i_dts = MP4_TrackGetDTS( p_demux, tk );
1623 const int64_t i_pts_delta = MP4_TrackGetPTSDelta( p_demux, tk );
1624 uint32_t i_nb_samples = 0;
1625 const uint32_t i_size = MP4_TrackGetReadSize( tk, &i_nb_samples );
1627 if( i_size > 0 && !stream_Seek( p_demux->s, MP4_TrackGetPos( tk ) ) )
1630 const uint32_t i_read = stream_ReadU32( p_demux->s, p_buffer,
1631 __MIN( sizeof(p_buffer), i_size ) );
1632 const uint32_t i_len = __MIN( GetWBE(p_buffer), i_read-2 );
1636 seekpoint_t *s = vlc_seekpoint_New();
1638 s->psz_name = strndup( &p_buffer[2], i_len );
1639 EnsureUTF8( s->psz_name );
1641 s->i_time_offset = i_dts + __MAX( i_pts_delta, 0 );
1643 if( !p_sys->p_title )
1644 p_sys->p_title = vlc_input_title_New();
1645 TAB_APPEND( p_sys->p_title->i_seekpoint, p_sys->p_title->seekpoint, s );
1648 if( tk->i_sample+1 >= tk->chunk[tk->i_chunk].i_sample_first +
1649 tk->chunk[tk->i_chunk].i_sample_count )
1653 static void LoadChapter( demux_t *p_demux )
1655 demux_sys_t *p_sys = p_demux->p_sys;
1658 if( ( p_chpl = MP4_BoxGet( p_sys->p_root, "/moov/udta/chpl" ) ) &&
1659 BOXDATA(p_chpl) && BOXDATA(p_chpl)->i_chapter > 0 )
1661 LoadChapterGpac( p_demux, p_chpl );
1663 else if( p_sys->p_tref_chap )
1665 MP4_Box_data_tref_generic_t *p_chap = p_sys->p_tref_chap->data.p_tref_generic;
1668 /* Load the first subtitle track like quicktime */
1669 for( i = 0; i < p_chap->i_entry_count; i++ )
1671 for( j = 0; j < p_sys->i_tracks; j++ )
1673 mp4_track_t *tk = &p_sys->track[j];
1674 if( tk->b_ok && tk->i_track_ID == p_chap->i_track_ID[i] &&
1675 tk->fmt.i_cat == SPU_ES && tk->fmt.i_codec == VLC_CODEC_SUBT )
1678 if( j < p_sys->i_tracks )
1680 LoadChapterApple( p_demux, &p_sys->track[j] );
1686 /* Add duration if titles are enabled */
1687 if( p_sys->p_title )
1689 p_sys->p_title->i_length = CLOCK_FREQ *
1690 (uint64_t)p_sys->i_overall_duration / (uint64_t)p_sys->i_timescale;
1694 /* now create basic chunk data, the rest will be filled by MP4_CreateSamplesIndex */
1695 static int TrackCreateChunksIndex( demux_t *p_demux,
1696 mp4_track_t *p_demux_track )
1698 demux_sys_t *p_sys = p_demux->p_sys;
1700 MP4_Box_t *p_co64; /* give offset for each chunk, same for stco and co64 */
1703 unsigned int i_chunk;
1704 unsigned int i_index, i_last;
1706 if( ( !(p_co64 = MP4_BoxGet( p_demux_track->p_stbl, "stco" ) )&&
1707 !(p_co64 = MP4_BoxGet( p_demux_track->p_stbl, "co64" ) ) )||
1708 ( !(p_stsc = MP4_BoxGet( p_demux_track->p_stbl, "stsc" ) ) ))
1710 return( VLC_EGENERIC );
1713 p_demux_track->i_chunk_count = BOXDATA(p_co64)->i_entry_count;
1714 if( !p_demux_track->i_chunk_count )
1716 msg_Warn( p_demux, "no chunk defined" );
1718 p_demux_track->chunk = calloc( p_demux_track->i_chunk_count,
1719 sizeof( mp4_chunk_t ) );
1720 if( p_demux_track->chunk == NULL )
1725 /* first we read chunk offset */
1726 for( i_chunk = 0; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
1728 mp4_chunk_t *ck = &p_demux_track->chunk[i_chunk];
1730 ck->i_offset = BOXDATA(p_co64)->i_chunk_offset[i_chunk];
1732 ck->i_first_dts = 0;
1733 ck->p_sample_count_dts = NULL;
1734 ck->p_sample_delta_dts = NULL;
1735 ck->p_sample_count_pts = NULL;
1736 ck->p_sample_offset_pts = NULL;
1739 /* now we read index for SampleEntry( soun vide mp4a mp4v ...)
1740 to be used for the sample XXX begin to 1
1741 We construct it begining at the end */
1742 i_last = p_demux_track->i_chunk_count; /* last chunk proceded */
1743 i_index = BOXDATA(p_stsc)->i_entry_count;
1745 while( i_index-- > 0 )
1747 for( i_chunk = BOXDATA(p_stsc)->i_first_chunk[i_index] - 1;
1748 i_chunk < i_last; i_chunk++ )
1750 if( i_chunk >= p_demux_track->i_chunk_count )
1752 msg_Warn( p_demux, "corrupted chunk table" );
1753 return VLC_EGENERIC;
1756 p_demux_track->chunk[i_chunk].i_sample_description_index =
1757 BOXDATA(p_stsc)->i_sample_description_index[i_index];
1758 p_demux_track->chunk[i_chunk].i_sample_count =
1759 BOXDATA(p_stsc)->i_samples_per_chunk[i_index];
1761 i_last = BOXDATA(p_stsc)->i_first_chunk[i_index] - 1;
1764 p_demux_track->chunk[0].i_sample_first = 0;
1765 for( i_chunk = 1; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
1767 p_demux_track->chunk[i_chunk].i_sample_first =
1768 p_demux_track->chunk[i_chunk-1].i_sample_first +
1769 p_demux_track->chunk[i_chunk-1].i_sample_count;
1772 msg_Dbg( p_demux, "track[Id 0x%x] read %d chunk",
1773 p_demux_track->i_track_ID, p_demux_track->i_chunk_count );
1775 if ( p_demux_track->i_chunk_count && (
1776 p_sys->moovfragment.i_chunk_range_min_offset == 0 ||
1777 p_sys->moovfragment.i_chunk_range_min_offset > p_demux_track->chunk[0].i_offset
1779 p_sys->moovfragment.i_chunk_range_min_offset = p_demux_track->chunk[0].i_offset;
1784 static int xTTS_CountEntries( demux_t *p_demux, uint32_t *pi_entry /* out */,
1785 const uint32_t i_index,
1786 uint32_t i_index_samples_left,
1787 uint32_t i_sample_count,
1788 const uint32_t *pi_index_sample_count,
1789 const uint32_t i_table_count )
1791 uint32_t i_array_offset;
1792 while( i_sample_count > 0 )
1794 if ( likely((UINT32_MAX - i_index) >= *pi_entry) )
1795 i_array_offset = i_index + *pi_entry;
1797 return VLC_EGENERIC;
1799 if ( i_array_offset >= i_table_count )
1801 msg_Err( p_demux, "invalid index counting total samples %u %u", i_array_offset, i_table_count );
1802 return VLC_EGENERIC;
1805 if ( i_index_samples_left )
1807 if ( i_index_samples_left > i_sample_count )
1809 i_index_samples_left -= i_sample_count;
1811 *pi_entry +=1; /* No samples left, go copy */
1816 i_sample_count -= i_index_samples_left;
1817 i_index_samples_left = 0;
1824 i_sample_count -= __MIN( i_sample_count, pi_index_sample_count[i_array_offset] );
1832 static int TrackCreateSamplesIndex( demux_t *p_demux,
1833 mp4_track_t *p_demux_track )
1835 demux_sys_t *p_sys = p_demux->p_sys;
1838 MP4_Box_data_stsz_t *stsz;
1839 /* TODO use also stss and stsh table for seeking */
1840 /* FIXME use edit table */
1843 * Gives the sample size for each samples. There is also a stz2 table
1844 * (compressed form) that we need to implement TODO */
1845 p_box = MP4_BoxGet( p_demux_track->p_stbl, "stsz" );
1848 /* FIXME and stz2 */
1849 msg_Warn( p_demux, "cannot find STSZ box" );
1850 return VLC_EGENERIC;
1852 stsz = p_box->data.p_stsz;
1854 /* Use stsz table to create a sample number -> sample size table */
1855 p_demux_track->i_sample_count = stsz->i_sample_count;
1856 if( stsz->i_sample_size )
1858 /* 1: all sample have the same size, so no need to construct a table */
1859 p_demux_track->i_sample_size = stsz->i_sample_size;
1860 p_demux_track->p_sample_size = NULL;
1864 /* 2: each sample can have a different size */
1865 p_demux_track->i_sample_size = 0;
1866 p_demux_track->p_sample_size =
1867 calloc( p_demux_track->i_sample_count, sizeof( uint32_t ) );
1868 if( p_demux_track->p_sample_size == NULL )
1871 for( uint32_t i_sample = 0; i_sample < p_demux_track->i_sample_count; i_sample++ )
1873 p_demux_track->p_sample_size[i_sample] =
1874 stsz->i_entry_size[i_sample];
1878 if ( p_demux_track->i_chunk_count )
1880 mp4_chunk_t *lastchunk = &p_demux_track->chunk[p_demux_track->i_chunk_count - 1];
1881 uint64_t i_total_size = lastchunk->i_offset;
1882 for( uint32_t i=0; i<lastchunk->i_sample_count; i++)
1884 if( p_demux_track->i_sample_size == 0 )
1885 i_total_size += stsz->i_entry_size[i];
1887 i_total_size += p_demux_track->i_sample_size;
1890 if ( i_total_size > p_sys->moovfragment.i_chunk_range_max_offset )
1891 p_sys->moovfragment.i_chunk_range_max_offset = i_total_size;
1894 /* Use stts table to create a sample number -> dts table.
1895 * XXX: if we don't want to waste too much memory, we can't expand
1896 * the box! so each chunk will contain an "extract" of this table
1897 * for fast research (problem with raw stream where a sample is sometime
1898 * just channels*bits_per_sample/8 */
1900 /* FIXME: refactor STTS & CTTS, STTS having now only few extra lines and
1901 * differing in 2/2 fields and 1 signedness */
1903 mtime_t i_next_dts = 0;
1905 * Gives mapping between sample and decoding time
1907 p_box = MP4_BoxGet( p_demux_track->p_stbl, "stts" );
1910 msg_Warn( p_demux, "cannot find STTS box" );
1911 return VLC_EGENERIC;
1915 MP4_Box_data_stts_t *stts = p_box->data.p_stts;
1917 msg_Warn( p_demux, "STTS table of %"PRIu32" entries", stts->i_entry_count );
1919 /* Create sample -> dts table per chunk */
1920 uint32_t i_index = 0;
1921 uint32_t i_current_index_samples_left = 0;
1923 for( uint32_t i_chunk = 0; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
1925 mp4_chunk_t *ck = &p_demux_track->chunk[i_chunk];
1926 uint32_t i_entry, i_sample_count;
1928 /* save first dts */
1929 ck->i_first_dts = i_next_dts;
1930 ck->i_last_dts = i_next_dts;
1932 /* count how many entries are needed for this chunk
1933 * for p_sample_delta_dts and p_sample_count_dts */
1936 int i_ret = xTTS_CountEntries( p_demux, &i_entry, i_index,
1937 i_current_index_samples_left,
1939 stts->pi_sample_count,
1940 stts->i_entry_count );
1941 if ( i_ret != VLC_SUCCESS )
1945 ck->p_sample_count_dts = calloc( i_entry, sizeof( uint32_t ) );
1946 ck->p_sample_delta_dts = calloc( i_entry, sizeof( uint32_t ) );
1947 if( !ck->p_sample_count_dts || !ck->p_sample_delta_dts )
1949 msg_Err( p_demux, "can't allocate memory for i_entry=%"PRIu32, i_entry );
1954 i_sample_count = ck->i_sample_count;
1956 for( uint32_t i = 0; i < i_entry; i++ )
1958 if ( i_current_index_samples_left )
1960 if ( i_current_index_samples_left > i_sample_count )
1962 if ( i_sample_count ) ck->i_last_dts = i_next_dts;
1963 ck->p_sample_count_dts[i] = i_sample_count;
1964 ck->p_sample_delta_dts[i] = stts->pi_sample_delta[i_index];
1965 i_next_dts += ck->p_sample_count_dts[i] * stts->pi_sample_delta[i_index];
1966 i_current_index_samples_left -= i_sample_count;
1968 assert( i == i_entry - 1 );
1973 if ( i_current_index_samples_left ) ck->i_last_dts = i_next_dts;
1974 ck->p_sample_count_dts[i] = i_current_index_samples_left;
1975 ck->p_sample_delta_dts[i] = stts->pi_sample_delta[i_index];
1976 i_next_dts += ck->p_sample_count_dts[i] * stts->pi_sample_delta[i_index];
1977 i_sample_count -= i_current_index_samples_left;
1978 i_current_index_samples_left = 0;
1984 if ( stts->pi_sample_count[i_index] > i_sample_count )
1986 if ( i_sample_count ) ck->i_last_dts = i_next_dts;
1987 ck->p_sample_count_dts[i] = i_sample_count;
1988 ck->p_sample_delta_dts[i] = stts->pi_sample_delta[i_index];
1989 i_next_dts += ck->p_sample_count_dts[i] * stts->pi_sample_delta[i_index];
1990 i_current_index_samples_left = stts->pi_sample_count[i_index] - i_sample_count;
1992 assert( i == i_entry - 1 );
1993 // keep building from same index
1997 if ( stts->pi_sample_count[i_index] ) ck->i_last_dts = i_next_dts;
1998 ck->p_sample_count_dts[i] = stts->pi_sample_count[i_index];
1999 ck->p_sample_delta_dts[i] = stts->pi_sample_delta[i_index];
2000 i_next_dts += ck->p_sample_count_dts[i] * stts->pi_sample_delta[i_index];
2001 i_sample_count -= stts->pi_sample_count[i_index];
2012 * Gives the delta between decoding time (dts) and composition table (pts)
2014 p_box = MP4_BoxGet( p_demux_track->p_stbl, "ctts" );
2015 if( p_box && p_box->data.p_ctts )
2017 MP4_Box_data_ctts_t *ctts = p_box->data.p_ctts;
2019 msg_Warn( p_demux, "CTTS table of %"PRIu32" entries", ctts->i_entry_count );
2021 /* Create pts-dts table per chunk */
2022 uint32_t i_index = 0;
2023 uint32_t i_current_index_samples_left = 0;
2025 for( uint32_t i_chunk = 0; i_chunk < p_demux_track->i_chunk_count; i_chunk++ )
2027 mp4_chunk_t *ck = &p_demux_track->chunk[i_chunk];
2028 uint32_t i_entry, i_sample_count;
2030 /* count how many entries are needed for this chunk
2031 * for p_sample_offset_pts and p_sample_count_pts */
2033 int i_ret = xTTS_CountEntries( p_demux, &i_entry, i_index,
2034 i_current_index_samples_left,
2036 ctts->pi_sample_count,
2037 ctts->i_entry_count );
2038 if ( i_ret != VLC_SUCCESS )
2042 ck->p_sample_count_pts = calloc( i_entry, sizeof( uint32_t ) );
2043 ck->p_sample_offset_pts = calloc( i_entry, sizeof( int32_t ) );
2044 if( !ck->p_sample_count_pts || !ck->p_sample_offset_pts )
2046 msg_Err( p_demux, "can't allocate memory for i_entry=%"PRIu32, i_entry );
2051 i_sample_count = ck->i_sample_count;
2053 for( uint32_t i = 0; i < i_entry; i++ )
2055 if ( i_current_index_samples_left )
2057 if ( i_current_index_samples_left > i_sample_count )
2059 ck->p_sample_count_pts[i] = i_sample_count;
2060 ck->p_sample_offset_pts[i] = ctts->pi_sample_offset[i_index];
2061 i_current_index_samples_left -= i_sample_count;
2063 assert( i == i_entry - 1 );
2068 ck->p_sample_count_pts[i] = i_current_index_samples_left;
2069 ck->p_sample_offset_pts[i] = ctts->pi_sample_offset[i_index];
2070 i_sample_count -= i_current_index_samples_left;
2071 i_current_index_samples_left = 0;
2077 if ( ctts->pi_sample_count[i_index] > i_sample_count )
2079 ck->p_sample_count_pts[i] = i_sample_count;
2080 ck->p_sample_offset_pts[i] = ctts->pi_sample_offset[i_index];
2081 i_current_index_samples_left = ctts->pi_sample_count[i_index] - i_sample_count;
2083 assert( i == i_entry - 1 );
2084 // keep building from same index
2088 ck->p_sample_count_pts[i] = ctts->pi_sample_count[i_index];
2089 ck->p_sample_offset_pts[i] = ctts->pi_sample_offset[i_index];
2090 i_sample_count -= ctts->pi_sample_count[i_index];
2100 msg_Dbg( p_demux, "track[Id 0x%x] read %"PRIu32" samples length:%"PRId64"s",
2101 p_demux_track->i_track_ID, p_demux_track->i_sample_count,
2102 i_next_dts / p_demux_track->i_timescale );
2109 * It computes the sample rate for a video track using the given sample
2112 static void TrackGetESSampleRate( demux_t *p_demux,
2113 unsigned *pi_num, unsigned *pi_den,
2114 const mp4_track_t *p_track,
2115 unsigned i_sd_index,
2121 MP4_Box_t *p_trak = MP4_GetTrakByTrackID( MP4_BoxGet( p_demux->p_sys->p_root, "/moov" ),
2122 p_track->i_track_ID );
2123 MP4_Box_t *p_mdhd = MP4_BoxGet( p_trak, "mdia/mdhd" );
2124 if ( p_mdhd && BOXDATA(p_mdhd) )
2126 vlc_ureduce( pi_num, pi_den,
2127 (uint64_t) BOXDATA(p_mdhd)->i_timescale * p_track->i_sample_count,
2128 (uint64_t) BOXDATA(p_mdhd)->i_duration,
2133 if( p_track->i_chunk_count <= 0 )
2137 const mp4_chunk_t *p_chunk = &p_track->chunk[i_chunk];
2138 while( p_chunk > &p_track->chunk[0] &&
2139 p_chunk[-1].i_sample_description_index == i_sd_index )
2144 uint64_t i_sample = 0;
2145 uint64_t i_first_dts = p_chunk->i_first_dts;
2146 uint64_t i_last_dts;
2149 i_sample += p_chunk->i_sample_count;
2150 i_last_dts = p_chunk->i_last_dts;
2153 while( p_chunk < &p_track->chunk[p_track->i_chunk_count] &&
2154 p_chunk->i_sample_description_index == i_sd_index );
2156 if( i_sample > 1 && i_first_dts < i_last_dts )
2157 vlc_ureduce( pi_num, pi_den,
2158 ( i_sample - 1) * p_track->i_timescale,
2159 i_last_dts - i_first_dts,
2165 * Create ES and PES to init decoder if needed, for a track starting at i_chunk
2167 static int TrackCreateES( demux_t *p_demux, mp4_track_t *p_track,
2168 unsigned int i_chunk, es_out_id_t **pp_es )
2170 demux_sys_t *p_sys = p_demux->p_sys;
2171 unsigned int i_sample_description_index;
2173 if( p_sys->b_fragmented )
2174 i_sample_description_index = 1; /* XXX */
2176 i_sample_description_index =
2177 p_track->chunk[i_chunk].i_sample_description_index;
2179 MP4_Box_t *p_sample;
2188 if( !i_sample_description_index )
2190 msg_Warn( p_demux, "invalid SampleEntry index (track[Id 0x%x])",
2191 p_track->i_track_ID );
2192 return VLC_EGENERIC;
2195 p_sample = MP4_BoxGet( p_track->p_stsd, "[%d]",
2196 i_sample_description_index - 1 );
2199 ( !p_sample->data.p_payload && p_track->fmt.i_cat != SPU_ES ) )
2201 msg_Warn( p_demux, "cannot find SampleEntry (track[Id 0x%x])",
2202 p_track->i_track_ID );
2203 return VLC_EGENERIC;
2206 p_track->p_sample = p_sample;
2208 if( ( p_frma = MP4_BoxGet( p_track->p_sample, "sinf/frma" ) ) && p_frma->data.p_frma )
2210 msg_Warn( p_demux, "Original Format Box: %4.4s", (char *)&p_frma->data.p_frma->i_type );
2212 p_sample->i_type = p_frma->data.p_frma->i_type;
2215 p_enda = MP4_BoxGet( p_sample, "wave/enda" );
2217 p_enda = MP4_BoxGet( p_sample, "enda" );
2219 p_pasp = MP4_BoxGet( p_sample, "pasp" );
2222 switch( p_track->fmt.i_cat )
2225 if ( !p_sample->data.p_sample_vide )
2227 p_track->fmt.video.i_width = p_sample->data.p_sample_vide->i_width;
2228 p_track->fmt.video.i_height = p_sample->data.p_sample_vide->i_height;
2229 p_track->fmt.video.i_bits_per_pixel =
2230 p_sample->data.p_sample_vide->i_depth;
2232 /* fall on display size */
2233 if( p_track->fmt.video.i_width <= 0 )
2234 p_track->fmt.video.i_width = p_track->i_width;
2235 if( p_track->fmt.video.i_height <= 0 )
2236 p_track->fmt.video.i_height = p_track->i_height;
2238 /* Find out apect ratio from display size */
2239 if( p_track->i_width > 0 && p_track->i_height > 0 &&
2240 /* Work-around buggy muxed files */
2241 p_sample->data.p_sample_vide->i_width != p_track->i_width )
2243 p_track->fmt.video.i_sar_num = p_track->i_width * p_track->fmt.video.i_height;
2244 p_track->fmt.video.i_sar_den = p_track->i_height * p_track->fmt.video.i_width;
2246 if( p_pasp && p_pasp->data.p_pasp->i_horizontal_spacing > 0 &&
2247 p_pasp->data.p_pasp->i_vertical_spacing > 0 )
2249 p_track->fmt.video.i_sar_num = p_pasp->data.p_pasp->i_horizontal_spacing;
2250 p_track->fmt.video.i_sar_den = p_pasp->data.p_pasp->i_vertical_spacing;
2253 /* Support for cropping (eg. in H263 files) */
2254 p_track->fmt.video.i_visible_width = p_track->fmt.video.i_width;
2255 p_track->fmt.video.i_visible_height = p_track->fmt.video.i_height;
2258 TrackGetESSampleRate( p_demux,
2259 &p_track->fmt.video.i_frame_rate,
2260 &p_track->fmt.video.i_frame_rate_base,
2261 p_track, i_sample_description_index, i_chunk );
2263 p_demux->p_sys->f_fps = (float)p_track->fmt.video.i_frame_rate /
2264 (float)p_track->fmt.video.i_frame_rate_base;
2267 switch( (int)p_track->f_rotation ) {
2269 p_track->fmt.video.orientation = ORIENT_ROTATED_90;
2272 p_track->fmt.video.orientation = ORIENT_ROTATED_180;
2275 p_track->fmt.video.orientation = ORIENT_ROTATED_270;
2282 if ( !p_sample->data.p_sample_soun )
2284 p_track->fmt.audio.i_channels =
2285 p_sample->data.p_sample_soun->i_channelcount;
2286 p_track->fmt.audio.i_rate =
2287 p_sample->data.p_sample_soun->i_sampleratehi;
2288 p_track->fmt.i_bitrate = p_sample->data.p_sample_soun->i_channelcount *
2289 p_sample->data.p_sample_soun->i_sampleratehi *
2290 p_sample->data.p_sample_soun->i_samplesize;
2291 p_track->fmt.audio.i_bitspersample =
2292 p_sample->data.p_sample_soun->i_samplesize;
2294 MP4_Box_data_sample_soun_t *p_soun = p_sample->data.p_sample_soun;
2296 p_track->fmt.i_original_fourcc = p_sample->i_type;
2298 if( ( p_track->i_sample_size == 1 || p_track->i_sample_size == 2 ) )
2300 if( p_soun->i_qt_version == 0 )
2302 switch( p_sample->i_type )
2304 case VLC_CODEC_ADPCM_IMA_QT:
2305 p_soun->i_qt_version = 1;
2306 p_soun->i_sample_per_packet = 64;
2307 p_soun->i_bytes_per_packet = 34;
2308 p_soun->i_bytes_per_frame = 34 * p_soun->i_channelcount;
2309 p_soun->i_bytes_per_sample = 2;
2311 case VLC_CODEC_MACE3:
2312 p_soun->i_qt_version = 1;
2313 p_soun->i_sample_per_packet = 6;
2314 p_soun->i_bytes_per_packet = 2;
2315 p_soun->i_bytes_per_frame = 2 * p_soun->i_channelcount;
2316 p_soun->i_bytes_per_sample = 2;
2318 case VLC_CODEC_MACE6:
2319 p_soun->i_qt_version = 1;
2320 p_soun->i_sample_per_packet = 12;
2321 p_soun->i_bytes_per_packet = 2;
2322 p_soun->i_bytes_per_frame = 2 * p_soun->i_channelcount;
2323 p_soun->i_bytes_per_sample = 2;
2325 case VLC_CODEC_ALAW:
2326 case VLC_FOURCC( 'u', 'l', 'a', 'w' ):
2327 p_soun->i_samplesize = 8;
2328 p_track->i_sample_size = p_soun->i_channelcount;
2330 case VLC_FOURCC( 'N', 'O', 'N', 'E' ):
2331 case VLC_FOURCC( 'r', 'a', 'w', ' ' ):
2332 case VLC_FOURCC( 't', 'w', 'o', 's' ):
2333 case VLC_FOURCC( 's', 'o', 'w', 't' ):
2334 /* What would be the fun if you could trust the .mov */
2335 p_track->i_sample_size = ((p_soun->i_samplesize+7)/8) * p_soun->i_channelcount;
2342 else if( p_soun->i_qt_version == 1 && p_soun->i_sample_per_packet <= 0 )
2344 p_soun->i_qt_version = 0;
2347 else if( p_sample->data.p_sample_soun->i_qt_version == 1 )
2349 switch( p_sample->i_type )
2351 case( VLC_FOURCC( '.', 'm', 'p', '3' ) ):
2352 case( VLC_FOURCC( 'm', 's', 0x00, 0x55 ) ):
2354 if( p_track->i_sample_size > 1 )
2355 p_soun->i_qt_version = 0;
2358 case( VLC_FOURCC( 'a', 'c', '-', '3' ) ):
2359 case( VLC_FOURCC( 'e', 'c', '-', '3' ) ):
2360 case( VLC_FOURCC( 'm', 's', 0x20, 0x00 ) ):
2361 p_soun->i_qt_version = 0;
2368 if( p_track->i_sample_size != 0 &&
2369 p_sample->data.p_sample_soun->i_qt_version == 1 &&
2370 p_sample->data.p_sample_soun->i_sample_per_packet <= 0 )
2372 msg_Err( p_demux, "Invalid sample per packet value for qt_version 1. Broken muxer!" );
2373 p_sample->data.p_sample_soun->i_qt_version = 0;
2376 /* Lookup for then channels extension */
2377 const MP4_Box_t *p_chan = MP4_BoxGet( p_sample, "chan" );
2380 if ( BOXDATA(p_chan)->layout.i_channels_layout_tag == MP4_CHAN_USE_CHANNELS_BITMAP )
2382 uint32_t rgi_chans_sequence[AOUT_CHAN_MAX + 1];
2383 uint16_t i_vlc_mapping = 0;
2384 uint8_t i_channels = 0;
2385 const uint32_t i_bitmap = BOXDATA(p_chan)->layout.i_channels_bitmap;
2386 for (uint8_t i=0;i<MP4_CHAN_BITMAP_MAPPING_COUNT;i++)
2388 if ( chan_bitmap_mapping[i].i_bitmap & i_bitmap )
2391 if ( (chan_bitmap_mapping[i].i_vlc & i_vlc_mapping) ||
2392 i_channels > AOUT_CHAN_MAX )
2394 /* double mapping or unsupported number of channels */
2396 msg_Warn( p_demux, "discarding chan mapping" );
2399 i_vlc_mapping |= chan_bitmap_mapping[i].i_vlc;
2400 rgi_chans_sequence[i_channels - 1] = chan_bitmap_mapping[i].i_vlc;
2403 rgi_chans_sequence[i_channels] = 0;
2404 p_track->b_chans_reorder = !!
2405 aout_CheckChannelReorder( rgi_chans_sequence, NULL, i_vlc_mapping,
2406 p_track->rgi_chans_reordering );
2418 /* It's a little ugly but .. there are special cases */
2419 switch( p_sample->i_type )
2421 case( VLC_FOURCC( '.', 'm', 'p', '3' ) ):
2422 case( VLC_FOURCC( 'm', 's', 0x00, 0x55 ) ):
2424 p_track->fmt.i_codec = VLC_CODEC_MPGA;
2427 case( VLC_FOURCC( 'a', 'c', '-', '3' ) ):
2429 MP4_Box_t *p_dac3_box = MP4_BoxGet( p_sample, "dac3", 0 );
2431 p_track->fmt.i_codec = VLC_CODEC_A52;
2434 static const int pi_bitrate[] = {
2441 MP4_Box_data_dac3_t *p_dac3 = p_dac3_box->data.p_dac3;
2442 p_track->fmt.audio.i_channels = 0;
2443 p_track->fmt.i_bitrate = 0;
2444 if( p_dac3->i_bitrate_code < sizeof(pi_bitrate)/sizeof(*pi_bitrate) )
2445 p_track->fmt.i_bitrate = pi_bitrate[p_dac3->i_bitrate_code] * 1000;
2446 p_track->fmt.audio.i_bitspersample = 0;
2450 case( VLC_FOURCC( 'e', 'c', '-', '3' ) ):
2452 p_track->fmt.i_codec = VLC_CODEC_EAC3;
2456 case( VLC_FOURCC( 'r', 'a', 'w', ' ' ) ):
2457 case( VLC_FOURCC( 'N', 'O', 'N', 'E' ) ):
2459 MP4_Box_data_sample_soun_t *p_soun = p_sample->data.p_sample_soun;
2461 if(p_soun && (p_soun->i_samplesize+7)/8 == 1 )
2462 p_track->fmt.i_codec = VLC_CODEC_U8;
2464 p_track->fmt.i_codec = VLC_FOURCC( 't', 'w', 'o', 's' );
2466 /* Buggy files workaround */
2467 if( p_sample->data.p_sample_soun && (p_track->i_timescale !=
2468 p_sample->data.p_sample_soun->i_sampleratehi) )
2470 msg_Warn( p_demux, "i_timescale (%"PRId32") != i_sampleratehi "
2471 "(%u), making both equal (report any problem).",
2472 p_track->i_timescale, p_soun->i_sampleratehi );
2474 if( p_soun->i_sampleratehi != 0 )
2475 p_track->i_timescale = p_soun->i_sampleratehi;
2477 p_soun->i_sampleratehi = p_track->i_timescale;
2482 case( VLC_FOURCC( 's', '2', '6', '3' ) ):
2483 p_track->fmt.i_codec = VLC_CODEC_H263;
2486 case( VLC_FOURCC( 't', 'e', 'x', 't' ) ):
2487 case( VLC_FOURCC( 't', 'x', '3', 'g' ) ):
2489 p_track->fmt.i_codec = VLC_CODEC_TX3G;
2490 MP4_Box_data_sample_text_t *p_text = p_sample->data.p_sample_text;
2493 text_style_t *p_style = text_style_New();
2496 if ( p_text->i_font_size ) /* !WARN: % in absolute storage */
2497 p_style->i_font_size = p_text->i_font_size;
2498 if ( p_text->i_font_color )
2500 p_style->i_font_color = p_text->i_font_color >> 8;
2501 p_style->i_font_alpha = p_text->i_font_color & 0xFF;
2503 if ( p_text->i_background_color[3] >> 8 )
2505 p_style->i_background_color = p_text->i_background_color[0] >> 8;
2506 p_style->i_background_color |= p_text->i_background_color[1] >> 8;
2507 p_style->i_background_color |= p_text->i_background_color[2] >> 8;
2508 p_style->i_background_alpha = p_text->i_background_color[3] >> 8;
2511 p_track->fmt.subs.p_style = p_style;
2513 /* FIXME UTF-8 doesn't work here ? */
2514 if( p_track->b_mac_encoding )
2515 p_track->fmt.subs.psz_encoding = strdup( "MAC" );
2517 p_track->fmt.subs.psz_encoding = strdup( "UTF-8" );
2520 case VLC_FOURCC('y','v','1','2'):
2521 p_track->fmt.i_codec = VLC_CODEC_YV12;
2523 case VLC_FOURCC('y','u','v','2'):
2524 p_track->fmt.i_codec = VLC_FOURCC('Y','U','Y','2');
2527 case VLC_FOURCC('i','n','2','4'):
2528 p_track->fmt.i_codec = p_enda && BOXDATA(p_enda)->i_little_endian == 1 ?
2529 VLC_FOURCC('4','2','n','i') : VLC_FOURCC('i','n','2','4');
2531 case VLC_FOURCC('i','n','3','2'):
2532 p_track->fmt.i_codec = p_enda && BOXDATA(p_enda)->i_little_endian == 1 ?
2533 VLC_CODEC_S32L : VLC_CODEC_S32B;
2535 case VLC_FOURCC('f','l','3','2'):
2536 p_track->fmt.i_codec = p_enda && BOXDATA(p_enda)->i_little_endian == 1 ?
2537 VLC_CODEC_F32L : VLC_CODEC_F32B;
2539 case VLC_FOURCC('f','l','6','4'):
2540 p_track->fmt.i_codec = p_enda && BOXDATA(p_enda)->i_little_endian == 1 ?
2541 VLC_CODEC_F64L : VLC_CODEC_F64B;
2543 case VLC_CODEC_DVD_LPCM:
2545 MP4_Box_data_sample_soun_t *p_soun = p_sample->data.p_sample_soun;
2546 if( p_soun->i_qt_version == 2 )
2553 static const struct {
2557 vlc_fourcc_t i_codec;
2559 { 0x01, 0x03, 32, VLC_CODEC_F32L },
2560 { 0x01, 0x03, 64, VLC_CODEC_F64L },
2561 { 0x01|0x02, 0x03, 32, VLC_CODEC_F32B },
2562 { 0x01|0x02, 0x03, 64, VLC_CODEC_F64B },
2564 { 0x00, 0x05, 8, VLC_CODEC_U8 },
2565 { 0x00| 0x04, 0x05, 8, VLC_CODEC_S8 },
2567 { 0x00, 0x07, 16, VLC_CODEC_U16L },
2568 { 0x00|0x02, 0x07, 16, VLC_CODEC_U16B },
2569 { 0x00 |0x04, 0x07, 16, VLC_CODEC_S16L },
2570 { 0x00|0x02|0x04, 0x07, 16, VLC_CODEC_S16B },
2572 { 0x00, 0x07, 24, VLC_CODEC_U24L },
2573 { 0x00|0x02, 0x07, 24, VLC_CODEC_U24B },
2574 { 0x00 |0x04, 0x07, 24, VLC_CODEC_S24L },
2575 { 0x00|0x02|0x04, 0x07, 24, VLC_CODEC_S24B },
2577 { 0x00, 0x07, 32, VLC_CODEC_U32L },
2578 { 0x00|0x02, 0x07, 32, VLC_CODEC_U32B },
2579 { 0x00 |0x04, 0x07, 32, VLC_CODEC_S32L },
2580 { 0x00|0x02|0x04, 0x07, 32, VLC_CODEC_S32B },
2585 for( int i = 0; p_formats[i].i_codec; i++ )
2587 if( p_formats[i].i_bits == p_soun->i_constbitsperchannel &&
2588 (p_soun->i_formatflags & p_formats[i].i_mask) == p_formats[i].i_flags )
2590 p_track->fmt.i_codec = p_formats[i].i_codec;
2591 p_track->fmt.audio.i_bitspersample = p_soun->i_constbitsperchannel;
2592 p_track->fmt.audio.i_blockalign =
2593 p_soun->i_channelcount * p_soun->i_constbitsperchannel / 8;
2594 p_track->i_sample_size = p_track->fmt.audio.i_blockalign;
2596 p_soun->i_qt_version = 0;
2604 p_track->fmt.i_codec = p_sample->i_type;
2608 /* now see if esds is present and if so create a data packet
2609 with decoder_specific_info */
2610 #define p_decconfig p_esds->data.p_esds->es_descriptor.p_decConfigDescr
2611 if( ( ( p_esds = MP4_BoxGet( p_sample, "esds" ) ) ||
2612 ( p_esds = MP4_BoxGet( p_sample, "wave/esds" ) ) )&&
2613 ( p_esds->data.p_esds )&&
2616 /* First update information based on i_objectTypeIndication */
2617 switch( p_decconfig->i_objectTypeIndication )
2619 case( 0x20 ): /* MPEG4 VIDEO */
2620 p_track->fmt.i_codec = VLC_CODEC_MP4V;
2622 case( 0x21 ): /* H.264 */
2623 p_track->fmt.i_codec = VLC_CODEC_H264;
2626 p_track->fmt.i_codec = VLC_CODEC_MP4A;
2627 if( p_decconfig->i_decoder_specific_info_len >= 2 &&
2628 p_decconfig->p_decoder_specific_info[0] == 0xF8 &&
2629 (p_decconfig->p_decoder_specific_info[1]&0xE0) == 0x80 )
2631 p_track->fmt.i_codec = VLC_CODEC_ALS;
2639 case( 0x65): /* MPEG2 video */
2640 p_track->fmt.i_codec = VLC_CODEC_MPGV;
2642 /* Theses are MPEG2-AAC */
2643 case( 0x66): /* main profile */
2644 case( 0x67): /* Low complexity profile */
2645 case( 0x68): /* Scaleable Sampling rate profile */
2646 p_track->fmt.i_codec = VLC_CODEC_MP4A;
2648 /* True MPEG 2 audio */
2650 p_track->fmt.i_codec = VLC_CODEC_MPGA;
2652 case( 0x6a): /* MPEG1 video */
2653 p_track->fmt.i_codec = VLC_CODEC_MPGV;
2655 case( 0x6b): /* MPEG1 audio */
2656 p_track->fmt.i_codec = VLC_CODEC_MPGA;
2658 case( 0x6c ): /* jpeg */
2659 p_track->fmt.i_codec = VLC_CODEC_JPEG;
2661 case( 0x6d ): /* png */
2662 p_track->fmt.i_codec = VLC_CODEC_PNG;
2664 case( 0x6e ): /* jpeg2000 */
2665 p_track->fmt.i_codec = VLC_FOURCC( 'M','J','2','C' );
2667 case( 0xa3 ): /* vc1 */
2668 p_track->fmt.i_codec = VLC_CODEC_VC1;
2671 p_track->fmt.i_codec = VLC_CODEC_DIRAC;
2674 p_track->fmt.i_codec = VLC_CODEC_A52;
2677 p_track->fmt.i_codec = VLC_CODEC_EAC3;
2679 case( 0xa9 ): /* dts */
2680 case( 0xaa ): /* DTS-HD HRA */
2681 case( 0xab ): /* DTS-HD Master Audio */
2682 p_track->fmt.i_codec = VLC_CODEC_DTS;
2685 p_track->fmt.i_codec = VLC_CODEC_VORBIS;
2689 case( 0xe0 ): /* NeroDigital: dvd subs */
2690 if( p_track->fmt.i_cat == SPU_ES )
2692 p_track->fmt.i_codec = VLC_CODEC_SPU;
2693 if( p_track->i_width > 0 )
2694 p_track->fmt.subs.spu.i_original_frame_width = p_track->i_width;
2695 if( p_track->i_height > 0 )
2696 p_track->fmt.subs.spu.i_original_frame_height = p_track->i_height;
2699 case( 0xe1 ): /* QCelp for 3gp */
2700 if( p_track->fmt.i_cat == AUDIO_ES )
2702 p_track->fmt.i_codec = VLC_CODEC_QCELP;
2708 /* Unknown entry, but don't touch i_fourcc */
2710 "unknown objectTypeIndication(0x%x) (Track[ID 0x%x])",
2711 p_decconfig->i_objectTypeIndication,
2712 p_track->i_track_ID );
2715 p_track->fmt.i_extra = p_decconfig->i_decoder_specific_info_len;
2716 if( p_track->fmt.i_extra > 0 )
2718 p_track->fmt.p_extra = malloc( p_track->fmt.i_extra );
2719 memcpy( p_track->fmt.p_extra, p_decconfig->p_decoder_specific_info,
2720 p_track->fmt.i_extra );
2722 if( p_track->fmt.i_codec == VLC_CODEC_SPU &&
2723 p_track->fmt.i_extra >= 16 * 4 )
2725 for( int i = 0; i < 16; i++ )
2727 p_track->fmt.subs.spu.palette[1 + i] =
2728 GetDWBE((char*)p_track->fmt.p_extra + i * 4);
2730 p_track->fmt.subs.spu.palette[0] = 0xBeef;
2735 switch( p_sample->i_type )
2737 /* qt decoder, send the complete chunk */
2738 case VLC_FOURCC ('h', 'd', 'v', '1'): // HDV 720p30
2739 case VLC_FOURCC ('h', 'd', 'v', '2'): // HDV 1080i60
2740 case VLC_FOURCC ('h', 'd', 'v', '3'): // HDV 1080i50
2741 case VLC_FOURCC ('h', 'd', 'v', '5'): // HDV 720p25
2742 case VLC_FOURCC ('m', 'x', '5', 'n'): // MPEG2 IMX NTSC 525/60 50mb/s produced by FCP
2743 case VLC_FOURCC ('m', 'x', '5', 'p'): // MPEG2 IMX PAL 625/60 50mb/s produced by FCP
2744 case VLC_FOURCC ('m', 'x', '4', 'n'): // MPEG2 IMX NTSC 525/60 40mb/s produced by FCP
2745 case VLC_FOURCC ('m', 'x', '4', 'p'): // MPEG2 IMX PAL 625/60 40mb/s produced by FCP
2746 case VLC_FOURCC ('m', 'x', '3', 'n'): // MPEG2 IMX NTSC 525/60 30mb/s produced by FCP
2747 case VLC_FOURCC ('m', 'x', '3', 'p'): // MPEG2 IMX PAL 625/50 30mb/s produced by FCP
2748 case VLC_FOURCC ('x', 'd', 'v', '2'): // XDCAM HD 1080i60
2749 case VLC_FOURCC ('A', 'V', 'm', 'p'): // AVID IMX PAL
2750 p_track->fmt.i_codec = VLC_CODEC_MPGV;
2752 /* qt decoder, send the complete chunk */
2753 case VLC_CODEC_SVQ1:
2754 case VLC_CODEC_SVQ3:
2755 case VLC_FOURCC( 'V', 'P', '3', '1' ):
2756 case VLC_FOURCC( '3', 'I', 'V', '1' ):
2757 case VLC_FOURCC( 'Z', 'y', 'G', 'o' ):
2758 p_track->fmt.i_extra =
2759 p_sample->data.p_sample_vide->i_qt_image_description;
2760 if( p_track->fmt.i_extra > 0 )
2762 p_track->fmt.p_extra = malloc( p_track->fmt.i_extra );
2763 memcpy( p_track->fmt.p_extra,
2764 p_sample->data.p_sample_vide->p_qt_image_description,
2765 p_track->fmt.i_extra);
2769 case VLC_CODEC_AMR_NB:
2770 p_track->fmt.audio.i_rate = 8000;
2772 case VLC_CODEC_AMR_WB:
2773 p_track->fmt.audio.i_rate = 16000;
2775 case VLC_FOURCC( 'Q', 'D', 'M', 'C' ):
2776 case VLC_CODEC_QDM2:
2777 case VLC_CODEC_ALAC:
2778 p_track->fmt.i_extra =
2779 p_sample->data.p_sample_soun->i_qt_description;
2780 if( p_track->fmt.i_extra > 0 )
2782 p_track->fmt.p_extra = malloc( p_track->fmt.i_extra );
2783 memcpy( p_track->fmt.p_extra,
2784 p_sample->data.p_sample_soun->p_qt_description,
2785 p_track->fmt.i_extra);
2787 if( p_track->fmt.i_extra == 56 && p_sample->i_type == VLC_CODEC_ALAC )
2789 p_track->fmt.audio.i_channels = *((uint8_t*)p_track->fmt.p_extra + 41);
2790 p_track->fmt.audio.i_rate = GetDWBE((uint8_t*)p_track->fmt.p_extra + 52);
2794 case VLC_FOURCC( 'v', 'c', '-', '1' ):
2796 MP4_Box_t *p_dvc1 = MP4_BoxGet( p_sample, "dvc1" );
2799 p_track->fmt.i_extra = BOXDATA(p_dvc1)->i_vc1;
2800 if( p_track->fmt.i_extra > 0 )
2802 p_track->fmt.p_extra = malloc( BOXDATA(p_dvc1)->i_vc1 );
2803 memcpy( p_track->fmt.p_extra, BOXDATA(p_dvc1)->p_vc1,
2804 p_track->fmt.i_extra );
2809 msg_Err( p_demux, "missing dvc1" );
2814 /* avc1: send avcC (h264 without annexe B, ie without start code)*/
2815 case VLC_FOURCC( 'a', 'v', 'c', '1' ):
2817 MP4_Box_t *p_avcC = MP4_BoxGet( p_sample, "avcC" );
2821 p_track->fmt.i_extra = BOXDATA(p_avcC)->i_avcC;
2822 if( p_track->fmt.i_extra > 0 )
2824 p_track->fmt.p_extra = malloc( BOXDATA(p_avcC)->i_avcC );
2825 memcpy( p_track->fmt.p_extra, BOXDATA(p_avcC)->p_avcC,
2826 p_track->fmt.i_extra );
2831 msg_Err( p_demux, "missing avcC" );
2835 case VLC_FOURCC( 'h', 'v', 'c', '1' ):
2836 case VLC_FOURCC( 'h', 'e', 'v', '1' ):
2838 MP4_Box_t *p_hvcC = MP4_BoxGet( p_sample, "hvcC" );
2842 p_track->fmt.i_extra = p_hvcC->data.p_hvcC->i_hvcC;
2843 if( p_track->fmt.i_extra > 0 )
2845 p_track->fmt.p_extra = malloc( p_hvcC->data.p_hvcC->i_hvcC );
2846 memcpy( p_track->fmt.p_extra, p_hvcC->data.p_hvcC->p_hvcC,
2847 p_track->fmt.i_extra );
2849 p_track->fmt.i_codec = VLC_CODEC_HEVC;
2853 msg_Err( p_demux, "missing hvcC" );
2859 case VLC_CODEC_ADPCM_MS:
2860 case VLC_CODEC_ADPCM_IMA_WAV:
2861 case VLC_CODEC_QCELP:
2862 p_track->fmt.audio.i_blockalign = p_sample->data.p_sample_soun->i_bytes_per_frame;
2866 msg_Dbg( p_demux, "Unrecognized FourCC %4.4s", (char *)&p_sample->i_type );
2874 *pp_es = es_out_Add( p_demux->out, &p_track->fmt );
2879 /* given a time it return sample/chunk
2880 * it also update elst field of the track
2882 static int TrackTimeToSampleChunk( demux_t *p_demux, mp4_track_t *p_track,
2883 int64_t i_start, uint32_t *pi_chunk,
2884 uint32_t *pi_sample )
2886 demux_sys_t *p_sys = p_demux->p_sys;
2887 MP4_Box_t *p_box_stss;
2889 unsigned int i_sample;
2890 unsigned int i_chunk;
2893 /* FIXME see if it's needed to check p_track->i_chunk_count */
2894 if( p_track->i_chunk_count == 0 )
2895 return( VLC_EGENERIC );
2897 /* handle elst (find the correct one) */
2898 MP4_TrackSetELST( p_demux, p_track, i_start );
2899 if( p_track->p_elst && p_track->BOXDATA(p_elst)->i_entry_count > 0 )
2901 MP4_Box_data_elst_t *elst = p_track->BOXDATA(p_elst);
2902 int64_t i_mvt= i_start * p_sys->i_timescale / CLOCK_FREQ;
2904 /* now calculate i_start for this elst */
2906 i_start -= p_track->i_elst_time * CLOCK_FREQ / p_sys->i_timescale;
2914 /* to track time scale */
2915 i_start = i_start * p_track->i_timescale / CLOCK_FREQ;
2916 /* add elst offset */
2917 if( ( elst->i_media_rate_integer[p_track->i_elst] > 0 ||
2918 elst->i_media_rate_fraction[p_track->i_elst] > 0 ) &&
2919 elst->i_media_time[p_track->i_elst] > 0 )
2921 i_start += elst->i_media_time[p_track->i_elst];
2924 msg_Dbg( p_demux, "elst (%d) gives %"PRId64"ms (movie)-> %"PRId64
2925 "ms (track)", p_track->i_elst,
2926 i_mvt * 1000 / p_sys->i_timescale,
2927 i_start * 1000 / p_track->i_timescale );
2931 /* convert absolute time to in timescale unit */
2932 i_start = i_start * p_track->i_timescale / CLOCK_FREQ;
2935 /* we start from sample 0/chunk 0, hope it won't take too much time */
2936 /* *** find good chunk *** */
2937 for( i_chunk = 0; ; i_chunk++ )
2939 if( i_chunk + 1 >= p_track->i_chunk_count )
2941 /* at the end and can't check if i_start in this chunk,
2942 it will be check while searching i_sample */
2943 i_chunk = p_track->i_chunk_count - 1;
2947 if( (uint64_t)i_start >= p_track->chunk[i_chunk].i_first_dts &&
2948 (uint64_t)i_start < p_track->chunk[i_chunk + 1].i_first_dts )
2954 /* *** find sample in the chunk *** */
2955 i_sample = p_track->chunk[i_chunk].i_sample_first;
2956 i_dts = p_track->chunk[i_chunk].i_first_dts;
2957 for( i_index = 0; i_sample < p_track->chunk[i_chunk].i_sample_count; )
2960 p_track->chunk[i_chunk].p_sample_count_dts[i_index] *
2961 p_track->chunk[i_chunk].p_sample_delta_dts[i_index] < (uint64_t)i_start )
2964 p_track->chunk[i_chunk].p_sample_count_dts[i_index] *
2965 p_track->chunk[i_chunk].p_sample_delta_dts[i_index];
2967 i_sample += p_track->chunk[i_chunk].p_sample_count_dts[i_index];
2972 if( p_track->chunk[i_chunk].p_sample_delta_dts[i_index] <= 0 )
2976 i_sample += ( i_start - i_dts ) /
2977 p_track->chunk[i_chunk].p_sample_delta_dts[i_index];
2982 if( i_sample >= p_track->i_sample_count )
2984 msg_Warn( p_demux, "track[Id 0x%x] will be disabled "
2985 "(seeking too far) chunk=%d sample=%d",
2986 p_track->i_track_ID, i_chunk, i_sample );
2987 return( VLC_EGENERIC );
2991 /* *** Try to find nearest sync points *** */
2992 if( ( p_box_stss = MP4_BoxGet( p_track->p_stbl, "stss" ) ) )
2994 MP4_Box_data_stss_t *p_stss = p_box_stss->data.p_stss;
2995 msg_Dbg( p_demux, "track[Id 0x%x] using Sync Sample Box (stss)",
2996 p_track->i_track_ID );
2997 for( unsigned i_index = 0; i_index < p_stss->i_entry_count; i_index++ )
2999 if( i_index >= p_stss->i_entry_count - 1 ||
3000 i_sample < p_stss->i_sample_number[i_index+1] )
3002 unsigned i_sync_sample = p_stss->i_sample_number[i_index];
3003 msg_Dbg( p_demux, "stss gives %d --> %d (sample number)",
3004 i_sample, i_sync_sample );
3006 if( i_sync_sample <= i_sample )
3008 while( i_chunk > 0 &&
3009 i_sync_sample < p_track->chunk[i_chunk].i_sample_first )
3014 while( i_chunk < p_track->i_chunk_count - 1 &&
3015 i_sync_sample >= p_track->chunk[i_chunk].i_sample_first +
3016 p_track->chunk[i_chunk].i_sample_count )
3019 i_sample = i_sync_sample;
3026 msg_Dbg( p_demux, "track[Id 0x%x] does not provide Sync "
3027 "Sample Box (stss)", p_track->i_track_ID );
3030 *pi_chunk = i_chunk;
3031 *pi_sample = i_sample;
3036 static int TrackGotoChunkSample( demux_t *p_demux, mp4_track_t *p_track,
3037 unsigned int i_chunk, unsigned int i_sample )
3039 bool b_reselect = false;
3041 /* now see if actual es is ok */
3042 if( p_track->i_chunk >= p_track->i_chunk_count ||
3043 p_track->chunk[p_track->i_chunk].i_sample_description_index !=
3044 p_track->chunk[i_chunk].i_sample_description_index )
3046 msg_Warn( p_demux, "recreate ES for track[Id 0x%x]",
3047 p_track->i_track_ID );
3049 es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE,
3050 p_track->p_es, &b_reselect );
3052 es_out_Del( p_demux->out, p_track->p_es );
3054 p_track->p_es = NULL;
3056 if( TrackCreateES( p_demux, p_track, i_chunk, &p_track->p_es ) )
3058 msg_Err( p_demux, "cannot create es for track[Id 0x%x]",
3059 p_track->i_track_ID );
3061 p_track->b_ok = false;
3062 p_track->b_selected = false;
3063 return VLC_EGENERIC;
3067 /* select again the new decoder */
3070 es_out_Control( p_demux->out, ES_OUT_SET_ES, p_track->p_es );
3073 p_track->i_chunk = i_chunk;
3074 p_track->i_sample = i_sample;
3076 return p_track->b_selected ? VLC_SUCCESS : VLC_EGENERIC;
3079 /****************************************************************************
3081 ****************************************************************************
3082 * Parse track information and create all needed data to run a track
3083 * If it succeed b_ok is set to 1 else to 0
3084 ****************************************************************************/
3085 static void MP4_TrackCreate( demux_t *p_demux, mp4_track_t *p_track,
3086 MP4_Box_t *p_box_trak,
3087 bool b_force_enable )
3089 demux_sys_t *p_sys = p_demux->p_sys;
3091 MP4_Box_t *p_tkhd = MP4_BoxGet( p_box_trak, "tkhd" );
3092 MP4_Box_t *p_tref = MP4_BoxGet( p_box_trak, "tref" );
3102 char language[4] = { '\0' };
3104 /* hint track unsupported */
3106 /* set default value (-> track unusable) */
3107 p_track->b_ok = false;
3108 p_track->b_enable = false;
3109 p_track->b_selected = false;
3110 p_track->b_chapter = false;
3111 p_track->b_mac_encoding = false;
3113 es_format_Init( &p_track->fmt, UNKNOWN_ES, 0 );
3120 /* do we launch this track by default ? */
3122 ( ( BOXDATA(p_tkhd)->i_flags&MP4_TRACK_ENABLED ) != 0 );
3123 if( !p_track->b_enable )
3124 p_track->fmt.i_priority = ES_PRIORITY_NOT_DEFAULTABLE;
3126 p_track->i_track_ID = BOXDATA(p_tkhd)->i_track_ID;
3128 p_track->i_width = BOXDATA(p_tkhd)->i_width / BLOCK16x16;
3129 p_track->i_height = BOXDATA(p_tkhd)->i_height / BLOCK16x16;
3130 p_track->f_rotation = BOXDATA(p_tkhd)->f_rotation;
3134 /* msg_Warn( p_demux, "unhandled box: tref --> FIXME" ); */
3137 p_mdhd = MP4_BoxGet( p_box_trak, "mdia/mdhd" );
3138 p_hdlr = MP4_BoxGet( p_box_trak, "mdia/hdlr" );
3140 if( ( !p_mdhd )||( !p_hdlr ) )
3145 p_track->i_timescale = BOXDATA(p_mdhd)->i_timescale;
3146 if( p_track->i_timescale == 0 )
3149 if( BOXDATA(p_mdhd)->i_language_code < 0x400 )
3151 strcpy( language, MP4_ConvertMacCode( BOXDATA(p_mdhd)->i_language_code ) );
3152 p_track->b_mac_encoding = true;
3154 else if( BOXDATA(p_mdhd)->i_language_code == 0x7fff )
3155 p_track->b_mac_encoding = true;
3158 for( unsigned i = 0; i < 3; i++ )
3159 language[i] = BOXDATA(p_mdhd)->i_language[i];
3163 switch( p_hdlr->data.p_hdlr->i_handler_type )
3166 if( !( p_smhd = MP4_BoxGet( p_box_trak, "mdia/minf/smhd" ) ) )
3170 p_track->fmt.i_cat = AUDIO_ES;
3174 if( !( p_vmhd = MP4_BoxGet( p_box_trak, "mdia/minf/vmhd" ) ) )
3178 p_track->fmt.i_cat = VIDEO_ES;
3185 p_track->fmt.i_codec = VLC_CODEC_TX3G;
3186 p_track->fmt.i_cat = SPU_ES;
3193 p_track->i_elst = 0;
3194 p_track->i_elst_time = 0;
3195 if( ( p_track->p_elst = p_elst = MP4_BoxGet( p_box_trak, "edts/elst" ) ) )
3197 MP4_Box_data_elst_t *elst = BOXDATA(p_elst);
3200 msg_Warn( p_demux, "elst box found" );
3201 for( i = 0; i < elst->i_entry_count; i++ )
3203 msg_Dbg( p_demux, " - [%d] duration=%"PRId64"ms media time=%"PRId64
3204 "ms) rate=%d.%d", i,
3205 elst->i_segment_duration[i] * 1000 / p_sys->i_timescale,
3206 elst->i_media_time[i] >= 0 ?
3207 (int64_t)(elst->i_media_time[i] * 1000 / p_track->i_timescale) :
3209 elst->i_media_rate_integer[i],
3210 elst->i_media_rate_fraction[i] );
3217 p_dinf = MP4_BoxGet( p_minf, "dinf" );
3219 if( !( p_track->p_stbl = MP4_BoxGet( p_box_trak,"mdia/minf/stbl" ) ) ||
3220 !( p_track->p_stsd = MP4_BoxGet( p_box_trak,"mdia/minf/stbl/stsd") ) )
3226 if( *language && strcmp( language, "```" ) && strcmp( language, "und" ) )
3228 p_track->fmt.psz_language = strdup( language );
3231 p_udta = MP4_BoxGet( p_box_trak, "udta" );
3234 MP4_Box_t *p_box_iter;
3235 for( p_box_iter = p_udta->p_first; p_box_iter != NULL;
3236 p_box_iter = p_box_iter->p_next )
3238 switch( p_box_iter->i_type )
3241 p_track->fmt.psz_description =
3242 strdup( p_box_iter->data.p_0xa9xxx->psz_text );
3245 p_track->fmt.psz_description =
3246 strdup( p_box_iter->data.p_name->psz_text );
3252 /* Create chunk index table and sample index table */
3253 if( TrackCreateChunksIndex( p_demux,p_track ) ||
3254 TrackCreateSamplesIndex( p_demux, p_track ) )
3256 msg_Err( p_demux, "cannot create chunks index" );
3257 return; /* cannot create chunks index */
3260 p_track->i_chunk = 0;
3261 p_track->i_sample = 0;
3263 /* Mark chapter only track */
3264 if( p_sys->p_tref_chap )
3266 MP4_Box_data_tref_generic_t *p_chap = p_sys->p_tref_chap->data.p_tref_generic;
3269 for( i = 0; i < p_chap->i_entry_count; i++ )
3271 if( p_track->i_track_ID == p_chap->i_track_ID[i] &&
3272 p_track->fmt.i_cat == UNKNOWN_ES )
3274 p_track->b_chapter = true;
3275 p_track->b_enable = false;
3282 if( b_force_enable &&
3283 ( p_track->fmt.i_cat == VIDEO_ES || p_track->fmt.i_cat == AUDIO_ES ) )
3285 msg_Warn( p_demux, "Enabling track[Id 0x%x] (buggy file without enabled track)",
3286 p_track->i_track_ID );
3287 p_track->b_enable = true;
3288 p_track->fmt.i_priority = ES_PRIORITY_SELECTABLE_MIN;
3291 p_track->p_es = NULL;
3292 if( TrackCreateES( p_demux,
3293 p_track, p_track->i_chunk,
3294 p_track->b_chapter ? NULL : &p_track->p_es ) )
3296 msg_Err( p_demux, "cannot create es for track[Id 0x%x]",
3297 p_track->i_track_ID );
3300 p_track->b_ok = true;
3304 for( i = 0; i < p_track->i_chunk_count; i++ )
3306 fprintf( stderr, "%-5d sample_count=%d pts=%lld\n",
3307 i, p_track->chunk[i].i_sample_count,
3308 p_track->chunk[i].i_first_dts );
3315 static void FreeAndResetChunk( mp4_chunk_t *ck )
3317 free( ck->p_sample_count_dts );
3318 free( ck->p_sample_delta_dts );
3319 free( ck->p_sample_count_pts );
3320 free( ck->p_sample_offset_pts );
3321 free( ck->p_sample_size );
3322 for( uint32_t i = 0; i < ck->i_sample_count; i++ )
3323 free( ck->p_sample_data[i] );
3324 free( ck->p_sample_data );
3325 memset( ck, 0, sizeof( mp4_chunk_t ) );
3328 /****************************************************************************
3330 ****************************************************************************
3331 * Destroy a track created by MP4_TrackCreate.
3332 ****************************************************************************/
3333 static void MP4_TrackDestroy( mp4_track_t *p_track )
3335 unsigned int i_chunk;
3337 p_track->b_ok = false;
3338 p_track->b_enable = false;
3339 p_track->b_selected = false;
3341 es_format_Clean( &p_track->fmt );
3343 for( i_chunk = 0; i_chunk < p_track->i_chunk_count; i_chunk++ )
3345 if( p_track->chunk )
3347 FREENULL(p_track->chunk[i_chunk].p_sample_count_dts);
3348 FREENULL(p_track->chunk[i_chunk].p_sample_delta_dts );
3350 FREENULL(p_track->chunk[i_chunk].p_sample_count_pts);
3351 FREENULL(p_track->chunk[i_chunk].p_sample_offset_pts );
3354 FREENULL( p_track->chunk );
3355 if( p_track->cchunk ) {
3356 FreeAndResetChunk( p_track->cchunk );
3357 FREENULL( p_track->cchunk );
3360 if( !p_track->i_sample_size )
3362 FREENULL( p_track->p_sample_size );
3366 static int MP4_TrackSelect( demux_t *p_demux, mp4_track_t *p_track,
3369 if( !p_track->b_ok || p_track->b_chapter )
3371 return VLC_EGENERIC;
3374 if( p_track->b_selected )
3376 msg_Warn( p_demux, "track[Id 0x%x] already selected",
3377 p_track->i_track_ID );
3381 return MP4_TrackSeek( p_demux, p_track, i_start );
3384 static void MP4_TrackUnselect( demux_t *p_demux, mp4_track_t *p_track )
3386 if( !p_track->b_ok || p_track->b_chapter )
3391 if( !p_track->b_selected )
3393 msg_Warn( p_demux, "track[Id 0x%x] already unselected",
3394 p_track->i_track_ID );
3399 es_out_Control( p_demux->out, ES_OUT_SET_ES_STATE,
3400 p_track->p_es, false );
3403 p_track->b_selected = false;
3406 static int MP4_TrackSeek( demux_t *p_demux, mp4_track_t *p_track,
3412 if( !p_track->b_ok || p_track->b_chapter )
3413 return VLC_EGENERIC;
3415 p_track->b_selected = false;
3417 if( TrackTimeToSampleChunk( p_demux, p_track, i_start,
3418 &i_chunk, &i_sample ) )
3420 msg_Warn( p_demux, "cannot select track[Id 0x%x]",
3421 p_track->i_track_ID );
3422 return VLC_EGENERIC;
3425 p_track->b_selected = true;
3426 if( !TrackGotoChunkSample( p_demux, p_track, i_chunk, i_sample ) )
3427 p_track->b_selected = true;
3429 return p_track->b_selected ? VLC_SUCCESS : VLC_EGENERIC;
3434 * 3 types: for audio
3437 #define QT_V0_MAX_SAMPLES 1024
3438 static uint32_t MP4_TrackGetReadSize( mp4_track_t *p_track, uint32_t *pi_nb_samples )
3440 uint32_t i_size = 0;
3443 if ( p_track->i_sample == p_track->i_sample_count )
3446 if ( p_track->fmt.i_cat != AUDIO_ES )
3450 if( p_track->i_sample_size == 0 ) /* all sizes are different */
3451 return p_track->p_sample_size[p_track->i_sample];
3453 return p_track->i_sample_size;
3457 const MP4_Box_data_sample_soun_t *p_soun = p_track->p_sample->data.p_sample_soun;
3458 const mp4_chunk_t *p_chunk = &p_track->chunk[p_track->i_chunk];
3459 uint32_t i_max_samples = p_chunk->i_sample_count - p_chunk->i_sample + 1;
3461 /* Group audio packets so we don't call demux for single sample unit */
3462 if( p_track->fmt.i_original_fourcc == VLC_CODEC_DVD_LPCM &&
3463 p_soun->i_constLPCMframesperaudiopacket &&
3464 p_soun->i_constbytesperaudiopacket )
3466 /* uncompressed case */
3467 uint32_t i_packets = i_max_samples / p_soun->i_constLPCMframesperaudiopacket;
3468 if ( UINT32_MAX / p_soun->i_constbytesperaudiopacket < i_packets )
3469 i_packets = UINT32_MAX / p_soun->i_constbytesperaudiopacket;
3470 *pi_nb_samples = i_packets * p_soun->i_constLPCMframesperaudiopacket;
3471 return i_packets * p_soun->i_constbytesperaudiopacket;
3474 /* all samples have a different size */
3475 if( p_track->i_sample_size == 0 )
3478 return p_track->p_sample_size[p_track->i_sample];
3481 if( p_soun->i_qt_version == 1 )
3483 if ( p_soun->i_compressionid != 0 || p_soun->i_bytes_per_sample > 1 ) /* compressed */
3485 /* in this case we are dealing with compressed data
3486 -2 in V1: additional fields are meaningless (VBR and such) */
3487 *pi_nb_samples = i_max_samples;//p_track->chunk[p_track->i_chunk].i_sample_count;
3488 if( p_track->fmt.audio.i_blockalign > 1 )
3489 *pi_nb_samples = p_soun->i_sample_per_packet;
3490 i_size = *pi_nb_samples / p_soun->i_sample_per_packet * p_soun->i_bytes_per_frame;
3493 else /* uncompressed case */
3496 if( p_track->fmt.audio.i_blockalign > 1 )
3499 i_packets = i_max_samples / p_soun->i_sample_per_packet;
3501 if ( UINT32_MAX / p_soun->i_bytes_per_frame < i_packets )
3502 i_packets = UINT32_MAX / p_soun->i_bytes_per_frame;
3504 *pi_nb_samples = i_packets * p_soun->i_sample_per_packet;
3505 i_size = i_packets * p_soun->i_bytes_per_frame;
3510 /* uncompressed v0 */
3512 for( uint32_t i=p_track->i_sample;
3513 i<p_chunk->i_sample_first+p_chunk->i_sample_count &&
3514 i<p_track->i_sample_count;
3518 if ( p_track->i_sample_size == 0 )
3519 i_size += p_track->p_sample_size[i];
3521 i_size += p_track->i_sample_size;
3522 if ( *pi_nb_samples == QT_V0_MAX_SAMPLES )
3527 //fprintf( stderr, "size=%d\n", i_size );
3531 static uint64_t MP4_TrackGetPos( mp4_track_t *p_track )
3533 unsigned int i_sample;
3536 i_pos = p_track->chunk[p_track->i_chunk].i_offset;
3538 if( p_track->i_sample_size )
3540 MP4_Box_data_sample_soun_t *p_soun =
3541 p_track->p_sample->data.p_sample_soun;
3543 if( p_track->fmt.i_cat != AUDIO_ES || p_soun->i_qt_version == 0 )
3545 i_pos += ( p_track->i_sample -
3546 p_track->chunk[p_track->i_chunk].i_sample_first ) *
3547 p_track->i_sample_size;
3551 /* we read chunk by chunk unless a blockalign is requested */
3552 if( p_track->fmt.audio.i_blockalign > 1 )
3553 i_pos += ( p_track->i_sample - p_track->chunk[p_track->i_chunk].i_sample_first ) /
3554 p_soun->i_sample_per_packet * p_soun->i_bytes_per_frame;
3559 for( i_sample = p_track->chunk[p_track->i_chunk].i_sample_first;
3560 i_sample < p_track->i_sample; i_sample++ )
3562 i_pos += p_track->p_sample_size[i_sample];
3569 static int MP4_TrackNextSample( demux_t *p_demux, mp4_track_t *p_track, uint32_t i_samples )
3571 if ( UINT32_MAX - p_track->i_sample < i_samples )
3573 p_track->i_sample = UINT32_MAX;
3574 return VLC_EGENERIC;
3577 p_track->i_sample += i_samples;
3579 if( p_track->i_sample >= p_track->i_sample_count )
3580 return VLC_EGENERIC;
3582 /* Have we changed chunk ? */
3583 if( p_track->i_sample >=
3584 p_track->chunk[p_track->i_chunk].i_sample_first +
3585 p_track->chunk[p_track->i_chunk].i_sample_count )
3587 if( TrackGotoChunkSample( p_demux, p_track, p_track->i_chunk + 1,
3588 p_track->i_sample ) )
3590 msg_Warn( p_demux, "track[0x%x] will be disabled "
3591 "(cannot restart decoder)", p_track->i_track_ID );
3592 MP4_TrackUnselect( p_demux, p_track );
3593 return VLC_EGENERIC;
3597 /* Have we changed elst */
3598 if( p_track->p_elst && p_track->BOXDATA(p_elst)->i_entry_count > 0 )
3600 demux_sys_t *p_sys = p_demux->p_sys;
3601 MP4_Box_data_elst_t *elst = p_track->BOXDATA(p_elst);
3602 uint64_t i_mvt = MP4_TrackGetDTS( p_demux, p_track ) *
3603 p_sys->i_timescale / CLOCK_FREQ;
3605 if( (unsigned int)p_track->i_elst < elst->i_entry_count &&
3606 i_mvt >= p_track->i_elst_time +
3607 elst->i_segment_duration[p_track->i_elst] )
3609 MP4_TrackSetELST( p_demux, p_track,
3610 MP4_TrackGetDTS( p_demux, p_track ) );
3617 static void MP4_TrackSetELST( demux_t *p_demux, mp4_track_t *tk,
3620 demux_sys_t *p_sys = p_demux->p_sys;
3621 int i_elst_last = tk->i_elst;
3623 /* handle elst (find the correct one) */
3625 tk->i_elst_time = 0;
3626 if( tk->p_elst && tk->BOXDATA(p_elst)->i_entry_count > 0 )
3628 MP4_Box_data_elst_t *elst = tk->BOXDATA(p_elst);
3629 int64_t i_mvt= i_time * p_sys->i_timescale / CLOCK_FREQ;
3631 for( tk->i_elst = 0; (unsigned int)tk->i_elst < elst->i_entry_count; tk->i_elst++ )
3633 mtime_t i_dur = elst->i_segment_duration[tk->i_elst];
3635 if( tk->i_elst_time <= i_mvt && i_mvt < tk->i_elst_time + i_dur )
3639 tk->i_elst_time += i_dur;
3642 if( (unsigned int)tk->i_elst >= elst->i_entry_count )
3644 /* msg_Dbg( p_demux, "invalid number of entry in elst" ); */
3645 tk->i_elst = elst->i_entry_count - 1;
3646 tk->i_elst_time -= elst->i_segment_duration[tk->i_elst];
3649 if( elst->i_media_time[tk->i_elst] < 0 )
3652 tk->i_elst_time += elst->i_segment_duration[tk->i_elst];
3655 if( i_elst_last != tk->i_elst )
3657 msg_Warn( p_demux, "elst old=%d new=%d", i_elst_last, tk->i_elst );
3662 static const char *MP4_ConvertMacCode( uint16_t i_code )
3664 static const struct { const char psz_iso639_1[3]; uint16_t i_code; } p_cvt[] = {
3665 { "en", 0 }, { "fr", 1 }, { "de", 2 }, { "it", 3 }, { "nl", 4 },
3666 { "sv", 5 }, { "es", 6 }, { "da", 7 }, { "pt", 8 }, { "no", 9 },
3667 { "he", 10 }, { "ja", 11 }, { "ar", 12 }, { "fi", 13 }, { "el", 14 },
3668 { "is", 15 }, { "mt", 16 }, { "tr", 17 }, { "hr", 18 }, { "zh", 19 },
3669 { "ur", 20 }, { "hi", 21 }, { "th", 22 }, { "ko", 23 }, { "lt", 24 },
3670 { "pl", 25 }, { "hu", 26 }, { "et", 27 }, { "lv", 28 }, //{ "??", 29 },
3671 { "fo", 30 }, { "fa", 31 }, { "ru", 32 }, { "zh", 33 }, { "nl", 34 },
3672 { "ga", 35 }, { "sq", 36 }, { "ro", 37 }, { "cs", 38 }, { "sk", 39 },
3673 { "sl", 40 }, { "yi", 41 }, { "sr", 42 }, { "mk", 43 }, { "bg", 44 },
3674 { "uk", 45 }, { "be", 46 }, { "uz", 47 }, { "az", 48 }, { "kk", 48 },
3675 { "az", 50 }, { "hy", 51 }, { "ka", 52 }, { "mo", 53 }, { "ky", 54 },
3676 { "tg", 55 }, { "tk", 56 }, { "mn", 57 }, { "mn", 58 }, { "ps", 59 },
3677 { "ku", 60 }, { "ks", 61 }, { "sd", 62 }, { "bo", 63 }, { "ne", 64 },
3678 { "sa", 65 }, { "mr", 66 }, { "bn", 67 }, { "as", 68 }, { "gu", 69 },
3679 { "pa", 70 }, { "or", 71 }, { "ml", 72 }, { "kn", 73 }, { "ta", 74 },
3680 { "te", 75 }, { "si", 76 }, { "my", 77 }, { "km", 78 }, { "lo", 79 },
3681 { "vi", 80 }, { "id", 81 }, { "tl", 82 }, { "ms", 83 }, { "ms", 84 },
3682 { "am", 85 }, { "ti", 86 }, { "om", 87 }, { "so", 88 }, { "sw", 89 },
3683 { "rw", 90 }, { "rn", 91 }, { "ny", 92 }, { "mg", 93 }, { "eo", 94 },
3685 { "cy", 128 }, { "eu", 129 },
3686 { "ca", 130 }, { "la", 131 }, { "qu", 132 }, { "gn", 133 }, { "ay", 134 },
3687 { "tt", 135 }, { "ug", 136 }, { "dz", 137 }, { "jv", 138 }, { "su", 139 },
3688 { "gl", 140 }, { "af", 141 }, { "br", 142 }, { "iu", 143 }, { "gd", 144 },
3689 { "gv", 145 }, { "ga", 146 }, { "to", 147 }, { "el", 148 },
3694 for( i = 0; *p_cvt[i].psz_iso639_1; i++ )
3696 if( p_cvt[i].i_code == i_code )
3697 return p_cvt[i].psz_iso639_1;
3702 /******************************************************************************
3703 * Here are the functions used for fragmented MP4
3704 *****************************************************************************/
3707 * It computes the sample rate for a video track using current video chunk
3709 static void ChunkGetESSampleRate( unsigned *pi_num, unsigned *pi_den,
3710 const mp4_track_t *p_track )
3712 if( p_track->cchunk->i_last_dts == 0 )
3719 const mp4_chunk_t *p_chunk = p_track->cchunk;
3721 uint32_t i_sample = p_chunk->i_sample_count;
3722 uint64_t i_first_dts = p_chunk->i_first_dts;
3723 uint64_t i_last_dts = p_chunk->i_last_dts;
3725 if( i_sample > 1 && i_first_dts < i_last_dts )
3726 vlc_ureduce( pi_num, pi_den,
3727 ( i_sample - 1) * p_track->i_timescale,
3728 i_last_dts - i_first_dts,
3733 * Build raw avcC box (without the 8 bytes header)
3734 * \return The size of the box.
3736 static int build_raw_avcC( uint8_t **p_extra, const uint8_t *CodecPrivateData,
3737 const unsigned cpd_len )
3740 unsigned sps_len = 0, pps_len = 0;
3741 const uint32_t mark = 0x00000001;
3743 assert( CodecPrivateData[0] == 0 );
3744 assert( CodecPrivateData[1] == 0 );
3745 assert( CodecPrivateData[2] == 0 );
3746 assert( CodecPrivateData[3] == 1 );
3748 uint32_t length = cpd_len + 3;
3749 avcC = calloc( length, 1 );
3750 if( unlikely( avcC == NULL ) )
3753 uint8_t *sps = avcC + 8;
3755 uint32_t candidate = ~mark;
3756 CodecPrivateData += 4;
3757 for( unsigned i = 0; i < cpd_len - 4; i++ )
3759 sps[i] = CodecPrivateData[i];
3760 candidate = (candidate << 8) | CodecPrivateData[i];
3761 if( candidate == mark )
3772 uint8_t *pps = sps + sps_len + 3;
3773 pps_len = cpd_len - sps_len - 4 * 2;
3774 memcpy( pps, CodecPrivateData + sps_len + 4, pps_len );
3777 uint8_t AVCProfileIndication = 0x64;
3778 uint8_t profile_compatibility = 0x40;
3779 uint8_t AVCLevelIndication = 0x1f;
3780 uint8_t lengthSizeMinusOne = 0x03;
3783 avcC[1] = AVCProfileIndication;
3784 avcC[2] = profile_compatibility;
3785 avcC[3] = AVCLevelIndication;
3786 avcC[4] = 0xfc + lengthSizeMinusOne;
3788 avcC[6] = (sps_len & 0xff00)>>8;
3789 avcC[7] = sps_len & 0xff;
3791 avcC[8+sps_len] = 1;
3792 avcC[9+sps_len] = (pps_len & 0xff00) >> 8;
3793 avcC[10+sps_len] = pps_len & 0xff;
3800 * Build a mp4_track_t from a StraBox
3803 static inline int MP4_SetCodecExtraData( es_format_t *fmt, MP4_Box_data_stra_t *p_data )
3805 fmt->i_extra = p_data->cpd_len;
3806 fmt->p_extra = malloc( p_data->cpd_len );
3807 if( unlikely( !fmt->p_extra ) )
3809 memcpy( fmt->p_extra, p_data->CodecPrivateData, p_data->cpd_len );
3813 static int MP4_frg_TrackCreate( demux_t *p_demux, mp4_track_t *p_track, MP4_Box_t *p_stra )
3815 demux_sys_t *p_sys = p_demux->p_sys;
3817 MP4_Box_data_stra_t *p_data = BOXDATA(p_stra);
3819 return VLC_EGENERIC;
3821 p_track->b_ok = true;
3822 p_track->b_selected = false;
3823 p_track->i_sample_count = UINT32_MAX;
3825 p_track->i_timescale = p_sys->i_timescale;
3826 p_track->i_width = p_data->MaxWidth;
3827 p_track->i_height = p_data->MaxHeight;
3828 p_track->i_track_ID = p_data->i_track_ID;
3830 es_format_t *fmt = &p_track->fmt;
3832 return VLC_EGENERIC;
3834 es_format_Init( fmt, p_data->i_es_cat, 0 );
3836 /* Set language FIXME */
3837 fmt->psz_language = strdup( "en" );
3839 fmt->i_original_fourcc = p_data->FourCC;
3840 fmt->i_codec = vlc_fourcc_GetCodec( fmt->i_cat, p_data->FourCC );
3842 uint8_t **p_extra = (uint8_t **)&fmt->p_extra;
3843 /* See http://msdn.microsoft.com/en-us/library/ff728116%28v=vs.90%29.aspx
3844 * for MS weird use of FourCC*/
3845 switch( fmt->i_cat )
3848 if( p_data->FourCC == VLC_FOURCC( 'A', 'V', 'C', '1' ) ||
3849 p_data->FourCC == VLC_FOURCC( 'A', 'V', 'C', 'B' ) ||
3850 p_data->FourCC == VLC_FOURCC( 'H', '2', '6', '4' ) )
3852 fmt->i_extra = build_raw_avcC( p_extra,
3853 p_data->CodecPrivateData, p_data->cpd_len );
3857 ret = MP4_SetCodecExtraData( fmt, p_data );
3858 if( ret != VLC_SUCCESS )
3862 fmt->video.i_width = p_data->MaxWidth;
3863 fmt->video.i_height = p_data->MaxHeight;
3864 fmt->video.i_bits_per_pixel = 0x18;
3865 fmt->video.i_visible_width = p_data->MaxWidth;
3866 fmt->video.i_visible_height = p_data->MaxHeight;
3869 ChunkGetESSampleRate( &fmt->video.i_frame_rate,
3870 &fmt->video.i_frame_rate_base, p_track );
3872 if( fmt->video.i_frame_rate_base != 0 )
3874 p_demux->p_sys->f_fps = (float)fmt->video.i_frame_rate /
3875 (float)fmt->video.i_frame_rate_base;
3878 p_demux->p_sys->f_fps = 24;
3883 fmt->audio.i_channels = p_data->Channels;
3884 fmt->audio.i_rate = p_data->SamplingRate;
3885 fmt->audio.i_bitspersample = p_data->BitsPerSample;
3886 fmt->audio.i_blockalign = p_data->nBlockAlign;
3888 fmt->i_bitrate = p_data->Bitrate;
3890 ret = MP4_SetCodecExtraData( fmt, p_data );
3891 if( ret != VLC_SUCCESS )
3904 * Return the track identified by tid
3906 static mp4_track_t *MP4_frg_GetTrackByID( demux_t *p_demux, const uint32_t tid )
3908 demux_sys_t *p_sys = p_demux->p_sys;
3910 mp4_track_t *ret = NULL;
3911 for( unsigned i = 0; i < p_sys->i_tracks; i++ )
3913 ret = &p_sys->track[i];
3914 if( ret->i_track_ID == tid )
3917 msg_Err( p_demux, "MP4_frg_GetTrack: track %"PRIu32" not found!", tid );
3921 static void FlushChunk( demux_t *p_demux, mp4_track_t *tk )
3923 msg_Dbg( p_demux, "Flushing chunk for track id %u", tk->i_track_ID );
3924 mp4_chunk_t *ck = tk->cchunk;
3925 while( ck->i_sample < ck->i_sample_count )
3930 if( ck->p_sample_size == NULL || ck->p_sample_data == NULL )
3933 uint32_t sample_size = ck->p_sample_size[ck->i_sample];
3934 assert( sample_size > 0 );
3935 p_block = block_Alloc( sample_size );
3936 if( unlikely( !p_block ) )
3939 uint8_t *src = ck->p_sample_data[ck->i_sample];
3940 memcpy( p_block->p_buffer, src, sample_size );
3944 p_block->i_dts = VLC_TS_0 + MP4_TrackGetDTS( p_demux, tk );
3946 i_delta = MP4_TrackGetPTSDelta( p_demux, tk );
3948 p_block->i_pts = p_block->i_dts + i_delta;
3949 else if( tk->fmt.i_cat != VIDEO_ES )
3950 p_block->i_pts = p_block->i_dts;
3952 p_block->i_pts = VLC_TS_INVALID;
3954 MP4_Block_Send( p_demux, tk, p_block );
3962 * \Note If we call that function too soon,
3963 * before the track has been selected by MP4_TrackSelect
3964 * (during the first execution of Demux), then the track gets disabled
3966 static int ReInitDecoder( demux_t *p_demux, mp4_track_t *p_track )
3968 demux_sys_t *p_sys = p_demux->p_sys;
3970 uint32_t i_sample = 0;
3971 bool b_smooth = false;
3972 MP4_Box_t *p_stra = NULL, *p_trak = NULL;
3974 if( !CmpUUID( &p_sys->p_root->p_first->i_uuid, &SmooBoxUUID ) )
3979 p_stra = MP4_BoxGet( p_sys->p_root, "uuid/uuid[0]" );
3980 if( !p_stra || CmpUUID( &p_stra->i_uuid, &StraBoxUUID ) )
3981 return VLC_EGENERIC;
3985 p_trak = MP4_BoxGet( p_sys->p_root, "/moov/trak[0]" );
3987 return VLC_EGENERIC;
3990 i_sample = p_track->i_sample;
3991 es_out_Del( p_demux->out, p_track->p_es );
3992 es_format_Clean( &p_track->fmt );
3995 MP4_frg_TrackCreate( p_demux, p_track, p_stra );
3997 MP4_TrackCreate( p_demux, p_track, p_trak, true );
3999 p_track->i_sample = i_sample;
4001 /* Temporary hack until we support track selection */
4002 p_track->b_selected = true;
4003 p_track->b_ok = true;
4004 p_track->b_enable = true;
4006 p_track->p_es = es_out_Add( p_demux->out, &p_track->fmt );
4007 p_track->b_codec_need_restart = false;
4013 * This function fills a mp4_chunk_t structure from a MP4_Box_t (p_chunk).
4014 * The 'i_tk_id' argument returns the ID of the track the chunk belongs to.
4015 * \note p_chunk usually contains a 'moof' and a 'mdat', and might contain a 'sidx'.
4016 * \return VLC_SUCCESS, VLC_EGENERIC or VLC_ENOMEM.
4018 static int MP4_frg_GetChunk( demux_t *p_demux, MP4_Box_t *p_chunk, unsigned *i_tk_id )
4020 MP4_Box_t *p_sidx = MP4_BoxGet( p_chunk, "sidx" );
4021 MP4_Box_t *p_moof = MP4_BoxGet( p_chunk, "moof" );
4024 msg_Warn( p_demux, "no moof box found!" );
4025 return VLC_EGENERIC;
4028 MP4_Box_t *p_traf = MP4_BoxGet( p_moof, "traf" );
4031 msg_Warn( p_demux, "no traf box found!" );
4032 return VLC_EGENERIC;
4035 MP4_Box_t *p_tfhd = MP4_BoxGet( p_traf, "tfhd" );
4038 msg_Warn( p_demux, "no tfhd box found!" );
4039 return VLC_EGENERIC;
4042 uint32_t i_track_ID = BOXDATA(p_tfhd)->i_track_ID;
4043 *i_tk_id = i_track_ID;
4044 assert( i_track_ID > 0 );
4045 msg_Dbg( p_demux, "GetChunk: track ID is %"PRIu32"", i_track_ID );
4047 mp4_track_t *p_track = MP4_frg_GetTrackByID( p_demux, i_track_ID );
4049 return VLC_EGENERIC;
4051 mp4_chunk_t *ret = p_track->cchunk;
4053 if( BOXDATA(p_tfhd)->b_empty )
4054 msg_Warn( p_demux, "No samples in this chunk!" );
4056 /* Usually we read 100 ms of each track. However, suppose we have two tracks,
4057 * Ta and Tv (audio and video). Suppose also that Ta is the first track to be
4058 * read, i.e. we read 100 ms of Ta, then 100 ms of Tv, then 100 ms of Ta,
4059 * and so on. Finally, suppose that we get the chunks the other way around,
4060 * i.e. first a chunk of Tv, then a chunk of Ta, then a chunk of Tv, and so on.
4061 * In that case, it is very likely that at some point, Ta->cchunk or Tv->cchunk
4062 * is not emptied when MP4_frg_GetChunks is called. It is therefore necessary to
4063 * flush it, i.e. send to the decoder the samples not yet sent.
4064 * Note that all the samples to be flushed should worth less than 100 ms,
4065 * (though I did not do the formal proof) and thus this flushing mechanism
4066 * should not cause A/V sync issues, or delays or whatever.
4068 if( ret->i_sample < ret->i_sample_count )
4069 FlushChunk( p_demux, p_track );
4071 if( ret->i_sample_count )
4072 FreeAndResetChunk( ret );
4074 uint32_t default_duration = 0;
4075 if( BOXDATA(p_tfhd)->i_flags & MP4_TFHD_DFLT_SAMPLE_DURATION )
4076 default_duration = BOXDATA(p_tfhd)->i_default_sample_duration;
4078 uint32_t default_size = 0;
4079 if( BOXDATA(p_tfhd)->i_flags & MP4_TFHD_DFLT_SAMPLE_SIZE )
4080 default_size = BOXDATA(p_tfhd)->i_default_sample_size;
4082 MP4_Box_t *p_trun = MP4_BoxGet( p_traf, "trun");
4085 msg_Warn( p_demux, "no trun box found!" );
4086 return VLC_EGENERIC;
4088 MP4_Box_data_trun_t *p_trun_data = p_trun->data.p_trun;
4090 ret->i_sample_count = p_trun_data->i_sample_count;
4091 assert( ret->i_sample_count > 0 );
4092 ret->i_sample_description_index = 1; /* seems to be always 1, is it? */
4093 ret->i_sample_first = p_track->i_sample_first;
4094 p_track->i_sample_first += ret->i_sample_count;
4096 ret->i_first_dts = p_track->i_first_dts;
4098 /* XXX I already saw DASH content with no default_duration and no
4099 * MP4_TRUN_SAMPLE_DURATION flag, but a sidx box was present.
4100 * This chunk of code might be buggy with segments having
4101 * more than one subsegment. */
4102 if( !default_duration )
4104 MP4_Box_t *p_trex = MP4_GetTrexByTrackID( p_moof, i_track_ID );
4106 default_duration = BOXDATA(p_trex)->i_default_sample_duration;
4109 MP4_Box_data_sidx_t *p_sidx_data = BOXDATA(p_sidx);
4110 assert( p_sidx_data->i_reference_count == 1 );
4112 if( p_sidx_data->i_timescale == 0 )
4113 return VLC_EGENERIC;
4115 unsigned i_chunk_duration = p_sidx_data->p_items[0].i_subsegment_duration /
4116 p_sidx_data->i_timescale;
4117 default_duration = i_chunk_duration * p_track->i_timescale / ret->i_sample_count;
4122 msg_Dbg( p_demux, "Default sample duration is %"PRIu32, default_duration );
4124 ret->p_sample_count_dts = calloc( ret->i_sample_count, sizeof( uint32_t ) );
4125 ret->p_sample_delta_dts = calloc( ret->i_sample_count, sizeof( uint32_t ) );
4127 if( !ret->p_sample_count_dts || !ret->p_sample_delta_dts )
4130 ret->p_sample_count_pts = calloc( ret->i_sample_count, sizeof( uint32_t ) );
4131 if( !ret->p_sample_count_pts )
4134 if( p_trun_data->i_flags & MP4_TRUN_SAMPLE_TIME_OFFSET )
4136 ret->p_sample_offset_pts = calloc( ret->i_sample_count, sizeof( int32_t ) );
4137 if( !ret->p_sample_offset_pts )
4141 ret->p_sample_size = calloc( ret->i_sample_count, sizeof( uint32_t ) );
4142 if( !ret->p_sample_size )
4145 ret->p_sample_data = calloc( ret->i_sample_count, sizeof( uint8_t * ) );
4146 if( !ret->p_sample_data )
4149 uint32_t dur = 0, i_mdatlen = 0, len;
4150 uint32_t chunk_duration = 0, chunk_size = 0;
4152 /* Skip header of mdat */
4154 int i_read = stream_Read( p_demux->s, &mdat, 8 );
4155 i_mdatlen = GetDWBE( mdat );
4156 if ( i_read < 8 || i_mdatlen < 8 ||
4157 VLC_FOURCC( mdat[4], mdat[5], mdat[6], mdat[7] ) != ATOM_mdat )
4158 return VLC_EGENERIC;
4160 for( uint32_t i = 0; i < ret->i_sample_count; i++)
4162 if( p_trun_data->i_flags & MP4_TRUN_SAMPLE_DURATION )
4163 dur = p_trun_data->p_samples[i].i_duration;
4165 dur = default_duration;
4166 ret->p_sample_delta_dts[i] = dur;
4167 chunk_duration += dur;
4169 ret->p_sample_count_dts[i] = ret->p_sample_count_pts[i] = 1;
4171 if( ret->p_sample_offset_pts )
4173 if ( p_trun_data->i_version == 0 )
4174 ret->p_sample_offset_pts[i] = (int32_t) p_trun_data->p_samples[i].i_composition_time_offset;
4176 ret->p_sample_offset_pts[i] = __MIN( INT32_MAX, p_trun_data->p_samples[i].i_composition_time_offset );
4179 if( p_trun_data->i_flags & MP4_TRUN_SAMPLE_SIZE )
4180 len = ret->p_sample_size[i] = p_trun_data->p_samples[i].i_size;
4182 len = ret->p_sample_size[i] = default_size;
4184 if ( chunk_size + len > ( i_mdatlen - 8 ) )
4185 return VLC_EGENERIC;
4187 ret->p_sample_data[i] = malloc( len );
4188 if( ret->p_sample_data[i] == NULL )
4190 uint32_t i_read = stream_ReadU32( p_demux->s, ret->p_sample_data[i], len );
4192 return VLC_EGENERIC;
4195 ret->i_last_dts = ret->i_first_dts + chunk_duration - dur;
4196 p_track->i_first_dts = chunk_duration + ret->i_first_dts;
4198 if( p_track->b_codec_need_restart &&
4199 p_track->fmt.i_cat == VIDEO_ES )
4200 ReInitDecoder( p_demux, p_track );
4202 /* Skip if we didn't reach the end of mdat box */
4203 if ( chunk_size < (i_mdatlen - 8) )
4204 stream_ReadU32( p_demux->s, NULL, i_mdatlen - chunk_size - 8 );
4206 p_track->b_has_non_empty_cchunk = true;
4212 * Get the next chunk of the track identified by i_tk_id.
4213 * \Note We don't want to seek all the time, so if the first chunk given by the
4214 * input method doesn't belong to the right track, we don't throw it away,
4215 * and so, in general, this function fetch more than one chunk.
4216 * Not to mention that a new init fragment might be put everywhere
4217 * between two chunks by the input method.
4219 static int MP4_frg_GetChunks( demux_t *p_demux, const unsigned i_tk_id )
4221 demux_sys_t *p_sys = p_demux->p_sys;
4222 mp4_track_t *p_track;
4224 for( unsigned i = 0; i < p_sys->i_tracks; i++ )
4226 MP4_Box_t *p_chunk = MP4_BoxGetNextChunk( p_demux->s );
4228 return VLC_EGENERIC;
4230 if( !p_chunk->p_first )
4231 goto MP4_frg_GetChunks_Error;
4232 uint32_t i_type = p_chunk->p_first->i_type;
4234 if( i_type == ATOM_uuid || i_type == ATOM_ftyp )
4236 MP4_BoxFree( p_demux->s, p_sys->p_root );
4237 p_sys->p_root = p_chunk;
4239 if( i_type == ATOM_ftyp ) /* DASH */
4241 MP4_Box_t *p_tkhd = MP4_BoxGet( p_chunk, "/moov/trak[0]/tkhd" );
4244 msg_Warn( p_demux, "No tkhd found!" );
4245 goto MP4_frg_GetChunks_Error;
4247 tid = p_tkhd->data.p_tkhd->i_track_ID;
4249 else /* Smooth Streaming */
4251 assert( !CmpUUID( &p_chunk->p_first->i_uuid, &SmooBoxUUID ) );
4252 MP4_Box_t *p_stra = MP4_BoxGet( p_chunk, "/uuid/uuid[0]" );
4253 if( !p_stra || CmpUUID( &p_stra->i_uuid, &StraBoxUUID ) )
4255 msg_Warn( p_demux, "No StraBox found!" );
4256 goto MP4_frg_GetChunks_Error;
4258 tid = p_stra->data.p_stra->i_track_ID;
4261 p_track = MP4_frg_GetTrackByID( p_demux, tid );
4263 goto MP4_frg_GetChunks_Error;
4264 p_track->b_codec_need_restart = true;
4266 return MP4_frg_GetChunks( p_demux, i_tk_id );
4269 if( MP4_frg_GetChunk( p_demux, p_chunk, &tid ) != VLC_SUCCESS )
4270 goto MP4_frg_GetChunks_Error;
4272 MP4_BoxFree( p_demux->s, p_chunk );
4274 if( tid == i_tk_id )
4279 MP4_frg_GetChunks_Error:
4280 MP4_BoxFree( p_demux->s, p_chunk );
4281 return VLC_EGENERIC;
4287 static int MP4_frg_TrackSelect( demux_t *p_demux, mp4_track_t *p_track )
4289 if( !p_track->b_ok || p_track->b_chapter )
4291 return VLC_EGENERIC;
4294 if( p_track->b_selected )
4296 msg_Warn( p_demux, "track[Id 0x%x] already selected", p_track->i_track_ID );
4300 msg_Dbg( p_demux, "Select track id %u", p_track->i_track_ID );
4301 p_track->b_selected = true;
4306 * DemuxFrg: read packet and send them to decoders
4307 * \return 1 on success, 0 on error.
4308 * TODO check for newly selected track
4310 int DemuxFrg( demux_t *p_demux )
4312 demux_sys_t *p_sys = p_demux->p_sys;
4314 unsigned i_track_selected;
4316 /* check for newly selected/unselected track */
4317 for( i_track = 0, i_track_selected = 0; i_track < p_sys->i_tracks; i_track++ )
4319 mp4_track_t *tk = &p_sys->track[i_track];
4322 if( !tk->b_ok || tk->b_chapter )
4325 es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
4326 msg_Dbg( p_demux, "track %u %s!", tk->i_track_ID, b ? "enabled" : "disabled" );
4328 if( tk->b_selected && !b )
4330 MP4_TrackUnselect( p_demux, tk );
4332 else if( !tk->b_selected && b)
4334 MP4_frg_TrackSelect( p_demux, tk );
4337 if( tk->b_selected )
4341 if( i_track_selected <= 0 )
4343 p_sys->i_time += __MAX( p_sys->i_timescale / 10 , 1 );
4344 if( p_sys->i_timescale > 0 )
4346 int64_t i_length = CLOCK_FREQ *
4347 (mtime_t)p_sys->moovfragment.i_duration /
4348 (mtime_t)p_sys->i_timescale;
4349 if( MP4_GetMoviePTS( p_sys ) >= i_length )
4354 msg_Warn( p_demux, "no track selected, exiting..." );
4358 /* first wait for the good time to read a packet */
4359 es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + p_sys->i_pcr );
4361 p_sys->i_pcr = MP4_GetMoviePTS( p_sys );
4363 /* we will read 100ms for each stream so ...*/
4364 p_sys->i_time += __MAX( p_sys->i_timescale / 10, 1 );
4366 for( i_track = 0; i_track < p_sys->i_tracks; i_track++ )
4368 mp4_track_t *tk = &p_sys->track[i_track];
4370 if( !tk->b_ok || tk->b_chapter || !tk->b_selected )
4372 msg_Warn( p_demux, "Skipping track id %u", tk->i_track_ID );
4376 if( !tk->b_has_non_empty_cchunk )
4378 if( MP4_frg_GetChunks( p_demux, tk->i_track_ID ) != VLC_SUCCESS )
4380 msg_Info( p_demux, "MP4_frg_GetChunks returned error. End of stream?" );
4385 while( MP4_TrackGetDTS( p_demux, tk ) < MP4_GetMoviePTS( p_sys ) )
4390 mp4_chunk_t *ck = tk->cchunk;
4391 if( ck->i_sample >= ck->i_sample_count )
4393 msg_Err( p_demux, "sample %"PRIu32" of %"PRIu32"",
4394 ck->i_sample, ck->i_sample_count );
4398 uint32_t sample_size = ck->p_sample_size[ck->i_sample];
4399 p_block = block_Alloc( sample_size );
4400 uint8_t *src = ck->p_sample_data[ck->i_sample];
4401 memcpy( p_block->p_buffer, src, sample_size );
4404 if( ck->i_sample == ck->i_sample_count )
4405 tk->b_has_non_empty_cchunk = false;
4408 p_block->i_dts = VLC_TS_0 + MP4_TrackGetDTS( p_demux, tk );
4410 i_delta = MP4_TrackGetPTSDelta( p_demux, tk );
4412 p_block->i_pts = p_block->i_dts + i_delta;
4413 else if( tk->fmt.i_cat != VIDEO_ES )
4414 p_block->i_pts = p_block->i_dts;
4416 p_block->i_pts = VLC_TS_INVALID;
4418 MP4_Block_Send( p_demux, tk, p_block );
4422 if( !tk->b_has_non_empty_cchunk )
4429 static MP4_Box_t * LoadNextChunk( demux_t *p_demux )
4431 /* Read Next Chunk */
4432 MP4_Box_t *p_chunk = MP4_BoxGetNextChunk( p_demux->s );
4435 msg_Warn( p_demux, "no next chunk" );
4439 if( !p_chunk->p_first )
4441 msg_Warn( p_demux, "no next chunk child" );
4448 static bool BoxExistsInRootTree( MP4_Box_t *p_root, uint32_t i_type, off_t i_pos )
4452 if ( p_root->i_pos == i_pos )
4454 assert( i_type == p_root->i_type );
4457 p_root = p_root->p_next;
4459 return (p_root != NULL);
4462 /* Keeps an ordered chain of all fragments */
4463 static bool AddFragment( demux_t *p_demux, MP4_Box_t *p_moox )
4465 demux_sys_t *p_sys = p_demux->p_sys;
4466 mp4_fragment_t *p_base_fragment = & p_sys->moovfragment;
4470 if( p_moox->i_type == ATOM_moov )
4472 if ( !p_sys->moovfragment.p_moox )
4474 p_sys->moovfragment.p_moox = p_moox;
4476 if( (p_mvhd = MP4_BoxGet( p_moox, "mvhd" )) )
4478 p_sys->i_timescale = BOXDATA(p_mvhd)->i_timescale;
4479 p_sys->i_overall_duration = BOXDATA(p_mvhd)->i_duration;
4482 if ( MP4_BoxCount( p_moox, "mvex" ) || !p_mvhd )
4483 { /* duration might be wrong an be set to whole duration :/ */
4484 p_sys->moovfragment.i_duration = 0;
4486 MP4_Box_t *p_trak = MP4_BoxGet( p_moox, "trak" );
4489 if ( p_trak->i_type == ATOM_trak && (p_tkhd = MP4_BoxGet( p_trak, "tkhd" )) )
4491 if ( BOXDATA(p_tkhd)->i_duration > p_sys->moovfragment.i_duration )
4492 p_sys->moovfragment.i_duration = BOXDATA(p_tkhd)->i_duration;
4494 p_trak = p_trak->p_next;
4498 msg_Dbg( p_demux, "added fragment %4.4s", (char*) &p_moox->i_type );
4503 else // p_moox->i_type == ATOM_moof
4505 assert(p_moox->i_type == ATOM_moof);
4506 mp4_fragment_t *p_fragment = p_sys->moovfragment.p_next;
4507 while ( p_fragment )
4509 if ( !p_base_fragment->p_moox || p_moox->i_pos > p_base_fragment->p_moox->i_pos )
4511 p_base_fragment = p_fragment;
4512 p_fragment = p_fragment->p_next;
4514 else if ( p_moox->i_pos == p_base_fragment->p_moox->i_pos )
4516 /* already exists */
4522 /* Add the moof fragment */
4523 mp4_fragment_t *p_new = malloc(sizeof(mp4_fragment_t));
4524 if ( !p_new ) return false;
4525 p_new->p_moox = p_moox;
4526 p_new->i_duration = 0;
4527 p_new->p_next = p_base_fragment->p_next;
4528 p_base_fragment->p_next = p_new;
4529 msg_Dbg( p_demux, "added fragment %4.4s", (char*) &p_moox->i_type );
4531 /* we have to probe all fragments :/ */
4532 uint64_t i_traf_base_data_offset = 0;
4533 uint64_t i_traf_min_offset = 0;
4534 uint32_t i_traf = 0;
4535 uint32_t i_traf_total_size = 0;
4536 uint32_t i_trafs_total_size = 0;
4538 MP4_Box_t *p_traf = MP4_BoxGet( p_new->p_moox, "traf" );
4541 if ( p_traf->i_type != ATOM_traf )
4543 p_traf = p_traf->p_next;
4546 const MP4_Box_t *p_tfhd = MP4_BoxGet( p_traf, "tfhd" );
4547 const MP4_Box_t *p_trun = MP4_BoxGet( p_traf, "trun" );
4548 if ( !p_tfhd || !p_trun )
4550 p_traf = p_traf->p_next;
4554 uint32_t i_track_timescale = 0;
4555 uint32_t i_track_defaultsamplesize = 0;
4556 uint32_t i_track_defaultsampleduration = 0;
4557 if ( p_sys->b_smooth )
4559 /* stra sets identical timescales */
4560 i_track_timescale = p_sys->i_timescale;
4561 i_track_defaultsamplesize = 1;
4562 i_track_defaultsampleduration = 1;
4566 /* set trex for defaults */
4567 MP4_Box_t *p_trex = MP4_GetTrexByTrackID( p_sys->moovfragment.p_moox, BOXDATA(p_tfhd)->i_track_ID );
4570 i_track_defaultsamplesize = BOXDATA(p_trex)->i_default_sample_size;
4571 i_track_defaultsampleduration = BOXDATA(p_trex)->i_default_sample_duration;
4574 MP4_Box_t *p_trak = MP4_GetTrakByTrackID( p_sys->moovfragment.p_moox, BOXDATA(p_tfhd)->i_track_ID );
4577 MP4_Box_t *p_mdhd = MP4_BoxGet( p_trak, "mdia/mdhd" );
4578 if ( p_mdhd ) i_track_timescale = BOXDATA(p_mdhd)->i_timescale;
4582 if ( !i_track_timescale )
4584 p_traf = p_traf->p_next;
4588 if ( BOXDATA(p_tfhd)->i_flags & MP4_TFHD_BASE_DATA_OFFSET )
4590 i_traf_base_data_offset = BOXDATA(p_tfhd)->i_base_data_offset;
4592 else if ( BOXDATA(p_tfhd)->i_flags & MP4_TFHD_DEFAULT_BASE_IS_MOOF )
4594 i_traf_base_data_offset = p_new->p_moox->i_pos /* + 8*/;
4599 i_traf_base_data_offset = p_new->p_moox->i_pos /*+ 8*/;
4601 i_traf_base_data_offset += i_traf_total_size;
4604 i_traf_total_size = 0;
4606 uint64_t i_trun_data_offset = i_traf_base_data_offset;
4607 uint64_t i_traf_duration = 0;
4608 uint32_t i_trun_size = 0;
4609 while ( p_trun && p_tfhd )
4611 if ( p_trun->i_type != ATOM_trun )
4613 p_trun = p_trun->p_next;
4616 const MP4_Box_data_trun_t *p_trundata = p_trun->data.p_trun;
4618 /* Get data offset */
4619 if ( p_trundata->i_flags & MP4_TRUN_DATA_OFFSET )
4620 i_trun_data_offset += __MAX( p_trundata->i_data_offset, 0 );
4622 i_trun_data_offset += i_trun_size;
4626 /* Sum total time */
4627 if ( p_trundata->i_flags & MP4_TRUN_SAMPLE_DURATION )
4629 for( uint32_t i=0; i< p_trundata->i_sample_count; i++ )
4630 i_traf_duration += p_trundata->p_samples[i].i_duration;
4632 else if ( BOXDATA(p_tfhd)->i_flags & MP4_TFHD_DFLT_SAMPLE_DURATION )
4634 i_traf_duration += p_trundata->i_sample_count *
4635 BOXDATA(p_tfhd)->i_default_sample_duration;
4639 i_traf_duration += p_trundata->i_sample_count *
4640 i_track_defaultsampleduration;
4643 /* Get total traf size */
4644 if ( p_trundata->i_flags & MP4_TRUN_SAMPLE_SIZE )
4646 for( uint32_t i=0; i< p_trundata->i_sample_count; i++ )
4647 i_trun_size += p_trundata->p_samples[i].i_size;
4649 else if ( BOXDATA(p_tfhd)->i_flags & MP4_TFHD_DFLT_SAMPLE_SIZE )
4651 i_trun_size += p_trundata->i_sample_count *
4652 BOXDATA(p_tfhd)->i_default_sample_size;
4656 i_trun_size += p_trundata->i_sample_count *
4657 i_track_defaultsamplesize;
4660 i_traf_total_size += i_trun_size;
4662 if ( i_traf_min_offset )
4663 i_traf_min_offset = __MIN( i_trun_data_offset, i_traf_min_offset );
4665 i_traf_min_offset = i_trun_data_offset;
4667 p_trun = p_trun->p_next;
4670 i_trafs_total_size += i_traf_total_size;
4671 p_new->i_duration = __MAX( p_new->i_duration, i_traf_duration * p_sys->i_timescale / i_track_timescale );
4673 p_traf = p_traf->p_next;
4677 p_new->i_chunk_range_min_offset = i_traf_min_offset;
4678 p_new->i_chunk_range_max_offset = i_traf_min_offset + i_trafs_total_size;
4680 msg_Dbg( p_demux, "new fragment is %"PRId64" %"PRId64, p_new->i_chunk_range_min_offset, p_new->i_chunk_range_max_offset );
4682 /* compute total duration with that new fragment if no overall provided */
4683 MP4_Box_t *p_mehd = MP4_BoxGet( p_sys->moovfragment.p_moox, "mvex/mehd");
4686 p_sys->i_overall_duration = 0;
4687 if ( p_sys->b_fragments_probed )
4689 p_new = &p_sys->moovfragment;
4692 p_sys->i_overall_duration += p_new->i_duration;
4693 p_new = p_new->p_next;
4698 p_sys->i_overall_duration = BOXDATA(p_mehd)->i_fragment_duration;
4700 msg_Dbg( p_demux, "total fragments duration %"PRId64, CLOCK_FREQ * p_sys->i_overall_duration / p_sys->i_timescale);
4704 static int ProbeIndex( demux_t *p_demux )
4706 demux_sys_t *p_sys = p_demux->p_sys;
4707 uint64_t i_backup_pos, i_stream_size;
4708 uint8_t mfro[MP4_MFRO_BOXSIZE];
4709 assert( p_sys->b_seekable );
4711 if ( MP4_BoxCount( p_sys->p_root, "/mfra" ) )
4714 i_stream_size = stream_Size( p_demux->s );
4715 if ( ( i_stream_size >> 62 ) ||
4716 ( i_stream_size < MP4_MFRO_BOXSIZE ) ||
4717 ( !MP4_stream_Tell( p_demux->s, &i_backup_pos ) ) ||
4718 ( stream_Seek( p_demux->s, i_stream_size - MP4_MFRO_BOXSIZE ) != VLC_SUCCESS )
4721 msg_Dbg( p_demux, "Probing tail for mfro has failed" );
4722 return VLC_EGENERIC;
4725 if ( stream_Read( p_demux->s, &mfro, MP4_MFRO_BOXSIZE ) == MP4_MFRO_BOXSIZE &&
4726 VLC_FOURCC(mfro[4],mfro[5],mfro[6],mfro[7]) == ATOM_mfro &&
4727 GetDWBE( &mfro ) == MP4_MFRO_BOXSIZE )
4729 uint32_t i_offset = GetDWBE( &mfro[12] );
4730 msg_Dbg( p_demux, "will read mfra index at %"PRIu64, i_stream_size - i_offset );
4731 if ( i_stream_size > i_offset &&
4732 stream_Seek( p_demux->s, i_stream_size - i_offset ) == VLC_SUCCESS )
4734 msg_Dbg( p_demux, "reading mfra index at %"PRIu64, i_stream_size - i_offset );
4735 MP4_ReadBoxContainerChildren( p_demux->s, p_sys->p_root, ATOM_mfra );
4739 return stream_Seek( p_demux->s, i_backup_pos );
4742 static int ProbeFragments( demux_t *p_demux, bool b_force )
4744 demux_sys_t *p_sys = p_demux->p_sys;
4745 uint64_t i_current_pos;
4747 if ( MP4_stream_Tell( p_demux->s, &i_current_pos ) )
4748 msg_Dbg( p_demux, "probing fragments from %"PRId64, i_current_pos );
4750 assert( p_sys->p_root );
4752 if ( p_sys->b_fastseekable || b_force )
4754 MP4_ReadBoxContainerChildren( p_demux->s, p_sys->p_root, 0 ); /* Get the rest of the file */
4755 p_sys->b_fragments_probed = true;
4759 /* We stop at first moof, which validates our fragmentation condition
4760 * and we'll find others while reading. */
4761 MP4_ReadBoxContainerChildren( p_demux->s, p_sys->p_root, ATOM_moof );
4764 if ( !p_sys->moovfragment.p_moox )
4766 MP4_Box_t *p_moov = MP4_BoxGet( p_sys->p_root, "/moov" );
4769 /* moov/mvex before probing should be present anyway */
4770 MP4_BoxDumpStructure( p_demux->s, p_sys->p_root );
4771 return VLC_EGENERIC;
4773 AddFragment( p_demux, p_moov );
4776 MP4_Box_t *p_moof = MP4_BoxGet( p_sys->p_root, "moof" );
4779 if ( p_moof->i_type == ATOM_moof )
4780 AddFragment( p_demux, p_moof );
4781 p_moof = p_moof->p_next;
4784 MP4_Box_t *p_mdat = MP4_BoxGet( p_sys->p_root, "mdat" );
4787 stream_Seek( p_demux->s, p_mdat->i_pos );
4788 msg_Dbg( p_demux, "rewinding to mdat %"PRId64, p_mdat->i_pos );
4794 static mp4_fragment_t * GetFragmentByPos( demux_t *p_demux, uint64_t i_pos, bool b_exact )
4796 mp4_fragment_t *p_fragment = &p_demux->p_sys->moovfragment;
4797 while ( p_fragment )
4799 if ( i_pos <= p_fragment->i_chunk_range_max_offset &&
4800 ( !b_exact || i_pos >= p_fragment->i_chunk_range_min_offset ) )
4802 msg_Dbg( p_demux, "fragment matched %"PRIu64" << %"PRIu64" << %"PRIu64,
4803 p_fragment->i_chunk_range_min_offset, i_pos,
4804 p_fragment->i_chunk_range_max_offset );
4809 p_fragment = p_fragment->p_next;
4815 /* Get a matching fragment data start by clock time */
4816 static mp4_fragment_t * GetFragmentByTime( demux_t *p_demux, const mtime_t i_time )
4818 mp4_fragment_t *p_fragment = &p_demux->p_sys->moovfragment;
4819 mtime_t i_base_time = 0;
4820 while ( p_fragment )
4822 mtime_t i_length = CLOCK_FREQ * p_fragment->i_duration / p_demux->p_sys->i_timescale;
4823 if ( i_time >= i_base_time &&
4824 i_time <= i_base_time + i_length )
4830 i_base_time += i_length;
4831 p_fragment = p_fragment->p_next;
4834 if ( !p_demux->p_sys->b_fragments_probed )
4835 return NULL; /* We have no way to guess missing fragments time */
4840 /* Returns fragment scaled time offset */
4841 static mtime_t LeafGetFragmentTimeOffset( demux_t *p_demux, mp4_fragment_t *p_fragment )
4843 mtime_t i_base_scaledtime = 0;
4844 mp4_fragment_t *p_current = &p_demux->p_sys->moovfragment;
4845 while ( p_current != p_fragment )
4847 i_base_scaledtime += p_current->i_duration;
4848 p_current = p_current->p_next;
4850 return i_base_scaledtime;
4853 static int LeafParseTRUN( demux_t *p_demux, mp4_track_t *p_track,
4854 const uint32_t i_defaultduration, const uint32_t i_defaultsize,
4855 const MP4_Box_data_trun_t *p_trun, uint32_t * const pi_mdatlen )
4857 assert( p_trun->i_sample_count );
4858 msg_Dbg( p_demux, "Default sample duration %"PRIu32" size %"PRIu32" firstdts %"PRIu64,
4859 i_defaultduration, i_defaultsize, p_track->i_first_dts );
4861 uint32_t dur = 0, len;
4862 uint32_t chunk_size = 0;
4863 mtime_t i_nzdts = CLOCK_FREQ * p_track->i_time / p_track->i_timescale;
4867 for( uint32_t i = 0; i < p_trun->i_sample_count; i++)
4869 i_nzdts += CLOCK_FREQ * dur / p_track->i_timescale;
4872 if( p_trun->i_flags & MP4_TRUN_SAMPLE_DURATION )
4873 dur = p_trun->p_samples[i].i_duration;
4875 dur = i_defaultduration;
4877 p_track->i_time += dur;
4879 if( p_trun->i_flags & MP4_TRUN_SAMPLE_TIME_OFFSET )
4881 if ( p_trun->i_version == 0 )
4882 i_nzpts += CLOCK_FREQ * (int32_t) p_trun->p_samples[i].i_composition_time_offset / p_track->i_timescale;
4884 i_nzpts += CLOCK_FREQ * p_trun->p_samples[i].i_composition_time_offset / p_track->i_timescale;
4887 if( p_trun->i_flags & MP4_TRUN_SAMPLE_SIZE )
4888 len = p_trun->p_samples[i].i_size;
4890 len = i_defaultsize;
4892 assert( dur ); /* dur, dur ! */
4895 if ( chunk_size + len > *pi_mdatlen )
4897 /* update data left in mdat */
4898 *pi_mdatlen -= chunk_size;
4899 return VLC_EGENERIC;
4902 block_t *p_block = stream_Block( p_demux->s, __MIN( len, INT32_MAX ) );
4903 uint32_t i_read = ( p_block ) ? p_block->i_buffer : 0;
4906 /* update data left in mdat */
4907 *pi_mdatlen -= chunk_size;
4908 *pi_mdatlen -= i_read;
4910 return VLC_EGENERIC;
4913 if ( p_demux->p_sys->i_pcr < VLC_TS_0 )
4915 p_demux->p_sys->i_pcr = i_nzdts;
4916 es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + i_nzdts );
4919 if ( p_track->p_es )
4921 p_block->i_dts = VLC_TS_0 + i_nzdts;
4922 p_block->i_pts = VLC_TS_0 + i_nzpts;
4923 p_block->i_length = CLOCK_FREQ * dur / p_track->i_timescale;
4924 MP4_Block_Send( p_demux, p_track, p_block );
4926 else free( p_block );
4931 /* update data left in mdat */
4932 *pi_mdatlen -= chunk_size;
4936 static int LeafGetTrackAndChunkByMOOVPos( demux_t *p_demux, uint64_t *pi_pos,
4937 mp4_track_t **pp_tk, unsigned int *pi_chunk )
4939 const demux_sys_t *p_sys = p_demux->p_sys;
4941 mp4_track_t *p_tk_closest = NULL;
4942 uint64_t i_closest = UINT64_MAX;
4943 unsigned int i_chunk_closest;
4947 for ( unsigned int i_track = 0; i_track < p_sys->i_tracks; i_track++ )
4949 for( unsigned int i_chunk = 0; i_chunk < p_sys->track[i_track].i_chunk_count; i_chunk++ )
4951 if ( p_sys->track[i_track].chunk[i_chunk].i_offset > *pi_pos )
4953 i_closest = __MIN( i_closest, p_sys->track[i_track].chunk[i_chunk].i_offset );
4954 p_tk_closest = &p_sys->track[i_track];
4955 i_chunk_closest = i_chunk;
4958 if ( *pi_pos == p_sys->track[i_track].chunk[i_chunk].i_offset )
4960 *pp_tk = &p_sys->track[i_track];
4961 *pi_chunk = i_chunk;
4967 if ( i_closest != UINT64_MAX )
4969 *pi_pos = i_closest;
4970 *pp_tk = p_tk_closest;
4971 *pi_chunk = i_chunk_closest;
4974 else return VLC_EGENERIC;
4977 static int LeafMOOVGetSamplesSize( const mp4_track_t *p_track, const uint32_t i_sample,
4978 uint32_t *pi_samplestoread, uint32_t *pi_samplessize,
4979 const uint32_t i_maxbytes, const uint32_t i_maxsamples )
4981 MP4_Box_t *p_stsz = MP4_BoxGet( p_track->p_stbl, "stsz" );
4983 return VLC_EGENERIC;
4985 if ( BOXDATA(p_stsz)->i_sample_size == 0 )
4987 uint32_t i_entry = i_sample;
4988 uint32_t i_totalbytes = 0;
4989 *pi_samplestoread = 1;
4991 if ( i_sample >= BOXDATA(p_stsz)->i_sample_count )
4992 return VLC_EGENERIC;
4994 *pi_samplessize = BOXDATA(p_stsz)->i_entry_size[i_sample];
4995 i_totalbytes += *pi_samplessize;
4997 if ( *pi_samplessize > i_maxbytes )
4998 return VLC_EGENERIC;
5001 while( i_entry < BOXDATA(p_stsz)->i_sample_count &&
5002 *pi_samplessize == BOXDATA(p_stsz)->i_entry_size[i_entry] &&
5003 i_totalbytes + *pi_samplessize < i_maxbytes &&
5004 *pi_samplestoread < i_maxsamples
5007 i_totalbytes += *pi_samplessize;
5008 (*pi_samplestoread)++;
5011 *pi_samplessize = i_totalbytes;
5015 /* all samples have same size */
5016 *pi_samplessize = BOXDATA(p_stsz)->i_sample_size;
5017 *pi_samplestoread = __MIN( i_maxsamples, BOXDATA(p_stsz)->i_sample_count );
5018 *pi_samplestoread = __MIN( i_maxbytes / *pi_samplessize, *pi_samplestoread );
5019 *pi_samplessize = *pi_samplessize * *pi_samplestoread;
5025 static inline mtime_t LeafGetMOOVTimeInChunk( const mp4_chunk_t *p_chunk, uint32_t i_sample )
5028 uint32_t i_index = 0;
5030 while( i_sample > 0 )
5032 if( i_sample > p_chunk->p_sample_count_dts[i_index] )
5034 i_time += p_chunk->p_sample_count_dts[i_index] *
5035 p_chunk->p_sample_delta_dts[i_index];
5036 i_sample -= p_chunk->p_sample_count_dts[i_index];
5041 i_time += i_sample * p_chunk->p_sample_delta_dts[i_index];
5049 static int LeafParseMDATwithMOOV( demux_t *p_demux )
5051 demux_sys_t *p_sys = p_demux->p_sys;
5053 assert( p_sys->context.i_current_box_type == ATOM_mdat );
5054 assert( p_sys->context.p_fragment->p_moox->i_type == ATOM_moov );
5056 uint64_t i_current_pos;
5057 if ( !MP4_stream_Tell( p_demux->s, &i_current_pos ) )
5058 return VLC_EGENERIC;
5060 if ( p_sys->context.i_mdatbytesleft == 0 ) /* Start parsing new mdat */
5062 /* Ready mdat section */
5064 int i_read = stream_Read( p_demux->s, &mdat, 8 );
5065 p_sys->context.i_mdatbytesleft = GetDWBE( mdat );
5066 if ( i_read < 8 || p_sys->context.i_mdatbytesleft < 8 ||
5067 VLC_FOURCC( mdat[4], mdat[5], mdat[6], mdat[7] ) != ATOM_mdat )
5070 if ( !MP4_stream_Tell( p_demux->s, &i_pos ) )
5071 msg_Err( p_demux, "No mdat atom at %"PRIu64, i_pos - __MAX( 0, i_read ) );
5072 return VLC_EGENERIC;
5075 p_sys->context.i_mdatbytesleft -= 8;
5078 while( p_sys->context.i_mdatbytesleft > 0 )
5080 mp4_track_t *p_track;
5081 unsigned int i_chunk;
5084 uint64_t i_pos = i_current_pos;
5085 int i_ret = LeafGetTrackAndChunkByMOOVPos( p_demux, &i_pos, &p_track, &i_chunk );
5086 if ( i_ret == VLC_EGENERIC )
5088 msg_Err(p_demux, "can't find referenced chunk for start at %"PRIu64, i_current_pos );
5091 else if( i_ret == VLC_ENOOBJ )
5093 assert( i_pos - i_current_pos > p_sys->context.i_mdatbytesleft );
5094 int i_read = stream_Read( p_demux->s, NULL, i_pos - i_current_pos );
5095 i_current_pos += i_read;
5096 p_sys->context.i_mdatbytesleft -= i_read;
5097 if ( i_read == 0 ) goto error;
5102 mp4_chunk_t *p_chunk = &p_track->chunk[i_chunk];
5104 uint32_t i_nb_samples_at_chunk_start = p_chunk->i_sample_first;
5105 uint32_t i_nb_samples_in_chunk = p_chunk->i_sample_count;
5107 assert(i_nb_samples_in_chunk);
5109 uint32_t i_nb_samples = 0;
5110 while ( i_nb_samples < i_nb_samples_in_chunk )
5112 uint32_t i_samplessize = 0;
5113 uint32_t i_samplescounttoread = 0;
5114 i_ret = LeafMOOVGetSamplesSize( p_track,
5115 i_nb_samples_at_chunk_start + i_nb_samples,
5116 &i_samplescounttoread, &i_samplessize,
5117 p_sys->context.i_mdatbytesleft,
5118 /*i_nb_samples_in_chunk - i_nb_samples*/ 1 );
5119 if ( i_ret != VLC_SUCCESS )
5122 if( p_sys->context.i_mdatbytesleft &&
5123 p_sys->context.i_mdatbytesleft >= i_samplessize )
5129 if( !(p_block = stream_Block( p_demux->s, i_samplessize )) )
5132 if ( MP4_stream_Tell( p_demux->s, &i_pos ) )
5134 p_sys->context.i_mdatbytesleft -= ( i_pos - i_current_pos );
5135 msg_Err( p_demux, "stream block error %"PRId64" %"PRId64, i_pos, i_pos - i_current_pos );
5139 else if( p_track->fmt.i_cat == SPU_ES )
5141 if ( p_track->fmt.i_codec != VLC_CODEC_TX3G &&
5142 p_track->fmt.i_codec != VLC_CODEC_SPU )
5143 p_block->i_buffer = 0;
5146 i_nb_samples += i_samplescounttoread;
5147 i_current_pos += i_samplessize;
5148 p_sys->context.i_mdatbytesleft -= i_samplessize;
5151 mtime_t i_time = LeafGetMOOVTimeInChunk( p_chunk, i_nb_samples );
5152 i_time += p_chunk->i_first_dts;
5153 p_track->i_time = i_time;
5154 p_block->i_dts = VLC_TS_0 + CLOCK_FREQ * i_time / p_track->i_timescale;
5157 int64_t i_delta = MP4_TrackGetPTSDelta( p_demux, p_track );
5159 p_block->i_pts = p_block->i_dts + i_delta;
5160 else if( p_track->fmt.i_cat != VIDEO_ES )
5161 p_block->i_pts = p_block->i_dts;
5163 p_block->i_pts = VLC_TS_INVALID;
5165 MP4_Block_Send( p_demux, p_track, p_block );
5167 if ( p_demux->p_sys->i_pcr < VLC_TS_0 )
5169 p_sys->i_time = p_track->i_time * p_sys->i_timescale / p_track->i_timescale;
5170 p_demux->p_sys->i_pcr = MP4_GetMoviePTS( p_demux->p_sys );
5171 es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + p_demux->p_sys->i_pcr );
5177 // sample size > left bytes
5181 p_track->i_sample += i_samplescounttoread;
5184 /* flag end of mdat section if needed */
5185 if ( p_sys->context.i_mdatbytesleft == 0 )
5186 p_sys->context.i_current_box_type = 0;
5193 /* Skip if we didn't reach the end of mdat box */
5194 if ( p_sys->context.i_mdatbytesleft > 0 )
5196 msg_Err( p_demux, "mdat had still %"PRIu32" bytes unparsed as samples",
5197 p_sys->context.i_mdatbytesleft );
5198 stream_ReadU32( p_demux->s, NULL, p_sys->context.i_mdatbytesleft );
5200 p_sys->context.i_current_box_type = 0;
5205 static mp4_track_t * LeafGetTrackByTrunPos( demux_t *p_demux, const uint64_t i_pos, const uint64_t i_moofpos )
5207 demux_sys_t *p_sys = p_demux->p_sys;
5209 for ( uint32_t i=0; i<p_sys->i_tracks; i++ )
5211 mp4_track_t *p_track = &p_sys->track[i];
5212 if ( !p_track->context.p_trun || !p_track->context.p_tfhd )
5214 const MP4_Box_data_trun_t *p_trun_data = p_track->context.BOXDATA(p_trun);
5215 uint64_t i_offset = 0;
5217 if ( p_track->context.BOXDATA(p_tfhd)->i_flags & MP4_TFHD_BASE_DATA_OFFSET )
5218 i_offset = p_track->context.BOXDATA(p_tfhd)->i_base_data_offset;
5220 i_offset = i_moofpos;
5222 //if ( p_track->context.BOXDATA(p_tfhd)->i_flags & MP4_TFHD_DEFAULT_BASE_IS_MOOF )
5223 // i_offset += i_moofpos;
5225 if (p_trun_data->i_flags & MP4_TRUN_DATA_OFFSET)
5226 i_offset += p_trun_data->i_data_offset;
5230 if ( i_offset == i_pos )
5237 static int LeafMapTrafTrunContextes( demux_t *p_demux, MP4_Box_t *p_moof )
5239 demux_sys_t *p_sys = p_demux->p_sys;
5242 for ( uint32_t i=0; i<p_sys->i_tracks; i++ )
5244 mp4_track_t *p_track = &p_sys->track[i];
5245 p_track->context.p_tfhd = NULL;
5246 p_track->context.p_traf = NULL;
5247 p_track->context.p_trun = NULL;
5250 if ( p_moof->i_type == ATOM_moov )
5253 MP4_Box_t *p_traf = MP4_BoxGet( p_moof, "traf" );
5256 msg_Warn( p_demux, "no traf box found!" );
5257 return VLC_EGENERIC;
5263 if ( p_traf->i_type == ATOM_traf )
5265 MP4_Box_t *p_tfhd = MP4_BoxGet( p_traf, "tfhd" );
5266 for ( uint32_t i=0; p_tfhd && i<p_sys->i_tracks; i++ )
5268 mp4_track_t *p_track = &p_sys->track[i];
5269 if ( BOXDATA(p_tfhd)->i_track_ID == p_track->i_track_ID )
5271 MP4_Box_t *p_trun = MP4_BoxGet( p_traf, "trun" );
5274 p_track->context.p_tfhd = p_tfhd;
5275 p_track->context.p_traf = p_traf;
5276 p_track->context.p_trun = p_trun;
5278 p_tfhd = NULL; /* break loop */
5282 p_traf = p_traf->p_next;
5288 static int LeafIndexGetMoofPosByTime( demux_t *p_demux, const mtime_t i_target_time,
5289 uint64_t *pi_pos, mtime_t *pi_mooftime )
5291 MP4_Box_t *p_tfra = MP4_BoxGet( p_demux->p_sys->p_root, "mfra/tfra" );
5294 if ( p_tfra->i_type == ATOM_tfra )
5297 const MP4_Box_data_tfra_t *p_data = BOXDATA(p_tfra);
5298 mp4_track_t *p_track = MP4_frg_GetTrackByID( p_demux, p_data->i_track_ID );
5299 if ( p_track && (p_track->fmt.i_cat == AUDIO_ES || p_track->fmt.i_cat == VIDEO_ES) )
5301 for ( uint32_t i = 0; i<p_data->i_number_of_entries; i += ( p_data->i_version == 1 ) ? 2 : 1 )
5305 if ( p_data->i_version == 1 )
5307 i_time = *((uint64_t *)(p_data->p_time + i));
5308 i_offset = *((uint64_t *)(p_data->p_moof_offset + i));
5312 i_time = p_data->p_time[i];
5313 i_offset = p_data->p_moof_offset[i];
5316 if ( CLOCK_FREQ * i_time / p_track->i_timescale >= i_target_time )
5318 if ( i_pos == -1 ) /* Not in this traf */
5321 *pi_pos = (uint64_t) i_pos;
5322 *pi_mooftime = CLOCK_FREQ * i_time / p_track->i_timescale;
5323 if ( p_track->fmt.i_cat == AUDIO_ES )
5324 *pi_mooftime -= CLOCK_FREQ / p_track->fmt.audio.i_rate * p_data->p_sample_number[i];
5326 *pi_mooftime -= CLOCK_FREQ / p_demux->p_sys->f_fps * p_data->p_sample_number[i];
5334 p_tfra = p_tfra->p_next;
5336 return VLC_EGENERIC;
5339 static int LeafParseMDATwithMOOF( demux_t *p_demux, MP4_Box_t *p_moof )
5341 demux_sys_t *p_sys = p_demux->p_sys;
5343 assert( p_moof->i_type == ATOM_moof );
5344 assert( p_sys->context.i_current_box_type == ATOM_mdat );
5346 if ( p_sys->context.i_mdatbytesleft == 0 )
5348 int i_ret = LeafMapTrafTrunContextes( p_demux, p_moof );
5349 if ( i_ret != VLC_SUCCESS )
5352 /* Ready mdat section */
5354 int i_read = stream_Read( p_demux->s, &mdat, 8 );
5355 p_sys->context.i_mdatbytesleft = GetDWBE( mdat );
5356 if ( i_read < 8 || p_sys->context.i_mdatbytesleft < 8 ||
5357 VLC_FOURCC( mdat[4], mdat[5], mdat[6], mdat[7] ) != ATOM_mdat )
5359 if ( MP4_stream_Tell( p_demux->s, &i_pos ) )
5360 msg_Err(p_demux, "No mdat atom at %"PRIu64, i_pos - i_read );
5361 return VLC_EGENERIC;
5363 p_sys->context.i_mdatbytesleft -= 8;
5366 if ( !MP4_stream_Tell( p_demux->s, &i_pos ) )
5367 return VLC_EGENERIC;
5368 if ( p_sys->b_smooth )
5369 i_pos -= p_moof->i_pos;
5370 mp4_track_t *p_track = LeafGetTrackByTrunPos( p_demux, i_pos, p_moof->i_pos );
5373 MP4_Box_data_tfhd_t *p_tfhd_data = p_track->context.BOXDATA(p_tfhd);
5374 uint32_t i_trun_sample_default_duration = 0;
5375 uint32_t i_trun_sample_default_size = 0;
5377 if ( p_track->context.p_trun )
5379 /* Get defaults for this/these RUN */
5380 if( p_tfhd_data->i_flags & MP4_TFHD_DFLT_SAMPLE_DURATION )
5381 i_trun_sample_default_duration = p_tfhd_data->i_default_sample_duration;
5383 if( p_tfhd_data->i_flags & MP4_TFHD_DFLT_SAMPLE_SIZE )
5384 i_trun_sample_default_size = p_tfhd_data->i_default_sample_size;
5386 if( !i_trun_sample_default_duration || !i_trun_sample_default_size )
5388 MP4_Box_t *p_trex = MP4_BoxGet( p_demux->p_sys->p_root, "moov/mvex/trex");
5391 while( p_trex && BOXDATA(p_trex)->i_track_ID != p_tfhd_data->i_track_ID )
5392 p_trex = p_trex->p_next;
5393 if ( p_trex && !i_trun_sample_default_duration )
5394 i_trun_sample_default_duration = BOXDATA(p_trex)->i_default_sample_duration;
5395 if ( p_trex && !i_trun_sample_default_size )
5396 i_trun_sample_default_size = BOXDATA(p_trex)->i_default_sample_size;
5400 const MP4_Box_data_trun_t *p_trun_data = p_track->context.BOXDATA(p_trun);
5402 /* NOW PARSE TRUN WITH MDAT */
5403 int i_ret = LeafParseTRUN( p_demux, p_track,
5404 i_trun_sample_default_duration, i_trun_sample_default_size,
5405 p_trun_data, & p_sys->context.i_mdatbytesleft );
5406 if ( i_ret != VLC_SUCCESS )
5409 p_track->context.p_trun = p_track->context.p_trun->p_next;
5412 if ( p_sys->context.i_mdatbytesleft == 0 )
5413 p_sys->context.i_current_box_type = 0;
5418 /* Skip if we didn't reach the end of mdat box */
5419 if ( p_sys->context.i_mdatbytesleft > 0 )
5421 msg_Warn( p_demux, "mdat had still %"PRIu32" bytes unparsed as samples", p_sys->context.i_mdatbytesleft - 8 );
5422 stream_ReadU32( p_demux->s, NULL, p_sys->context.i_mdatbytesleft );
5425 p_sys->context.i_current_box_type = 0;
5430 static int DemuxAsLeaf( demux_t *p_demux )
5432 demux_sys_t *p_sys = p_demux->p_sys;
5433 unsigned i_track_selected = 0;
5435 /* check for newly selected/unselected track */
5436 for( unsigned i_track = 0; i_track < p_sys->i_tracks; i_track++ )
5438 mp4_track_t *tk = &p_sys->track[i_track];
5441 if( !tk->b_ok || tk->b_chapter )
5444 es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
5445 msg_Dbg( p_demux, "track %u %s!", tk->i_track_ID, b ? "enabled" : "disabled" );
5447 if( tk->b_selected && !b )
5448 MP4_TrackUnselect( p_demux, tk );
5449 else if( !tk->b_selected && b)
5450 MP4_frg_TrackSelect( p_demux, tk );
5452 if( tk->b_selected )
5456 if( i_track_selected <= 0 )
5458 msg_Warn( p_demux, "no track selected, exiting..." );
5462 if ( p_sys->context.i_current_box_type != ATOM_mdat )
5464 /* Othewise mdat is skipped. FIXME: mdat reading ! */
5465 const uint8_t *p_peek;
5466 int i_read = stream_Peek( p_demux->s, &p_peek, 8 );
5470 p_sys->context.i_current_box_type = VLC_FOURCC( p_peek[4], p_peek[5], p_peek[6], p_peek[7] );
5472 if ( p_sys->context.i_current_box_type != ATOM_mdat )
5474 if ( ! BoxExistsInRootTree( p_sys->p_root, p_sys->context.i_current_box_type, stream_Tell( p_demux->s ) ) )
5475 {// only if !b_probed ??
5476 MP4_Box_t *p_vroot = LoadNextChunk( p_demux );
5477 switch( p_sys->context.i_current_box_type )
5481 /* create fragment */
5482 AddFragment( p_demux, p_vroot->p_first );
5488 /* Append to root */
5489 p_sys->p_root->p_last->p_next = p_vroot->p_first;
5490 p_sys->p_root->p_last = p_vroot->p_first;
5491 p_vroot->p_last = NULL;
5492 p_vroot->p_next = NULL;
5493 p_vroot->p_first = NULL;
5494 MP4_BoxFree( p_demux->s, p_vroot );
5499 msg_Err( p_demux, "skipping known chunk type %4.4s size %"PRIu32, (char*)& p_sys->context.i_current_box_type, GetDWBE( p_peek ) );
5500 stream_Read( p_demux->s, NULL, GetDWBE( p_peek ) );
5505 /* skip mdat header */
5506 p_sys->context.p_fragment = GetFragmentByPos( p_demux,
5507 stream_Tell( p_demux->s ) + 8, true );
5512 if ( p_sys->context.i_current_box_type == ATOM_mdat )
5514 assert(p_sys->context.p_fragment);
5515 if ( p_sys->context.p_fragment )
5516 switch( p_sys->context.p_fragment->p_moox->i_type )
5518 case ATOM_moov://[ftyp/moov, mdat]+ -> [moof, mdat]+
5519 LeafParseMDATwithMOOV( p_demux );
5522 LeafParseMDATwithMOOF( p_demux, p_sys->context.p_fragment->p_moox ); // BACKUP CHUNK!
5525 msg_Err( p_demux, "fragment type %4.4s", (char*) &p_sys->context.p_fragment->p_moox->i_type );
5530 /* Get current time */
5531 mtime_t i_lowest_dts = VLC_TS_INVALID;
5532 mtime_t i_lowest_time = INT64_MAX;
5533 for( unsigned int i_track = 0; i_track < p_sys->i_tracks; i_track++ )
5535 const mp4_track_t *p_track = &p_sys->track[i_track];
5536 if( !p_track->b_selected || ( p_track->fmt.i_cat != VIDEO_ES && p_track->fmt.i_cat != AUDIO_ES ) )
5539 i_lowest_time = __MIN( i_lowest_time, p_track->i_time * p_sys->i_timescale / p_track->i_timescale );
5541 if ( i_lowest_dts == VLC_TS_INVALID )
5542 i_lowest_dts = CLOCK_FREQ * p_track->i_time / p_track->i_timescale;
5544 i_lowest_dts = __MIN( i_lowest_dts, CLOCK_FREQ * p_track->i_time / p_track->i_timescale );
5547 p_sys->i_time = i_lowest_time;
5548 p_sys->i_pcr = i_lowest_dts;
5549 es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + p_sys->i_pcr );