diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 695e565d..008f10f7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -19,72 +19,66 @@ jobs: build_type: Release pcm_tests: ON - - name: "MacOS 14 arm64 (xc15)" - os: macos-14-xlarge + - name: "MacOS 27 arm64 (xc27)" + os: xcode-27 build_type: Release pcm_tests: ON - set_xcode_version_cmd: xcodes select 15.4 + set_xcode_version_cmd: xcodes select 27.1 - - name: "MacOS 14 x86_64 (xc15)" - os: macos-14-large + - name: "MacOS 26 arm64 (xc26)" + os: macos-26 build_type: Release pcm_tests: ON - set_xcode_version_cmd: xcodes select 15.4 + set_xcode_version_cmd: xcodes select 26.6 - - name: "MacOS 13 arm64 (xc14)" - os: macos-13-xlarge + - name: "MacOS 15 arm64 (xc16)" + os: macos-15 build_type: Release pcm_tests: ON - set_xcode_version_cmd: xcodes select 14.3.1 + set_xcode_version_cmd: xcodes select 16.4 - - name: "MacOS 13 x86_64 (xc14)" - os: macos-13-large + - name: "MacOS 15 x86_64 (xc16)" + os: macos-15-intel build_type: Release pcm_tests: ON - set_xcode_version_cmd: xcodes select 14.3.1 + set_xcode_version_cmd: xcodes select 16.4 - - name: "MacOS 12 (xc13)" - os: macos-12 + - name: "Ubuntu 26.04 (GCC-14)" + os: ubuntu-26.04 build_type: Release pcm_tests: ON - set_xcode_version_cmd: xcodes select 13.4.1 + cc: "gcc-14" + cxx: "g++-14" - - name: "Ubuntu 22.04 (GCC-11)" - os: ubuntu-22.04 + - name: "Ubuntu 24.04 arm64 (GCC-13)" + os: ubuntu-24.04-arm build_type: Release pcm_tests: ON - cc: "gcc-11" - cxx: "g++-11" + cc: "gcc-13" + cxx: "g++-13" - - name: "Ubuntu 22.04 (GCC-10)" - os: ubuntu-22.04 + - name: "Ubuntu 24.04 (GCC-13)" + os: ubuntu-24.04 build_type: Release pcm_tests: ON - cc: "gcc-10" - cxx: "g++-10" + cc: "gcc-13" + cxx: "g++-13" - - name: "Ubuntu 20.04 (GCC-9)" - os: ubuntu-20.04 + - name: "Ubuntu 24.04 (GCC-12)" + os: ubuntu-24.04 build_type: Release pcm_tests: ON - cc: "gcc-9" - cxx: "g++-9" + cc: "gcc-12" + cxx: "g++-12" - - name: "Ubuntu 20.04 (GCC-8)" - os: ubuntu-20.04 - build_type: Release - pcm_tests: ON - cc: "gcc-8" - cxx: "g++-8" - - - name: "Code-Coverage (Ubuntu 20.04, GCC-9)" - os: ubuntu-20.04 + - name: "Code-Coverage (Ubuntu 24.04, GCC-13)" + os: ubuntu-24.04 build_type: Coverage pcm_tests: OFF code_coverage: true - cc: "gcc-9" - cxx: "g++-9" - gcov: "gcov-9" + cc: "gcc-13" + cxx: "g++-13" + gcov: "gcov-13" steps: @@ -136,7 +130,7 @@ jobs: sudo apt-get install -y lcov lcov --version echo $(which ${GCOV}) - lcov --gcov-tool $(which ${GCOV}) -d . -c -o coverage.info + lcov --gcov-tool $(which ${GCOV}) -d . -c -o coverage.info --ignore-errors mismatch --exclude '*/test/*' - name: Upload code coverage results if: matrix.config.code_coverage == true diff --git a/audiostream/src/ni/media/audio/os/mac/core_audio_source.h b/audiostream/src/ni/media/audio/os/mac/core_audio_source.h index 3eba8b90..a9734903 100644 --- a/audiostream/src/ni/media/audio/os/mac/core_audio_source.h +++ b/audiostream/src/ni/media/audio/os/mac/core_audio_source.h @@ -335,14 +335,15 @@ void core_audio_source::setupInfo( audio::ifstream_info::container_type auto info = buildOutStreamInfo( m_media, fileId, container ); - AudioStreamBasicDescription description{.mFormatID = kAudioFormatLinearPCM, - .mChannelsPerFrame = UInt32( info.num_channels() ), - .mSampleRate = Float64( info.sample_rate() ), - .mFormatFlags = formatToAudioFormatFlags( info.format() ), - .mFramesPerPacket = 1, - .mBitsPerChannel = UInt32( info.bits_per_sample() ), - .mBytesPerPacket = UInt32( info.bytes_per_frame() ), - .mBytesPerFrame = UInt32( info.bytes_per_frame() )}; + auto description = AudioStreamBasicDescription{}; + description.mSampleRate = Float64( info.sample_rate() ); + description.mFormatID = kAudioFormatLinearPCM; + description.mFormatFlags = formatToAudioFormatFlags( info.format() ); + description.mBytesPerPacket = UInt32( info.bytes_per_frame() ); + description.mFramesPerPacket = 1; + description.mBytesPerFrame = UInt32( info.bytes_per_frame() ); + description.mChannelsPerFrame = UInt32( info.num_channels() ); + description.mBitsPerChannel = UInt32( info.bits_per_sample() ); if ( ExtAudioFileSetProperty( m_media, kExtAudioFileProperty_ClientDataFormat, sizeof( description ), &description ) != noErr ) @@ -388,10 +389,11 @@ std::streamsize core_audio_source::read( char* dst, std::streamsize size size = std::min( size, std::streamsize( end - m_pos ) ); - AudioBufferList buffer{.mNumberBuffers = 1, - .mBuffers[0] = {.mNumberChannels = UInt32( m_info.num_channels() ), - .mDataByteSize = UInt32( size ), - .mData = static_cast( dst )}}; + auto buffer = AudioBufferList{}; + buffer.mNumberBuffers = 1; + buffer.mBuffers[0].mNumberChannels = UInt32( m_info.num_channels() ); + buffer.mBuffers[0].mDataByteSize = UInt32( size ); + buffer.mBuffers[0].mData = dst; auto num_frames = UInt32( size / m_info.bytes_per_frame() ); if ( noErr != ExtAudioFileRead( m_media, &num_frames, &buffer ) ) diff --git a/audiostream/src/ni/media/audio/os/win/media_foundation_helper.h b/audiostream/src/ni/media/audio/os/win/media_foundation_helper.h index c84309ac..b9ddf04e 100644 --- a/audiostream/src/ni/media/audio/os/win/media_foundation_helper.h +++ b/audiostream/src/ni/media/audio/os/win/media_foundation_helper.h @@ -46,6 +46,10 @@ DEFINE_MEDIATYPE_GUID( MFAudioFormat_ALAC, 0x6C61 ); #endif +// The encoder delay and padding attributes are only declared for windows10 and higher +DEFINE_GUID( MF_SD_AUDIO_ENCODER_DELAY, 0x8e85422c, 0x73de, 0x403f, 0x9a, 0x35, 0x55, 0x0a, 0xd6, 0xe8, 0xb9, 0x51 ); +DEFINE_GUID( MF_SD_AUDIO_ENCODER_PADDING, 0x529c7f2c, 0xac4b, 0x4e3f, 0xbf, 0xc3, 0x09, 0x02, 0x19, 0x49, 0x82, 0xcb ); + // Flac is only defined in widows10 sdk and higher #ifndef MFAudioFormat_FLAC DEFINE_MEDIATYPE_GUID( MFAudioFormat_FLAC, 0xF1AC ); diff --git a/audiostream/src/ni/media/audio/os/win/media_foundation_source.h b/audiostream/src/ni/media/audio/os/win/media_foundation_source.h index b424c559..528f3f34 100644 --- a/audiostream/src/ni/media/audio/os/win/media_foundation_source.h +++ b/audiostream/src/ni/media/audio/os/win/media_foundation_source.h @@ -90,7 +90,10 @@ class media_foundation_source offset_type m_nominalPos = 0; offset_type m_adjustedPos = 0; - offset_type m_fadeInBlocks = 0; + offset_type m_timestampOrigin = 0; + + offset_type m_fadeInBlocks = 0; + offset_type m_largestBlockFrames = s_defaultBlockSize; bool seekInternal( offset_type ); @@ -103,7 +106,7 @@ class media_foundation_source auto consumeBlock() -> std::unique_ptr; bool updateBuffer( std::unique_ptr ); - bool discardFadeinBlock(); + bool discardFadeinBlock( offset_type ); SyncronousByteStream* m_byteStream; }; @@ -238,8 +241,7 @@ auto retrieveAudioStreamsIndices( IMFSourceReader& reader ) -> std::vector -size_t calcStreamIndex( IMFSourceReader& reader, size_t stream ) +inline size_t calcStreamIndex( const std::vector& indices, size_t stream ) { // The audio streams are indexed as follows: // @@ -251,8 +253,6 @@ size_t calcStreamIndex( IMFSourceReader& reader, size_t stream ) // ... // Stem N 0 - auto indices = retrieveAudioStreamsIndices( reader ); - size_t minSize = stream + 1; if ( indices.size() < minSize ) { @@ -263,6 +263,256 @@ size_t calcStreamIndex( IMFSourceReader& reader, size_t stream ) return indices[indices.size() - stream - 1]; } +//---------------------------------------------------------------------------------------------------------------------- + +struct EncoderDelay +{ + bool declared = false; + uint64_t priming = 0; + uint64_t padding = 0; +}; + +inline EncoderDelay readItunesEncoderDelay( IMFSourceReader& reader, size_t streamIndex ) +{ + EncoderDelay delay; + PROPVARIANT var; + if ( SUCCEEDED( reader.GetPresentationAttribute( DWORD( streamIndex ), MF_SD_AUDIO_ENCODER_DELAY, &var ) ) ) + { + delay.declared = SUCCEEDED( PropVariantToUInt64( var, &delay.priming ) ); + PropVariantClear( &var ); + } + if ( SUCCEEDED( reader.GetPresentationAttribute( DWORD( streamIndex ), MF_SD_AUDIO_ENCODER_PADDING, &var ) ) ) + { + PropVariantToUInt64( var, &delay.padding ); + PropVariantClear( &var ); + } + return delay; +} + +//---------------------------------------------------------------------------------------------------------------------- + +inline uint64_t readBigEndian( const uint8_t* data, size_t numBytes ) +{ + uint64_t value = 0; + while ( numBytes-- > 0 ) + value = ( value << 8 ) | *data++; + return value; +} + +struct Mp4Box +{ + const uint8_t* begin = nullptr; + const uint8_t* end = nullptr; + + size_t size() const + { + return size_t( end - begin ); + } +}; + +// Calls visit( type, child ) for each child box, stopping at the first malformed one. +template +void forEachMp4Box( Mp4Box parent, Visitor&& visit ) +{ + auto pos = parent.begin; + while ( parent.end - pos >= 8 ) + { + auto size = readBigEndian( pos, 4 ); + const auto type = uint32_t( readBigEndian( pos + 4, 4 ) ); + size_t headerSize = 8; + if ( size == 1 && parent.end - pos >= 16 ) + { + size = readBigEndian( pos + 8, 8 ); + headerSize = 16; + } + if ( size < headerSize || size > uint64_t( parent.end - pos ) ) + return; + + visit( type, Mp4Box{pos + headerSize, pos + size} ); + pos += size; + } +} + +inline Mp4Box findMp4Box( Mp4Box parent, uint32_t type ) +{ + Mp4Box found; + forEachMp4Box( parent, [&]( uint32_t childType, Mp4Box child ) { + if ( childType == type && !found.begin ) + found = child; + } ); + return found; +} + +struct Mp4Movie +{ + bool hasItunesBrand = false; + std::vector movieBox; +}; + +inline Mp4Movie readMp4Movie( IMFByteStream& stream ) +{ + constexpr uint64_t maxBrandsSize = 4096; + constexpr uint64_t maxMovieBoxSize = 64 << 20; + + Mp4Movie movie; + auto& payload = movie.movieBox; + uint8_t header[16]; + ULONG read = 0; + QWORD position = 0; + QWORD length = 0; + stream.GetLength( &length ); + while ( SUCCEEDED( stream.Read( header, 8, &read ) ) && read == 8 ) + { + auto size = readBigEndian( header, 4 ); + size_t headerSize = 8; + if ( size == 1 ) + { + if ( FAILED( stream.Read( header + 8, 8, &read ) ) || read != 8 ) + break; + size = readBigEndian( header + 8, 8 ); + headerSize = 16; + } + // A size of 0 means the box runs to the end of the file, so no box can follow it. A box that doesn't fit in the + // file is malformed. + if ( size < headerSize || FAILED( stream.GetCurrentPosition( &position ) ) || position > length + || size - headerSize > length - position ) + break; + + auto remaining = size - headerSize; + const auto type = readBigEndian( header + 4, 4 ); + if ( type == 'ftyp' ) + { + std::vector brands( size_t( std::min( remaining, maxBrandsSize ) ) ); + if ( FAILED( stream.Read( brands.data(), ULONG( brands.size() ), &read ) ) || read != brands.size() ) + break; + remaining -= brands.size(); + + // Layout: major brand (4 bytes), minor version (4), then the compatible brands. + for ( size_t i = 0; i + 4 <= brands.size(); i += i == 0 ? 8 : 4 ) + { + const auto brand = readBigEndian( brands.data() + i, 4 ); + if ( brand == 'M4A ' || brand == 'M4B ' ) + movie.hasItunesBrand = true; + } + } + else if ( type == 'moov' ) + { + if ( remaining <= maxMovieBoxSize ) + { + payload.resize( size_t( remaining ) ); + if ( FAILED( stream.Read( payload.data(), ULONG( payload.size() ), &read ) ) || read != payload.size() ) + payload.clear(); + } + break; + } + + if ( FAILED( stream.Seek( msoCurrent, LONGLONG( remaining ), 0, &position ) ) ) + break; + } + + stream.SetCurrentPosition( 0 ); + return movie; +} + +struct Mp4SoundTrack +{ + // Times are in the track's timescale. + uint32_t timescale = 0; + uint64_t mediaDuration = 0; + bool hasEditList = false; + uint64_t editListStart = 0; + + // Counts the last packet in full, even when the time-to-sample table shortens it, as Core Audio does. Assumes every + // packet lasts as long as the first, as AAC's 1024-frame packets do. + uint64_t packetsDuration = 0; + + bool hasRollGroup = false; +}; + +// Returns the media time at which the edit list starts playing the track's media. +inline uint64_t readMp4EditListStart( Mp4Box elst ) +{ + // Layout: version (1 byte), flags (3), entry count (4), then the entries. + constexpr size_t entriesOffset = 8; + if ( elst.size() < entriesOffset ) + return 0; + + // Each entry holds a duration, a media time and a rate (4 bytes). Version 1 stores the times in 8 bytes, version 0 + // in 4. + const size_t timeSize = elst.begin[0] == 1 ? 8 : 4; + const size_t entrySize = 2 * timeSize + 4; + + const uint64_t emptyEdit = timeSize == 8 ? UINT64_MAX : UINT32_MAX; + + for ( auto entry = elst.begin + entriesOffset; size_t( elst.end - entry ) >= entrySize; entry += entrySize ) + { + // media time -1 marks an empty edit, which delays the track rather than skipping any of it, so it's ignored + const auto mediaTime = readBigEndian( entry + timeSize, timeSize ); + if ( mediaTime != emptyEdit ) + return mediaTime; + } + return 0; +} + +// Returns the sound tracks in file order. +inline std::vector readMp4SoundTracks( const std::vector& movieBox ) +{ + std::vector soundTracks; + forEachMp4Box( Mp4Box{movieBox.data(), movieBox.data() + movieBox.size()}, [&]( uint32_t type, Mp4Box trak ) { + if ( type != 'trak' ) + return; + + // Layout: version (1 byte), flags (3), pre-defined (4), then the handler type. + constexpr size_t handlerTypeOffset = 8; + const auto mdia = findMp4Box( trak, 'mdia' ); + const auto hdlr = findMp4Box( mdia, 'hdlr' ); + if ( hdlr.size() < handlerTypeOffset + 4 || readBigEndian( hdlr.begin + handlerTypeOffset, 4 ) != 'soun' ) + return; + + Mp4SoundTrack track; + const auto elst = findMp4Box( findMp4Box( trak, 'edts' ), 'elst' ); + track.hasEditList = elst.size() > 0; + track.editListStart = readMp4EditListStart( elst ); + + // Layout: version (1 byte), flags (3), creation and modification times (4 bytes each in version 0, 8 in + // version 1), the timescale (4), then the duration (4 bytes in version 0, 8 in version 1). + const auto mdhd = findMp4Box( mdia, 'mdhd' ); + const bool isMdhdVersion1 = mdhd.size() > 0 && mdhd.begin[0] == 1; + const size_t timescaleOffset = isMdhdVersion1 ? 4 + 2 * 8 : 4 + 2 * 4; + const size_t durationSize = isMdhdVersion1 ? 8 : 4; + if ( mdhd.size() >= timescaleOffset + 4 + durationSize ) + { + track.timescale = uint32_t( readBigEndian( mdhd.begin + timescaleOffset, 4 ) ); + track.mediaDuration = readBigEndian( mdhd.begin + timescaleOffset + 4, durationSize ); + } + + const auto stbl = findMp4Box( findMp4Box( mdia, 'minf' ), 'stbl' ); + + // Layout: version (1 byte), flags (3), sample size (4), then the sample count. + constexpr size_t packetCountOffset = 8; + const auto stsz = findMp4Box( stbl, 'stsz' ); + + // Layout: version (1 byte), flags (3), entry count (4), then pairs of sample count and sample duration. + constexpr size_t packetDurationOffset = 12; + const auto stts = findMp4Box( stbl, 'stts' ); + + if ( stsz.size() >= packetCountOffset + 4 && stts.size() >= packetDurationOffset + 4 ) + track.packetsDuration = readBigEndian( stsz.begin + packetCountOffset, 4 ) + * readBigEndian( stts.begin + packetDurationOffset, 4 ); + + // Layout: version (1 byte), flags (3), then the grouping type. + constexpr size_t groupingTypeOffset = 4; + forEachMp4Box( stbl, [&]( uint32_t boxType, Mp4Box box ) { + if ( boxType == 'sgpd' && box.size() >= groupingTypeOffset + 4 + && readBigEndian( box.begin + groupingTypeOffset, 4 ) == 'roll' ) + track.hasRollGroup = true; + } ); + + soundTracks.push_back( track ); + } ); + return soundTracks; +} + } // namespace @@ -345,9 +595,6 @@ class media_foundation_source::MfBuffer BYTE* m_data = nullptr; }; -const auto defaultOffset = 0; -const auto aacOfffset = 2112; - //---------------------------------------------------------------------------------------------------------------------- template @@ -357,17 +604,18 @@ media_foundation_source::media_foundation_source( Source&& : m_initializer( new MfInitializer ) , m_byteStream( new SyncronousByteStream( std::move( source ) ) ) { - m_reader = allocateOrThrow( - [&]( IMFSourceReader** p ) { return MFCreateSourceReaderFromByteStream( m_byteStream, nullptr, p ); }, - "Could not open the audio file." ); - using codec_type = audio::ifstream_info::codec_type; using container_type = audio::ifstream_info::container_type; - if ( container_type::mp4 == container ) - m_readOffset = m_adjustedPos = aacOfffset; + const auto movie = container_type::mp4 == container ? readMp4Movie( *m_byteStream ) : Mp4Movie{}; + const auto soundTracks = readMp4SoundTracks( movie.movieBox ); - m_streamIndex = calcStreamIndex( *m_reader, stream ); + m_reader = allocateOrThrow( + [&]( IMFSourceReader** p ) { return MFCreateSourceReaderFromByteStream( m_byteStream, nullptr, p ); }, + "Could not open the audio file." ); + + const auto audioStreams = retrieveAudioStreamsIndices( *m_reader ); + m_streamIndex = calcStreamIndex( audioStreams, stream ); if ( FAILED( m_reader->SetStreamSelection( DWORD( MF_SOURCE_READER_ALL_STREAMS ), FALSE ) ) || FAILED( m_reader->SetStreamSelection( DWORD( m_streamIndex ), TRUE ) ) ) { @@ -431,6 +679,16 @@ media_foundation_source::media_foundation_source( Source&& m_info.sample_rate( sample_rate ); } + // Media Foundation decodes the encoder priming and padding as audio and ignores edit lists. + offset_type framesBeyondDuration = 0; + const Mp4SoundTrack* track = nullptr; + // calcStreamIndex reverses Media Foundation's track order, so stream also indexes the sound tracks in file order. + if ( soundTracks.size() == audioStreams.size() && soundTracks[stream].timescale > 0 ) + track = &soundTracks[stream]; + + const auto itunesDelay = + container_type::mp4 == container ? readItunesEncoderDelay( *m_reader, m_streamIndex ) : EncoderDelay{}; + { PROPVARIANT var; LONGLONG length100ns = 0; @@ -442,10 +700,43 @@ media_foundation_source::media_foundation_source( Source&& } auto lengthFrames = time100nsToFrames( length100ns, m_info.sample_rate() ); - if ( lengthFrames < m_readOffset ) + + // Chooses the priming as Core Audio does on macOS. An edit list starting past the end of the media is malformed. + const bool editListDeclaresPriming = + track && track->hasRollGroup && track->hasEditList + && track->editListStart < ( track->packetsDuration > 0 ? track->packetsDuration : track->mediaDuration ); + const bool itunesTagDeclaresPriming = itunesDelay.declared && movie.hasItunesBrand; + + if ( editListDeclaresPriming ) + { + m_readOffset = offset_type( track->editListStart * m_info.sample_rate() / track->timescale ); + } + else if ( itunesTagDeclaresPriming ) + { + m_readOffset = offset_type( itunesDelay.priming ); + + // The movie header's duration excludes the priming and padding when an edit list is also present. The + // media header's always includes them. Without it, padding is kept rather than risking cutting audio. + if ( track && track->mediaDuration > 0 ) + { + lengthFrames = offset_type( track->mediaDuration * m_info.sample_rate() / track->timescale ); + framesBeyondDuration = offset_type( itunesDelay.priming + itunesDelay.padding ); + } + } + else if ( codec_type::aac == m_info.codec() ) + { + constexpr offset_type defaultAacPriming = 2112; + m_readOffset = defaultAacPriming; + framesBeyondDuration = defaultAacPriming; + if ( track && track->packetsDuration > 0 ) + lengthFrames = offset_type( track->packetsDuration * m_info.sample_rate() / track->timescale ); + } + m_adjustedPos = m_readOffset; + + if ( lengthFrames < framesBeyondDuration ) throw std::runtime_error( "Empty File" ); - m_info.num_frames( size_t( lengthFrames - m_readOffset ) ); + m_info.num_frames( size_t( lengthFrames - framesBeyondDuration ) ); } { @@ -485,8 +776,17 @@ media_foundation_source::media_foundation_source( Source&& throw std::runtime_error( "Could not load uncompressed pcm decoder." ); } - if ( m_readOffset != 0 && !setPosition( *m_reader, framesTo100ns( m_readOffset, m_info.sample_rate() ) ) ) - throw std::runtime_error( "Could not reposition in media buffer." ); + // Media Foundation on Windows 10 timestamps the first decoded frame of an MP4 track with the start of its edit + // list, while later versions timestamp it with 0. + if ( container_type::mp4 == container ) + { + if ( const auto first = consumeBlock() ) + { + m_timestampOrigin = first->range.lower(); + if ( !seekInternal( 0 ) ) + throw std::runtime_error( "Could not rewind the audio stream." ); + } + } } //---------------------------------------------------------------------------------------------------------------------- @@ -510,7 +810,7 @@ std::streampos media_foundation_source::seek( offset_type off, BOOST_IOS const auto nominalPos = absolute_position( m_nominalPos, begPos, endPos, off / frameSize, way ); // The allowed range for the nominal offset is [0, lengthInFrames[ - // The allowed range for the adjusted offset is [aacReadOffset, lengthInFrames + aacReadOffset[ + // The allowed range for the adjusted offset is [m_readOffset, lengthInFrames + m_readOffset[ auto adjustedPos = nominalPos + m_readOffset; @@ -564,15 +864,15 @@ template bool media_foundation_source::seekInternal( offset_type adjustedPos ) { // WMF applies a fade-in to the audio data fetched after a seek, which produces crackling. To avoid this, when - // doing a seek we jump one block back of the target, then discard it in the following fetch. + // doing a seek we jump one block back of the target, then discard it in the following fetch. Targets too close to + // the start are reached by decoding from the beginning of the stream, which includes any encoder priming. constexpr offset_type fadeInBlocks = 2; - constexpr offset_type fadeInFrames = fadeInBlocks * s_defaultBlockSize; + const offset_type fadeInFrames = fadeInBlocks * m_largestBlockFrames; - static const auto minValue = fadeInFrames + m_readOffset; - bool removeFadein = adjustedPos >= minValue; + const bool removeFadein = adjustedPos >= fadeInFrames; - adjustedPos = removeFadein ? adjustedPos - fadeInFrames : m_readOffset; - if ( !setPosition( *m_reader, framesTo100ns( adjustedPos, m_info.sample_rate() ) ) ) + adjustedPos = removeFadein ? adjustedPos - fadeInFrames : 0; + if ( !setPosition( *m_reader, framesTo100ns( adjustedPos + m_timestampOrigin, m_info.sample_rate() ) ) ) return false; m_buffer.reset(); @@ -648,8 +948,8 @@ auto media_foundation_source::searchAndRetrieveBlock( offset_type target { // We start by discarding the first data block if it contains a fade-in. - if ( !discardFadeinBlock() ) - return nullptr; + if ( !discardFadeinBlock( target ) ) + return searchBackwardAndRetrieveBlock( target, 2 * s_defaultBlockSize ); // We then fetch the next block and check its timestamp to determine where we are in the audio stream, then move to // the target position. @@ -695,11 +995,12 @@ auto media_foundation_source::searchBackwardAndRetrieveBlock( offset_typ // If the target frame is behind the current position in the audio stream, we seek backwards recursively with an // increasing step until we reach it. If we overshoot, we simply move forward by consuming the excess blocks. - auto correctedTarget = target >= m_readOffset + backstep ? target - backstep : m_readOffset; + auto correctedTarget = target >= backstep ? target - backstep : 0; if ( seekInternal( correctedTarget ) ) { - if ( !discardFadeinBlock() ) - return nullptr; + if ( !discardFadeinBlock( target ) ) + return correctedTarget > 0 ? searchBackwardAndRetrieveBlock( target, 2 * backstep + 2 * s_defaultBlockSize ) + : nullptr; auto block = consumeBlock(); if ( !block ) @@ -715,9 +1016,8 @@ auto media_foundation_source::searchBackwardAndRetrieveBlock( offset_typ return searchForwardAndRetrieveBlock( target ); else { - return correctedTarget > m_readOffset - ? searchBackwardAndRetrieveBlock( target, backstep + 2 * s_defaultBlockSize ) - : nullptr; + return correctedTarget > 0 ? searchBackwardAndRetrieveBlock( target, 2 * backstep + 2 * s_defaultBlockSize ) + : nullptr; } } @@ -751,9 +1051,10 @@ auto media_foundation_source::consumeBlock() -> std::unique_ptr if ( !checkErrors( mfSample.get(), flags ) || FAILED( mfSample->GetSampleDuration( &duration ) ) ) return nullptr; - offset_type beg = - m_buffer ? m_buffer->frameRange().upper() : time100nsToFrames( timestamp, m_info.sample_rate() ); + offset_type beg = m_buffer ? m_buffer->frameRange().upper() + : time100nsToFrames( timestamp, m_info.sample_rate() ) - m_timestampOrigin; offset_type end = beg + time100nsToFrames( duration, m_info.sample_rate() ); + m_largestBlockFrames = std::max( m_largestBlockFrames, end - beg ); std::unique_ptr block( new MfBlock{{beg, end}, std::move( mfSample )} ); return block; @@ -775,18 +1076,26 @@ bool media_foundation_source::updateBuffer( std::unique_ptr blo //---------------------------------------------------------------------------------------------------------------------- template -bool media_foundation_source::discardFadeinBlock() +bool media_foundation_source::discardFadeinBlock( offset_type target ) { // If this is the first fetch after a seek we need to discard the first frame, as WMF applies a fade-in - // effect to the first few samples that produces crackling when played back by Traktor. + // effect to the first few samples that produces crackling when played back by Traktor. Returns false if a discarded + // block reaches the target, as with codecs that decode large blocks (ALAC decodes 4096 frames at a time): the seek + // then has to start further back. - while ( m_fadeInBlocks > 0 ) + for ( ; m_fadeInBlocks > 0; --m_fadeInBlocks ) { auto frame = consumeBlock(); if ( !frame ) + break; + + if ( frame->range.upper() > target ) + { + m_fadeInBlocks = 0; return false; - --m_fadeInBlocks; + } } + m_fadeInBlocks = 0; return true; } diff --git a/audiostream/test/CMakeLists.txt b/audiostream/test/CMakeLists.txt index 4f177a4f..355cf279 100644 --- a/audiostream/test/CMakeLists.txt +++ b/audiostream/test/CMakeLists.txt @@ -81,7 +81,7 @@ endif() # audio/mp4 if( NIMEDIA_ENABLE_MP4_DECODING ) - add_src_file (FILES_test_audio_mp4 "ni/media/audio/mp4/mp4_source.test.cpp" MAC) + add_src_file (FILES_test_audio_mp4 "ni/media/audio/mp4/mp4_source.test.cpp") add_src_group (FILES_test_all test_audio_mp4 FILES_test_audio_mp4) endif() diff --git a/audiostream/test/ni/media/audio/istream_read.test.h b/audiostream/test/ni/media/audio/istream_read.test.h index 4d8075b2..bc1acafb 100644 --- a/audiostream/test/ni/media/audio/istream_read.test.h +++ b/audiostream/test/ni/media/audio/istream_read.test.h @@ -29,16 +29,15 @@ #include -#include #include #include #include #include #include +#include #include #include -#include #include namespace @@ -47,10 +46,11 @@ namespace template auto generate_range() { - auto range = std::vector( 256 ); - boost::algorithm::iota( range, std::numeric_limits::lowest() ); - - static_assert( std::is_signed(), "char must be signed" ); + auto range = std::vector(); + for ( auto value = int{ std::numeric_limits::lowest() }; + value <= std::numeric_limits::max(); + ++value ) + range.push_back( static_cast( value ) ); auto format = pcm::make_format(); diff --git a/audiostream/test/ni/media/audio/mp4/mp4_source.test.cpp b/audiostream/test/ni/media/audio/mp4/mp4_source.test.cpp index f7e14368..2c9ebd40 100644 --- a/audiostream/test/ni/media/audio/mp4/mp4_source.test.cpp +++ b/audiostream/test/ni/media/audio/mp4/mp4_source.test.cpp @@ -25,10 +25,18 @@ #include #include +#include #include #include +#include #include +#include +#include + +#include +#include + class mp4_source_test : public source_test { @@ -52,8 +60,160 @@ TEST_P( mp4_source_test, ifvectorstream ) //---------------------------------------------------------------------------------------------------------------------- +#if BOOST_OS_WINDOWS + +// Media Foundation delivers the encoder priming as audio, so seeking relies on media_foundation_source skipping it. +TEST_P( mp4_source_test, seek_matches_sequential_read ) +{ + auto stream = open_file_as(); + + const auto num_channels = stream.info().num_channels(); + const auto num_frames = stream.info().num_frames(); + + auto sequential = std::vector( stream.info().num_samples() ); + stream >> sequential; + + const size_t block_frames = 1024; + for ( const size_t frame : {size_t( 0 ), size_t( 1 ), size_t( 3000 ), num_frames / 2, num_frames - block_frames} ) + { + auto block = std::vector( block_frames * num_channels ); + stream.clear(); + stream.frame_seekg( frame ); + stream >> block; + + const auto expected_begin = sequential.begin() + frame * num_channels; + EXPECT_TRUE( std::equal( block.begin(), block.end(), expected_begin ) ) << "seeking to frame " << frame; + } +} + +#endif + +//---------------------------------------------------------------------------------------------------------------------- + +// These files were made from sin440.1.44100.44100.s16le.aac192.ffmpeg.m4a, whose encoder primed 1024 frames, by +// changing its edit list to play all of the media, removing its roll sample group, or both. Every platform has to +// decode them as Core Audio does. +namespace +{ + +constexpr size_t ffmpeg_priming = 1024; + +audio::ifstream open_priming_test_file( const std::string& name ) +{ + return audio::ifstream( ( test_files_input_path() / "mp4" / name ).string() ); +} + +// Expects each decoded frame to be the frame of the 440 Hz source sine that lies offset frames later. +void expect_sin440_at_offset( audio::ifstream& stream, std::ptrdiff_t offset ) +{ + constexpr size_t source_frames = 44100; + constexpr size_t first_frame = 2048; + constexpr size_t end_frame = 42000; + + auto samples = std::vector( stream.info().num_samples() ); + stream >> samples; + ASSERT_GE( samples.size(), end_frame ); + + auto generator = *make_generator( "sin440", 1, stream.info().sample_rate() ); + auto source = std::vector( source_frames ); + boost::generate( source, generator ); + + const auto decoded = std::vector( samples.begin() + first_frame, samples.begin() + end_frame ); + const auto expected = + std::vector( source.begin() + first_frame + offset, source.begin() + end_frame + offset ); + EXPECT_GT( xcorr( decoded, expected ), 0.9998 ); +} + +// Without a roll sample group, as older ffmpeg versions write, Core Audio ignores the edit list. It assumes the +// standard 2112 frames of AAC priming, more than the encoder primed, and plays every decoded frame after them. +void expect_default_aac_priming( const std::string& name ) +{ + constexpr size_t decoded_frames = 45 * 1024; + constexpr size_t assumed_priming = 2112; + + auto stream = open_priming_test_file( name ); + ASSERT_TRUE( stream.good() ); + EXPECT_EQ( stream.info().num_frames(), decoded_frames - assumed_priming ); + expect_sin440_at_offset( stream, std::ptrdiff_t( assumed_priming - ffmpeg_priming ) ); +} + +} // namespace + +// An edit list that plays all of the media declares nothing. With a roll sample group, Core Audio plays all of it. +TEST( mp4_source_priming_test, edit_list_playing_all ) +{ + auto stream = open_priming_test_file( "sin440.ffmpeg.edit_list_plays_all.m4a" ); + ASSERT_TRUE( stream.good() ); + EXPECT_EQ( stream.info().num_frames(), size_t( 45 * 1024 ) ); + expect_sin440_at_offset( stream, -std::ptrdiff_t( ffmpeg_priming ) ); +} + +TEST( mp4_source_priming_test, undeclared_aac_priming ) +{ + expect_default_aac_priming( "sin440.ffmpeg.undeclared_priming.m4a" ); +} + +TEST( mp4_source_priming_test, edit_list_ignored_without_roll_group ) +{ + expect_default_aac_priming( "sin440.ffmpeg.edit_list_without_roll_group.m4a" ); +} + +// These files were made from a 1 second 440 Hz sine encoded by Apple's afconvert, whose encoder primed 2112 frames, by +// setting its edit list to 1024 frames, its iTunSMPB tag to 1600 frames of priming and 1404 of padding, its roll sample +// group and its brand. Each expectation is how Core Audio decodes the file. +namespace +{ + +constexpr size_t apple_priming = 2112; + +void expect_apple_file( const std::string& name, size_t num_frames, size_t applied_priming ) +{ + auto stream = open_priming_test_file( name ); + ASSERT_TRUE( stream.good() ); + EXPECT_EQ( stream.info().num_frames(), num_frames ); + expect_sin440_at_offset( stream, std::ptrdiff_t( applied_priming ) - std::ptrdiff_t( apple_priming ) ); +} + +} // namespace + +// Without a roll sample group, the edit list is ignored and the iTunSMPB tag decides. +TEST( mp4_source_priming_test, itunes_tag_with_edit_list ) +{ + expect_apple_file( "sin440.apple.itunes_tag_and_edit_list.m4a", 44100, 1600 ); +} + +TEST( mp4_source_priming_test, edit_list_with_roll_group_overrides_itunes_tag ) +{ + expect_apple_file( "sin440.apple.edit_list_with_roll_group_and_itunes_tag.m4a", 44100, 1024 ); +} + +// The iTunSMPB tag only counts in files of an iTunes brand, so this file falls back to the standard AAC priming. +TEST( mp4_source_priming_test, itunes_tag_ignored_without_itunes_brand ) +{ + expect_apple_file( "sin440.apple.itunes_tag_without_itunes_brand.m4a", 44992, apple_priming ); +} + +//---------------------------------------------------------------------------------------------------------------------- + INSTANTIATE_TEST_SUITE_P( reference_test, mp4_source_test, reference_files( audio::ifstream_info::container_type::mp4 ), ParamToString{} ); + +//---------------------------------------------------------------------------------------------------------------------- + +// A box whose 64-bit size runs past the end of the file must not send the parser back to an earlier box. +TEST( mp4_source_test_malformed, box_larger_than_file_does_not_hang ) +{ + const auto file = + std::vector{ 0, 0, 0, 16, 'f', 't', 'y', 'p', 'M', '4', 'A', ' ', 0, 0, 0, 0, + 0, 0, 0, 1, 'f', 'r', 'e', 'e', -1, -1, -1, -1, -1, -1, -1, char( 0xf0 ) }; + try + { + audio::ifvectorstream stream( file, audio::ifstream_info::container_type::mp4 ); + } + catch ( const std::exception& ) + { + } +} diff --git a/audiostream/test/ni/media/test_helper.cpp b/audiostream/test/ni/media/test_helper.cpp index 82434920..fa1cd61e 100644 --- a/audiostream/test/ni/media/test_helper.cpp +++ b/audiostream/test/ni/media/test_helper.cpp @@ -23,13 +23,11 @@ #include #include -#include #include #include #include #include #include -#include #include #include diff --git a/audiostream/test/test_files/mp4/sin440.apple.edit_list_with_roll_group_and_itunes_tag.m4a b/audiostream/test/test_files/mp4/sin440.apple.edit_list_with_roll_group_and_itunes_tag.m4a new file mode 100644 index 00000000..54361e63 Binary files /dev/null and b/audiostream/test/test_files/mp4/sin440.apple.edit_list_with_roll_group_and_itunes_tag.m4a differ diff --git a/audiostream/test/test_files/mp4/sin440.apple.itunes_tag_and_edit_list.m4a b/audiostream/test/test_files/mp4/sin440.apple.itunes_tag_and_edit_list.m4a new file mode 100644 index 00000000..71eb1d2a Binary files /dev/null and b/audiostream/test/test_files/mp4/sin440.apple.itunes_tag_and_edit_list.m4a differ diff --git a/audiostream/test/test_files/mp4/sin440.apple.itunes_tag_without_itunes_brand.m4a b/audiostream/test/test_files/mp4/sin440.apple.itunes_tag_without_itunes_brand.m4a new file mode 100644 index 00000000..ac0cccb3 Binary files /dev/null and b/audiostream/test/test_files/mp4/sin440.apple.itunes_tag_without_itunes_brand.m4a differ diff --git a/audiostream/test/test_files/mp4/sin440.ffmpeg.edit_list_plays_all.m4a b/audiostream/test/test_files/mp4/sin440.ffmpeg.edit_list_plays_all.m4a new file mode 100644 index 00000000..e71fedbb Binary files /dev/null and b/audiostream/test/test_files/mp4/sin440.ffmpeg.edit_list_plays_all.m4a differ diff --git a/audiostream/test/test_files/mp4/sin440.ffmpeg.edit_list_without_roll_group.m4a b/audiostream/test/test_files/mp4/sin440.ffmpeg.edit_list_without_roll_group.m4a new file mode 100644 index 00000000..fb760f3a Binary files /dev/null and b/audiostream/test/test_files/mp4/sin440.ffmpeg.edit_list_without_roll_group.m4a differ diff --git a/audiostream/test/test_files/mp4/sin440.ffmpeg.undeclared_priming.m4a b/audiostream/test/test_files/mp4/sin440.ffmpeg.undeclared_priming.m4a new file mode 100644 index 00000000..c63ecc97 Binary files /dev/null and b/audiostream/test/test_files/mp4/sin440.ffmpeg.undeclared_priming.m4a differ diff --git a/audiostream/test/test_files/reference_files/sin440.1.44100.44100.s16le.aac192.ffmpeg.m4a b/audiostream/test/test_files/reference_files/sin440.1.44100.44100.s16le.aac192.ffmpeg.m4a new file mode 100644 index 00000000..df6cb284 Binary files /dev/null and b/audiostream/test/test_files/reference_files/sin440.1.44100.44100.s16le.aac192.ffmpeg.m4a differ diff --git a/vcpkg.json b/vcpkg.json index 5ac0d05d..871f063b 100644 --- a/vcpkg.json +++ b/vcpkg.json @@ -13,7 +13,6 @@ "boost-format", "boost-icl", "boost-iostreams", - "boost-locale", "boost-math", "boost-program-options", "boost-system",