diff --git a/scripts/llext_link_helper.py b/scripts/llext_link_helper.py index 727234654334..e3b4f9c2dd51 100755 --- a/scripts/llext_link_helper.py +++ b/scripts/llext_link_helper.py @@ -203,6 +203,50 @@ def prune_xtensa_relocs(path): print(f'llext_link_helper.py: dropped {dropped} of {total} relocations not needing ' 'run-time processing') +def promote_defined_weak_syms(path): + # Zephyr llext_load/llext_link only index and relocate STB_GLOBAL and + # STB_LOCAL symbols, leaving STB_WEAK relocations (e.g. C++ templates + # and vtables) unpatched at 0. Promote defined STB_WEAK FUNC/OBJECT + # symbols to STB_GLOBAL so LLEXT resolves them against ext->sym_tab. + SYM_SIZE = 16 + STB_GLOBAL = 1 + STB_WEAK = 2 + STT_OBJECT = 1 + STT_FUNC = 2 + SHN_UNDEF = 0 + SHN_LORESERVE = 0xff00 + + with open(path, 'rb') as f: + elf = ELFFile(f) + if elf['e_type'] != 'ET_REL': + return + symtab = None + for section in elf.iter_sections(): + if section['sh_type'] == 'SHT_SYMTAB' and section['sh_entsize'] == SYM_SIZE: + symtab = section + break + if symtab is None: + return + sh_offset = symtab['sh_offset'] + raw = bytearray(symtab.data()) + + promoted = 0 + for off in range(0, len(raw), SYM_SIZE): + st_info = raw[off + 12] + st_shndx, = struct.unpack_from('> 4 + stype = st_info & 0xf + if (bind == STB_WEAK and stype in (STT_OBJECT, STT_FUNC) and + SHN_UNDEF < st_shndx < SHN_LORESERVE): + raw[off + 12] = (STB_GLOBAL << 4) | stype + promoted += 1 + + if promoted: + with open(path, 'r+b') as f: + f.seek(sh_offset) + f.write(raw) + print(f'llext_link_helper.py: promoted {promoted} defined STB_WEAK symbols to STB_GLOBAL') + def main(): global args @@ -380,6 +424,7 @@ def main(): if '-r' in params: prune_xtensa_relocs(f'{args.file}.tmp') + promote_defined_weak_syms(f'{args.file}.tmp') copy_command = [args.copy] diff --git a/src/audio/CMakeLists.txt b/src/audio/CMakeLists.txt index acaa0c2f708d..d46d60eed112 100644 --- a/src/audio/CMakeLists.txt +++ b/src/audio/CMakeLists.txt @@ -104,6 +104,9 @@ endif() if(CONFIG_COMP_VOLUME) add_subdirectory(volume) endif() +if(CONFIG_COMP_RESONANCE_AUDIO) + add_subdirectory(resonance_audio) +endif() if(CONFIG_COMP_WEBRTC_VAD) add_subdirectory(webrtc_vad) endif() diff --git a/src/audio/Kconfig b/src/audio/Kconfig index 2e567c1f1b04..0f3aee25c707 100644 --- a/src/audio/Kconfig +++ b/src/audio/Kconfig @@ -224,6 +224,7 @@ rsource "multiband_drc/Kconfig" rsource "mux/Kconfig" rsource "nxp/Kconfig" rsource "phase_vocoder/Kconfig" +rsource "resonance_audio/Kconfig" rsource "rtnr/Kconfig" rsource "selector/Kconfig" rsource "smart_amp/Kconfig" diff --git a/src/audio/resonance_audio/CMakeLists.txt b/src/audio/resonance_audio/CMakeLists.txt new file mode 100644 index 000000000000..fcce04877591 --- /dev/null +++ b/src/audio/resonance_audio/CMakeLists.txt @@ -0,0 +1,17 @@ +# SPDX-License-Identifier: BSD-3-Clause + +if(CONFIG_COMP_RESONANCE_AUDIO STREQUAL "m" AND DEFINED CONFIG_LLEXT) + add_subdirectory(llext ${PROJECT_BINARY_DIR}/resonance_audio_llext) + add_dependencies(app resonance_audio) +else() + add_local_sources(sof resonance_audio.c) + if(CONFIG_COMP_RESONANCE_AUDIO_STUB) + add_local_sources(sof resonance_audio-stub.c) + else() + include(${CMAKE_CURRENT_LIST_DIR}/resonance_audio.cmake) + add_local_sources(sof resonance_audio-real.c resonance_shims.c) + add_dependencies(modules_sof resonance_audio_ext) + target_link_libraries(modules_sof PUBLIC + "${RESONANCE_AUDIO_INSTALL_DIR}/lib/libresonance_audio_dsp.a") + endif() +endif() diff --git a/src/audio/resonance_audio/Kconfig b/src/audio/resonance_audio/Kconfig new file mode 100644 index 000000000000..85b44aae4c77 --- /dev/null +++ b/src/audio/resonance_audio/Kconfig @@ -0,0 +1,33 @@ +# SPDX-License-Identifier: BSD-3-Clause + +config COMP_RESONANCE_AUDIO + tristate "Google Resonance Audio spatializer (virtual surround & FOA)" + help + Select to include the Google Resonance Audio spatializer module. + Renders Mono, Stereo, 5.1, 7.1, and 1st-order Ambisonics (AmbiX) + into 2-channel binaural stereo using SADIE HRTF measurements, with + ALSA kcontrol support for head-tracking orientation and speaker mode. + + Source is fetched via west (resonance-audio + eigen + pffft). + For CI builds without external sources, select COMP_RESONANCE_AUDIO_STUB. + +if COMP_RESONANCE_AUDIO + +config COMP_RESONANCE_AUDIO_STUB + bool "Resonance Audio stub backend (dependency-free stereo downmix)" + default y if COMP_STUBS + help + Build the resonance_audio module with a dependency-free stereo + downmix stub backend. Useful for CI validation of the SOF module + adapter, LLEXT packaging, and topology wiring without C++ Resonance + Audio sources. + +config RESONANCE_AUDIO_ROOM_REVERB + bool "Enable shoebox room reflections & spectral reverb by default" + default n + help + Enables Resonance Audio room early reflections and spectral reverb + by default on pipeline prepare(). Can also be toggled at runtime via + ALSA switch/bytes kcontrol. + +endif # COMP_RESONANCE_AUDIO diff --git a/src/audio/resonance_audio/llext/CMakeLists.txt b/src/audio/resonance_audio/llext/CMakeLists.txt new file mode 100644 index 000000000000..637882a999a6 --- /dev/null +++ b/src/audio/resonance_audio/llext/CMakeLists.txt @@ -0,0 +1,26 @@ +# Copyright (c) 2026 Intel Corporation. +# SPDX-License-Identifier: Apache-2.0 + +if(CONFIG_COMP_RESONANCE_AUDIO_STUB) + sof_llext_build("resonance_audio" + SOURCES ../resonance_audio.c + ../resonance_audio-stub.c + LIB openmodules + ) +else() + include(${CMAKE_CURRENT_LIST_DIR}/../resonance_audio.cmake) + + sof_llext_build("resonance_audio" + SOURCES ../resonance_audio.c + ../resonance_audio-real.c + ../resonance_shims.c + INCLUDES "${CMAKE_CURRENT_LIST_DIR}/.." + CFLAGS -DLLEXT_MODULE -DLL_EXTENSION_BUILD + LIBS_PATH "${RESONANCE_AUDIO_INSTALL_DIR}/lib" + LIBS resonance_audio_dsp + LIB openmodules + ) + + add_dependencies(resonance_audio_llext_lib resonance_audio_ext) + add_dependencies(resonance_audio resonance_audio_ext) +endif() diff --git a/src/audio/resonance_audio/llext/llext.toml.h b/src/audio/resonance_audio/llext/llext.toml.h new file mode 100644 index 000000000000..3eda8d676e6b --- /dev/null +++ b/src/audio/resonance_audio/llext/llext.toml.h @@ -0,0 +1,6 @@ +#include +#define LOAD_TYPE "2" +#include "../resonance_audio.toml" + +[module] +count = __COUNTER__ diff --git a/src/audio/resonance_audio/overrides/ambisonics/ambisonic_lookup_table.cc b/src/audio/resonance_audio/overrides/ambisonics/ambisonic_lookup_table.cc new file mode 100644 index 000000000000..d43259404189 --- /dev/null +++ b/src/audio/resonance_audio/overrides/ambisonics/ambisonic_lookup_table.cc @@ -0,0 +1,246 @@ +/* +Copyright 2018 Google Inc. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS-IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +#include "ambisonics/ambisonic_lookup_table.h" + +#include "ambisonics/ambisonic_spread_coefficients.h" +#include "ambisonics/associated_legendre_polynomials_generator.h" +#include "ambisonics/utils.h" +#include "base/constants_and_types.h" +#include "base/misc_math.h" + + +namespace vraudio { + +namespace { + +// Number of azimuth angles to store in the pre-computed encoder lookup table +// (for 0 - 90 degrees using 1 degree increments). +const size_t kNumAzimuths = 91; + +// Number of elevation angles to store in the pre-computed encoder lookup table +// (for 0 - 90 degrees using 1 degree increments). +const size_t kNumElevations = 91; + +// Number of Cartesian axes for which to compute spherical harmonic symmetries. +const size_t kNumAxes = 3; + +// Minimum angular source spreads at different orders for which we start to +// apply spread gain correction coefficients. Array index corresponds to +// ambisonic order. For more information about sound source spread control, +// please refer to the Matlab code and the corresponding paper. +const int kMinSpreads[kMaxSupportedAmbisonicOrder + 1] = {361, 54, 40, 31}; + +// Spread coefficients are stored sequentially in a 1-d table. Therefore, to +// access coefficients for the required ambisonic order we need to apply offsets +// which are equal to the total number of coefficients for previous orders. For +// example, the total number of coefficient in each ambisonic order 'n' is +// equal to the number of unique orders multiplied by number of unique spreads, +// i.e.: (n + 1) * (360 - kMinSpreads[n] + 1). +const int kSpreadCoeffOffsets[kMaxSupportedAmbisonicOrder + 1] = {0, 1, 615, + 1578}; + +size_t GetEncoderTableIndex(size_t i, size_t j, size_t k, size_t width, + size_t depth) { + return i * width * depth + j * depth + k; +} + +size_t GetSymmetriesTableIndex(size_t i, size_t j, size_t width) { + return i * width + j; +} + +int GetSpreadTableIndex(int ambisonic_order, float source_spread_deg) { + // Number of unique ambisonic orders in the sound field. For example, in a + // first order sound field we have components of order 0 and 1. + const int num_unique_orders = ambisonic_order + 1; + return kSpreadCoeffOffsets[ambisonic_order] + + num_unique_orders * (static_cast(source_spread_deg) - + kMinSpreads[ambisonic_order]); +} + +} // namespace + +AmbisonicLookupTable::AmbisonicLookupTable(int max_ambisonic_order) + : max_ambisonic_order_(max_ambisonic_order), + max_num_coeffs_in_table_( + GetNumPeriphonicComponents(max_ambisonic_order_) - 1), + encoder_table_(kNumAzimuths * kNumElevations * max_num_coeffs_in_table_), + symmetries_table_(kNumAxes * max_num_coeffs_in_table_) { + DCHECK_GE(max_ambisonic_order_, 0); + DCHECK_LE(max_ambisonic_order_, kMaxSupportedAmbisonicOrder); + ComputeEncoderTable(); + ComputeSymmetriesTable(); +} + +void AmbisonicLookupTable::GetEncodingCoeffs( + int ambisonic_order, const SphericalAngle& source_direction, + float source_spread_deg, std::vector* encoding_coeffs) const { + + DCHECK_GE(ambisonic_order, 0); + DCHECK_LE(ambisonic_order, kMaxSupportedAmbisonicOrder); + DCHECK_GE(source_spread_deg, 0.0f); + DCHECK_LE(source_spread_deg, 360.0f); + DCHECK(encoding_coeffs); + // Raw coefficients are stored only for ambisonic orders 1 and up, since 0th + // order raw coefficient is always 1. + const size_t num_raw_coeffs = GetNumPeriphonicComponents(ambisonic_order) - 1; + // The actual number of returned Ambisonic coefficients is therefore + // |num_raw_coeffs + 1|. + DCHECK_EQ(encoding_coeffs->size(), num_raw_coeffs + 1); + DCHECK_GE(source_direction.azimuth(), -kPi); + DCHECK_LE(source_direction.azimuth(), kTwoPi); + DCHECK_GE(source_direction.elevation(), -kHalfPi); + DCHECK_LE(source_direction.elevation(), kHalfPi); + const int azimuth_deg = + source_direction.azimuth() < kPi + ? static_cast(source_direction.azimuth() * kDegreesFromRadians) + : static_cast(source_direction.azimuth() * kDegreesFromRadians) - + 360; + const int elevation_deg = + static_cast(source_direction.elevation() * kDegreesFromRadians); + const size_t abs_azimuth_deg = static_cast(std::abs(azimuth_deg)); + const size_t azimuth_idx = + abs_azimuth_deg > 90 ? 180 - abs_azimuth_deg : abs_azimuth_deg; + const size_t elevation_idx = static_cast(std::abs(elevation_deg)); + (*encoding_coeffs)[0] = 1.0f; + for (size_t raw_coeff_idx = 0; raw_coeff_idx < num_raw_coeffs; + ++raw_coeff_idx) { + // Variable to hold information about spherical harmonic phase flip. 1 means + // no flip; -1 means 180 degrees flip. + float flip = 1.0f; + // The following three 'if' statements implement the logic to correct the + // phase of the current spherical harmonic, depending on which quadrant the + // sound source is located in. For more information, please see the Matlab + // code and the corresponding paper. + if (azimuth_deg < 0) { + flip = symmetries_table_[GetSymmetriesTableIndex( + 0, raw_coeff_idx, max_num_coeffs_in_table_)]; + } + if (elevation_deg < 0) { + flip *= symmetries_table_[GetSymmetriesTableIndex( + 1, raw_coeff_idx, max_num_coeffs_in_table_)]; + } + if (abs_azimuth_deg > 90) { + flip *= symmetries_table_[GetSymmetriesTableIndex( + 2, raw_coeff_idx, max_num_coeffs_in_table_)]; + } + const size_t encoder_table_idx = + GetEncoderTableIndex(azimuth_idx, elevation_idx, raw_coeff_idx, + kNumElevations, max_num_coeffs_in_table_); + (*encoding_coeffs)[raw_coeff_idx + 1] = + encoder_table_[encoder_table_idx] * flip; + } + + // If the spread is more than min. theoretical spread for the given + // |ambisonic_order|, multiply the encoding coefficients by the required + // spread control gains from the |kSpreadCoeffs| lookup table. + if (source_spread_deg >= kMinSpreads[ambisonic_order]) { + const int spread_table_idx = + GetSpreadTableIndex(ambisonic_order, source_spread_deg); + (*encoding_coeffs)[0] *= kSpreadCoeffs[spread_table_idx]; + for (size_t coeff = 1; coeff < encoding_coeffs->size(); ++coeff) { + const int current_coefficient_degree = + GetPeriphonicAmbisonicOrderForChannel(coeff); + (*encoding_coeffs)[coeff] *= + kSpreadCoeffs[spread_table_idx + current_coefficient_degree]; + } + } +} + +void AmbisonicLookupTable::ComputeEncoderTable() { + // Precompute horizontal trig terms (kMaxSupportedAmbisonicOrder + 1 orders x 91 angles) + // and flip the loops so |alp_generator.Generate| runs 91 times instead of 8,281. + std::vector cos_az((max_ambisonic_order_ + 1) * kNumAzimuths); + std::vector sin_az((max_ambisonic_order_ + 1) * kNumAzimuths); + for (int m = 0; m <= max_ambisonic_order_; ++m) { + for (size_t az = 0; az < kNumAzimuths; ++az) { + const float phase = static_cast(m) * + static_cast(az) * kRadiansFromDegrees; + cos_az[m * kNumAzimuths + az] = std::cos(phase); + sin_az[m * kNumAzimuths + az] = std::sin(phase); + } + } + + std::vector norm_vals(max_num_coeffs_in_table_); + std::vector alp_indices(max_num_coeffs_in_table_); + AssociatedLegendrePolynomialsGenerator alp_generator( + max_ambisonic_order_, /*condon_shortley_phase=*/false, + /*compute_negative_order=*/false); + for (int degree = 1; degree <= max_ambisonic_order_; ++degree) { + for (int order = -degree; order <= degree; ++order) { + const size_t raw_coeff_idx = AcnSequence(degree, order) - 1; + norm_vals[raw_coeff_idx] = Sn3dNormalization(degree, order); + alp_indices[raw_coeff_idx] = + alp_generator.GetIndex(degree, std::abs(order)); + } + } + + for (size_t elevation_idx = 0; elevation_idx < kNumElevations; ++elevation_idx) { + const float elevation_rad = + static_cast(elevation_idx) * kRadiansFromDegrees; + const std::vector alp_vals = + alp_generator.Generate(std::sin(elevation_rad)); + for (size_t azimuth_idx = 0; azimuth_idx < kNumAzimuths; ++azimuth_idx) { + for (int degree = 1; degree <= max_ambisonic_order_; ++degree) { + for (int order = -degree; order <= degree; ++order) { + const size_t raw_coeff_idx = AcnSequence(degree, order) - 1; + const float alp_value = alp_vals[alp_indices[raw_coeff_idx]]; + const float horiz = + (order >= 0) ? cos_az[order * kNumAzimuths + azimuth_idx] + : sin_az[(-order) * kNumAzimuths + azimuth_idx]; + const size_t encoder_table_idx = + GetEncoderTableIndex(azimuth_idx, elevation_idx, raw_coeff_idx, + kNumElevations, max_num_coeffs_in_table_); + encoder_table_[encoder_table_idx] = + norm_vals[raw_coeff_idx] * alp_value * horiz; + } + } + } + } +} + +void AmbisonicLookupTable::ComputeSymmetriesTable() { + + for (int degree = 1; degree <= max_ambisonic_order_; ++degree) { + for (int order = -degree; order <= degree; ++order) { + const size_t raw_coeff_idx = AcnSequence(degree, order) - 1; + // Symmetry wrt the left-right axis (Y). + symmetries_table_[GetSymmetriesTableIndex(0, raw_coeff_idx, + max_num_coeffs_in_table_)] = + order < 0 ? -1.0f : 1.0f; + // Symmetry wrt the up-down axis (Z). + symmetries_table_[GetSymmetriesTableIndex(1, raw_coeff_idx, + max_num_coeffs_in_table_)] = + static_cast(IntegerPow(-1, degree + order)); + // Symmetry wrt the front-back axis (X). + symmetries_table_[GetSymmetriesTableIndex(2, raw_coeff_idx, + max_num_coeffs_in_table_)] = + order < 0 ? static_cast(-IntegerPow(-1, std::abs(order))) + : static_cast(IntegerPow(-1, order)); + } + } +} + +float AmbisonicLookupTable::UnnormalizedSphericalHarmonic(float alp_value, + int order, + float azimuth_rad) { + const float horizontal_term = + (order >= 0) ? std::cos(static_cast(order) * azimuth_rad) + : std::sin(static_cast(-order) * azimuth_rad); + return alp_value * horizontal_term; +} + +} // namespace vraudio diff --git a/src/audio/resonance_audio/overrides/base/constants_and_types.h b/src/audio/resonance_audio/overrides/base/constants_and_types.h new file mode 100644 index 000000000000..f4e463b48d47 --- /dev/null +++ b/src/audio/resonance_audio/overrides/base/constants_and_types.h @@ -0,0 +1,176 @@ +/* +Copyright 2018 Google Inc. All Rights Reserved. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS-IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +#ifndef RESONANCE_AUDIO_BASE_CONSTANTS_AND_TYPES_H_ +#define RESONANCE_AUDIO_BASE_CONSTANTS_AND_TYPES_H_ + +#include +#include // for size_t + +namespace vraudio { + +// Sound object / ambisonic source identifier. + +typedef int SourceId; + +// Invalid source id that can be used to initialize handler variables during +// class construction. +static const SourceId kInvalidSourceId = -1; + + +// Defines memory alignment of audio buffers. Note that not only the first +// element of the |data_| buffer is memory aligned but also the address of the +// first elements of the |ChannelView|s. +const size_t kMemoryAlignmentBytes = 64; + +// Maximum Ambisonic order currently supported in vr audio, equivalent to High +// Quality sound object rendering mode. This number is limited by a) number of +// HRIR data points used in the binaural renderer; b) size of the lookup table +// controlling the angular spread of a sound source in the Ambisonic Lookup +// Table class. +static const int kMaxSupportedAmbisonicOrder = 3; + +// Maximum allowed size of internal buffers (capped for SOF DSP SRAM/DRAM). +const size_t kMaxSupportedNumFrames = 256; + +// Number of mono channels. +static const size_t kNumMonoChannels = 1; + +// Number of stereo channels. +static const size_t kNumStereoChannels = 2; + +// Number of surround 5.1 channels. +static const size_t kNumSurroundFiveDotOneChannels = 6; + +// Number of surround 7.1 channels. +static const size_t kNumSurroundSevenDotOneChannels = 8; + +// Number of first-order ambisonic channels. +static const size_t kNumFirstOrderAmbisonicChannels = 4; + +// Number of second-order ambisonic channels. +static const size_t kNumSecondOrderAmbisonicChannels = 9; + +// Number of third-order ambisonic channels. +static const size_t kNumThirdOrderAmbisonicChannels = 16; + +// Number of first-order ambisonic with non-diegetic stereo channels. +static const size_t kNumFirstOrderAmbisonicWithNonDiegeticStereoChannels = 6; + +// Number of second-order ambisonic with non-diegetic stereo channels. +static const size_t kNumSecondOrderAmbisonicWithNonDiegeticStereoChannels = 11; + +// Number of third-order ambisonic with non-diegetic stereo channels. +static const size_t kNumThirdOrderAmbisonicWithNonDiegeticStereoChannels = 18; + +// Negative 60dB in amplitude. +static const float kNegative60dbInAmplitude = 0.001f; + +// Tolerated error margins for floating points. +static const double kEpsilonDouble = 1e-6; +static const float kEpsilonFloat = 1e-6f; + +// Inverse square root of two (equivalent to -3dB audio signal attenuation). +static const float kInverseSqrtTwo = 1.0f / std::sqrt(2.0f); + +// Square roots. +static const float kSqrtTwo = std::sqrt(2.0f); +static const float kSqrtThree = std::sqrt(3.0f); + +// Pi in radians. +static const float kPi = static_cast(M_PI); +// Half pi in radians. +static const float kHalfPi = static_cast(M_PI / 2.0); +// Two pi in radians. +static const float kTwoPi = static_cast(2.0 * M_PI); + +// Defines conversion factor from degrees to radians. +static const float kRadiansFromDegrees = static_cast(M_PI / 180.0); + +// Defines conversion factor from radians to degrees. +static const float kDegreesFromRadians = static_cast(180.0 / M_PI); + +// The negated natural logarithm of 1000. +static const float kNegativeLog1000 = -std::log(1000.0f); + +// The lowest octave band for computing room effects. +static const float kLowestOctaveBandHz = 31.25f; + +// Number of octave bands in which room effects are computed. +static const size_t kNumReverbOctaveBands = 9; + +// Centers of possible frequency bands up 8 kHz. +// ------------------------------------ +// Band no. Low Center High [Frequencies in Hz] +// ------------------------------------ +// 0 22 31.25 44.2 +// 1 44.2 62.5 88.4 +// 2 88.4 125 176.8 +// 3 176.8 250 353.6 +// 4 353.6 500 707.1 +// 5 707.1 1000 1414.2 +// 6 1414.2 2000 2828.4 +// 7 2828.4 4000 5656.9 +// 8 5656.9 8000 11313.7 +//-------------------------------------- +const float kOctaveBandCentres[kNumReverbOctaveBands] = { + 31.25f, 62.5f, 125.0f, 250.0f, 500.0f, 1000.0f, 2000.0f, 4000.0f, 8000.0f}; + +// Number of surfaces in a shoe-box room. +static const size_t kNumRoomSurfaces = 6; + +// Speed of sound in air at 20 degrees Celsius in meters per second. +// http://www.sengpielaudio.com/calculator-speedsound.htm +static const float kSpeedOfSound = 343.0f; + +// Locations of the stereo virtual loudspeakers in degrees. +static const float kStereoLeftDegrees = 90.0f; +static const float kStereoRightDegrees = -90.0f; + +// Conversion factor from seconds to milliseconds. +static const float kMillisecondsFromSeconds = 1000.0f; + +// Conversion factor from milliseconds to seconds. +static const float kSecondsFromMilliseconds = 0.001f; + +// Conversion factor from seconds to milliseconds. +static const double kMicrosecondsFromSeconds = 1e6; + +// Conversion factor from milliseconds to seconds. +static const double kSecondsFromMicroseconds = 1e-6; + +// The distance threshold where the near field effect should fade in. +static const float kNearFieldThreshold = 1.0f; + +// Minimum allowed distance of a near field sound source used to cap the allowed +// energy boost. +static const float kMinNearFieldDistance = 0.1f; + +// Maximum gain applied by Near Field Effect to the mono source signal. +static const float kMaxNearFieldEffectGain = 9.0f; + +// Number of samples across which the gain value should be interpolated for +// a unit gain change of 1.0f. + +static const size_t kUnitRampLength = 2048; + +// Rotation quantization which applies in ambisonic soundfield rotators. + +static const float kRotationQuantizationRad = 1.0f * kRadiansFromDegrees; + +} // namespace vraudio + +#endif // RESONANCE_AUDIO_BASE_CONSTANTS_AND_TYPES_H_ diff --git a/src/audio/resonance_audio/overrides/base/logging.h b/src/audio/resonance_audio/overrides/base/logging.h new file mode 100644 index 000000000000..5ce35f576078 --- /dev/null +++ b/src/audio/resonance_audio/overrides/base/logging.h @@ -0,0 +1,86 @@ +/* SPDX-License-Identifier: BSD-3-Clause + * + * Lightweight embedded logging override for Google Resonance Audio on SOF DSP. + * Eliminates , , and abort() dependencies from libstdc++. + */ +#ifndef RESONANCE_AUDIO_PLATFORM_LOGGING_H_ +#define RESONANCE_AUDIO_PLATFORM_LOGGING_H_ + +#include + +#undef DCHECK +#undef DCHECK_EQ +#undef DCHECK_NE +#undef DCHECK_LE +#undef DCHECK_LT +#undef DCHECK_GE +#undef DCHECK_GT +#undef CHECK +#undef CHECK_EQ +#undef CHECK_NE +#undef CHECK_LE +#undef CHECK_LT +#undef CHECK_GE +#undef CHECK_GT +#undef CHECK_NOTNULL +#undef LOG + +extern "C" void resonance_panic(void); + +namespace vraudio_log_detail { + +struct NullStream { + template + NullStream& operator<<(const T&) { + return *this; + } +}; + +struct FatalStream { + ~FatalStream() { + resonance_panic(); + } + template + FatalStream& operator<<(const T&) { + return *this; + } +}; + +} // namespace vraudio_log_detail + +#define DCHECK(expr) \ + if (false && (expr)) {} else vraudio_log_detail::NullStream() +#define DCHECK_OP(val1, val2, op) DCHECK((val1) op (val2)) + +#define DCHECK_EQ(val1, val2) DCHECK_OP((val1), (val2), ==) +#define DCHECK_NE(val1, val2) DCHECK_OP((val1), (val2), !=) +#define DCHECK_LE(val1, val2) DCHECK_OP((val1), (val2), <=) +#define DCHECK_LT(val1, val2) DCHECK_OP((val1), (val2), <) +#define DCHECK_GE(val1, val2) DCHECK_OP((val1), (val2), >=) +#define DCHECK_GT(val1, val2) DCHECK_OP((val1), (val2), >) + +#define CHECK(condition) \ + if (!(condition)) { resonance_panic(); } \ + vraudio_log_detail::NullStream() + +#define CHECK_OP(val1, val2, op) CHECK((val1) op (val2)) + +#define CHECK_EQ(val1, val2) CHECK_OP((val1), (val2), ==) +#define CHECK_NE(val1, val2) CHECK_OP((val1), (val2), !=) +#define CHECK_LE(val1, val2) CHECK_OP((val1), (val2), <=) +#define CHECK_LT(val1, val2) CHECK_OP((val1), (val2), <) +#define CHECK_GE(val1, val2) CHECK_OP((val1), (val2), >=) +#define CHECK_GT(val1, val2) CHECK_OP((val1), (val2), >) + +template +inline T CheckNotNull(T&& t) { + if (t == nullptr) { + resonance_panic(); + } + return std::forward(t); +} +#define CHECK_NOTNULL(val) CheckNotNull(val) + +#define LOG(severity) vraudio_log_detail::NullStream() + +#endif // RESONANCE_AUDIO_PLATFORM_LOGGING_H_ diff --git a/src/audio/resonance_audio/overrides/config/global_config.h b/src/audio/resonance_audio/overrides/config/global_config.h new file mode 100644 index 000000000000..29fecdb92bf9 --- /dev/null +++ b/src/audio/resonance_audio/overrides/config/global_config.h @@ -0,0 +1,24 @@ +/* SPDX-License-Identifier: BSD-3-Clause + * + * Embedded GlobalConfig override for Resonance Audio on SOF DSP. + * Caps Ambisonic order at 1st-order HOA (4 internal channels) to minimize + * SRAM/heap footprint and .rodata HRIR assets. + */ +#ifndef RESONANCE_AUDIO_CONFIG_GLOBAL_CONFIG_H_ +#define RESONANCE_AUDIO_CONFIG_GLOBAL_CONFIG_H_ + +#include "graph/graph_manager_config.h" + +namespace vraudio { + +inline GraphManagerConfig GlobalConfig() { + GraphManagerConfig config; + config.configuration_name = "SOF FOA Config"; + config.max_ambisonic_order = 1; + config.sh_hrir_filenames = {{1, "WAV/Subject_002/SH/sh_hrir_order_1.wav"}}; + return config; +} + +} // namespace vraudio + +#endif // RESONANCE_AUDIO_CONFIG_GLOBAL_CONFIG_H_ diff --git a/src/audio/resonance_audio/overrides/graph/reflections_node.h b/src/audio/resonance_audio/overrides/graph/reflections_node.h new file mode 100644 index 000000000000..8003e5a89cd5 --- /dev/null +++ b/src/audio/resonance_audio/overrides/graph/reflections_node.h @@ -0,0 +1,30 @@ +/* + * Copyright(c) 2026 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#ifdef CONFIG_RESONANCE_AUDIO_ROOM_REVERB +#include_next "graph/reflections_node.h" +#else +#ifndef RESONANCE_AUDIO_GRAPH_REFLECTIONS_NODE_H_ +#define RESONANCE_AUDIO_GRAPH_REFLECTIONS_NODE_H_ + +#include "graph/system_settings.h" +#include "node/processing_node.h" + +namespace vraudio { + +/* Lightweight stub when room reverb/reflections are disabled to save ~430 KB DRAM. */ +class ReflectionsNode : public ProcessingNode { + public: + explicit ReflectionsNode(const SystemSettings&) {} + void Update() {} + + protected: + const AudioBuffer* AudioProcess(const NodeInput&) override { return nullptr; } +}; + +} // namespace vraudio + +#endif // RESONANCE_AUDIO_GRAPH_REFLECTIONS_NODE_H_ +#endif // CONFIG_RESONANCE_AUDIO_ROOM_REVERB diff --git a/src/audio/resonance_audio/overrides/graph/reverb_node.h b/src/audio/resonance_audio/overrides/graph/reverb_node.h new file mode 100644 index 000000000000..af8590e6b683 --- /dev/null +++ b/src/audio/resonance_audio/overrides/graph/reverb_node.h @@ -0,0 +1,31 @@ +/* + * Copyright(c) 2026 Intel Corporation. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + */ + +#ifdef CONFIG_RESONANCE_AUDIO_ROOM_REVERB +#include_next "graph/reverb_node.h" +#else +#ifndef RESONANCE_AUDIO_GRAPH_REVERB_NODE_H_ +#define RESONANCE_AUDIO_GRAPH_REVERB_NODE_H_ + +#include "dsp/fft_manager.h" +#include "graph/system_settings.h" +#include "node/processing_node.h" + +namespace vraudio { + +/* Lightweight stub when room reverb is disabled to save ~1.28 MB DRAM + ~78 KB rodata. */ +class ReverbNode : public ProcessingNode { + public: + ReverbNode(const SystemSettings&, FftManager*) {} + void Update() {} + + protected: + const AudioBuffer* AudioProcess(const NodeInput&) override { return nullptr; } +}; + +} // namespace vraudio + +#endif // RESONANCE_AUDIO_GRAPH_REVERB_NODE_H_ +#endif // CONFIG_RESONANCE_AUDIO_ROOM_REVERB diff --git a/src/audio/resonance_audio/resonance_audio-real.c b/src/audio/resonance_audio/resonance_audio-real.c new file mode 100644 index 000000000000..dc00990743fd --- /dev/null +++ b/src/audio/resonance_audio/resonance_audio-real.c @@ -0,0 +1,157 @@ +/* SPDX-License-Identifier: BSD-3-Clause + * + * Real C++17 Google Resonance Audio backend glue for SOF. + */ + +#include +#include +#include +#include "resonance_audio.h" +#include "resonance_wrapper.h" + +static enum resonance_input_mode resolve_input_mode(int in_channels, + uint32_t mode_override) +{ + if (mode_override <= RESONANCE_MODE_FOA_AMBIX) + return (enum resonance_input_mode)mode_override; + + switch (in_channels) { + case 1: + return RESONANCE_MODE_MONO; + case 2: + return RESONANCE_MODE_STEREO; + case 4: + return RESONANCE_MODE_FOA_AMBIX; + case 6: + return RESONANCE_MODE_SURROUND_51; + case 8: + return RESONANCE_MODE_SURROUND_71; + default: + return RESONANCE_MODE_STEREO; + } +} + +static int real_init(struct processing_module *mod) +{ + struct resonance_comp_data *cd = module_get_private_data(mod); + + cd->backend_ctx = NULL; + return 0; +} + +static int real_configure(struct processing_module *mod, int sample_rate_hz, + int block_frames, int in_channels, + uint32_t mode_override, bool speaker_mode, + bool room_enable, float master_volume) +{ + struct resonance_comp_data *cd = module_get_private_data(mod); + struct resonance_cfg cfg; + resonance_inst_t *inst; + + if (cd->backend_ctx) { + resonance_free((resonance_inst_t *)cd->backend_ctx); + cd->backend_ctx = NULL; + } + + cfg.sample_rate_hz = sample_rate_hz; + cfg.frames_per_buffer = (size_t)block_frames; + cfg.mode = resolve_input_mode(in_channels, mode_override); + cfg.stereo_speaker_mode = speaker_mode; + cfg.room_reverb_enable = room_enable; + cfg.master_volume = master_volume; + + inst = resonance_create(&cfg); + if (!inst) + return -EINVAL; + + resonance_set_head_pose(inst, cd->head_pos, cd->head_quat); + cd->backend_ctx = inst; + return 0; +} + +static int real_process(struct processing_module *mod, + const float *in_interleaved, int in_channels, + float *out_interleaved, int num_frames) +{ + struct resonance_comp_data *cd = module_get_private_data(mod); + resonance_inst_t *inst = (resonance_inst_t *)cd->backend_ctx; + + if (!inst) + return -EINVAL; + + return resonance_process(inst, in_interleaved, (size_t)in_channels, + out_interleaved, (size_t)num_frames); +} + +static void real_set_pose(struct processing_module *mod, const float pos[3], + const float quat[4]) +{ + struct resonance_comp_data *cd = module_get_private_data(mod); + resonance_inst_t *inst = (resonance_inst_t *)cd->backend_ctx; + + if (inst) + resonance_set_head_pose(inst, pos, quat); +} + +static void real_set_speaker_mode(struct processing_module *mod, bool enabled) +{ + struct resonance_comp_data *cd = module_get_private_data(mod); + resonance_inst_t *inst = (resonance_inst_t *)cd->backend_ctx; + + if (inst) + resonance_set_stereo_speaker_mode(inst, enabled); +} + +static void real_set_room_enable(struct processing_module *mod, bool enabled) +{ + struct resonance_comp_data *cd = module_get_private_data(mod); + resonance_inst_t *inst = (resonance_inst_t *)cd->backend_ctx; + + if (inst) + resonance_set_room_enabled(inst, enabled); +} + +static void real_set_volume(struct processing_module *mod, float volume) +{ + struct resonance_comp_data *cd = module_get_private_data(mod); + resonance_inst_t *inst = (resonance_inst_t *)cd->backend_ctx; + + if (inst) + resonance_set_master_volume(inst, volume); +} + +static int real_reset(struct processing_module *mod) +{ + struct resonance_comp_data *cd = module_get_private_data(mod); + + if (!cd->configured) + return 0; + + return real_configure(mod, cd->sample_rate, cd->block_frames, + cd->in_channels, cd->mode_override, + cd->speaker_mode, cd->room_enable, + cd->master_volume); +} + +static void real_free(struct processing_module *mod) +{ + struct resonance_comp_data *cd = module_get_private_data(mod); + + if (cd->backend_ctx) { + resonance_free((resonance_inst_t *)cd->backend_ctx); + cd->backend_ctx = NULL; + } +} + +const struct resonance_backend resonance_backend = { + .name = "resonance-audio-foa", + .init = real_init, + .configure = real_configure, + .process = real_process, + .set_pose = real_set_pose, + .set_speaker_mode = real_set_speaker_mode, + .set_room_enable = real_set_room_enable, + .set_volume = real_set_volume, + .reset = real_reset, + .free = real_free, +}; diff --git a/src/audio/resonance_audio/resonance_audio-stub.c b/src/audio/resonance_audio/resonance_audio-stub.c new file mode 100644 index 000000000000..0f6d8e7bdcf6 --- /dev/null +++ b/src/audio/resonance_audio/resonance_audio-stub.c @@ -0,0 +1,106 @@ +/* SPDX-License-Identifier: BSD-3-Clause + * + * Dependency-free stub backend for Google Resonance Audio (CI / stub builds). + * Downmixes/copies input channels cleanly to stereo output without HRTF. + */ + +#include +#include "resonance_audio.h" + +void resonance_audio_backend_enter(struct processing_module *mod) +{ + (void)mod; +} + +void resonance_audio_backend_exit(struct processing_module *mod) +{ + (void)mod; +} + +void resonance_audio_set_active_mod(struct processing_module *mod) +{ + (void)mod; +} + +struct processing_module *resonance_audio_get_active_mod(void) +{ + return NULL; +} + +static int stub_init(struct processing_module *mod) +{ + (void)mod; + return 0; +} + +static int stub_configure(struct processing_module *mod, int sample_rate_hz, + int block_frames, int in_channels, + uint32_t mode_override, bool speaker_mode, + bool room_enable, float master_volume) +{ + (void)mod; + (void)sample_rate_hz; + (void)block_frames; + (void)in_channels; + (void)mode_override; + (void)speaker_mode; + (void)room_enable; + (void)master_volume; + return 0; +} + +static int stub_process(struct processing_module *mod, + const float *in_interleaved, int in_channels, + float *out_interleaved, int num_frames) +{ + struct resonance_comp_data *cd = module_get_private_data(mod); + float gain = cd ? cd->master_volume : 1.0f; + int f; + + for (f = 0; f < num_frames; f++) { + const float *in = &in_interleaved[f * in_channels]; + float *out = &out_interleaved[f * RESONANCE_OUT_CHANNELS]; + + if (in_channels == 1) { + out[0] = in[0] * gain; + out[1] = in[0] * gain; + } else if (in_channels == 2) { + out[0] = in[0] * gain; + out[1] = in[1] * gain; + } else if (in_channels == 4) { + /* Basic FOA W+Y M-S decode: L = W + Y, R = W - Y */ + out[0] = (in[0] + in[1]) * 0.5f * gain; + out[1] = (in[0] - in[1]) * 0.5f * gain; + } else { + /* 5.1 / 7.1 simple stereo folddown (L, R, C, LS, RS) */ + float c = (in_channels >= 3) ? in[2] * 0.707f : 0.0f; + float ls = (in_channels >= 6) ? in[4] * 0.5f : 0.0f; + float rs = (in_channels >= 6) ? in[5] * 0.5f : 0.0f; + + out[0] = (in[0] + c + ls) * 0.5f * gain; + out[1] = (in[1] + c + rs) * 0.5f * gain; + } + } + + return 0; +} + +static int stub_reset(struct processing_module *mod) +{ + (void)mod; + return 0; +} + +static void stub_free(struct processing_module *mod) +{ + (void)mod; +} + +const struct resonance_backend resonance_backend = { + .name = "resonance-audio-stub", + .init = stub_init, + .configure = stub_configure, + .process = stub_process, + .reset = stub_reset, + .free = stub_free, +}; diff --git a/src/audio/resonance_audio/resonance_audio.c b/src/audio/resonance_audio/resonance_audio.c new file mode 100644 index 000000000000..b0260e1a17c0 --- /dev/null +++ b/src/audio/resonance_audio/resonance_audio.c @@ -0,0 +1,1139 @@ +/* SPDX-License-Identifier: BSD-3-Clause + * + * Google Resonance Audio spatializer module — SOF module_interface core. + * + * Single multi-channel input (1/2/4/6/8 ch) -> 2-channel binaural stereo output. + * Accumulates interleaved PCM frames into normalized float [-1, 1], applies + * staged IPC4 kcontrol pose/mode updates on the audio thread, and drains + * stereo binaural output symmetrically via an output lookahead FIFO. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if CONFIG_IPC_MAJOR_4 +#include +#include +#endif + +#include "resonance_audio.h" + +SOF_DEFINE_REG_UUID(resonance_audio); + +LOG_MODULE_REGISTER(resonance_audio, CONFIG_SOF_LOG_LEVEL); + +#define RESONANCE_S32_INV_SCALE (1.0f / 2147483648.0f) +#define RESONANCE_S16_INV_SCALE (1.0f / 32768.0f) +#define RESONANCE_S32_SCALE 2147483648.0f +#define RESONANCE_S16_SCALE 32768.0f + +static void init_default_state(struct resonance_comp_data *cd) +{ + cd->enabled = true; + cd->speaker_mode = false; + cd->room_enable = IS_ENABLED(CONFIG_RESONANCE_AUDIO_ROOM_REVERB); + cd->mode_override = RESONANCE_INPUT_MODE_AUTO; + cd->master_volume = 1.0f; + cd->head_pos[0] = 0.0f; + cd->head_pos[1] = 0.0f; + cd->head_pos[2] = 0.0f; + cd->head_quat[0] = 0.0f; + cd->head_quat[1] = 0.0f; + cd->head_quat[2] = 0.0f; + cd->head_quat[3] = 1.0f; +} + +__cold static int resonance_init(struct processing_module *mod) +{ + struct module_data *md = &mod->priv; + struct comp_dev *dev = mod->dev; + struct resonance_comp_data *cd; + int ret = 0; + + assert_can_be_cold(); + comp_info(dev, "resonance_audio: init"); + + cd = mod_zalloc(mod, sizeof(*cd)); + if (!cd) + return -ENOMEM; + + md->private = cd; + cd->backend = &resonance_backend; + init_default_state(cd); + + /* Pin 0: multi-ch PCM audio; Pin 1: optional compressed mmap spatial metadata. */ + mod->max_sources = 2; + + if (cd->backend->init) { + resonance_audio_backend_enter(mod); + ret = cd->backend->init(mod); + resonance_audio_backend_exit(mod); + if (ret) { + comp_err(dev, "resonance_audio: backend init failed %d", ret); + mod_free(mod, cd); + return ret; + } + } + + return 0; +} + +static bool is_valid_in_channels(int ch) +{ + return ch == 1 || ch == 2 || ch == 4 || ch == 6 || ch == 8; +} + +static bool is_finite_f32(float v) +{ + uint32_t bits; + + memcpy(&bits, &v, sizeof(bits)); + return (bits & 0x7f800000U) != 0x7f800000U; +} + +static void resonance_resolve_sources(struct sof_source **sources, int num_of_sources, + int *audio_idx, int *meta_idx) +{ + int i; + + *audio_idx = -1; + *meta_idx = -1; + + for (i = 0; i < num_of_sources; i++) { +#if CONFIG_IPC_MAJOR_4 + uint32_t q = IPC4_SINK_QUEUE_ID(source_get_id(sources[i])); + + if (q == 1 && *meta_idx < 0) + *meta_idx = i; + else if (*audio_idx < 0) + *audio_idx = i; + else if (*meta_idx < 0) + *meta_idx = i; +#else + if (*audio_idx < 0) + *audio_idx = i; + else if (*meta_idx < 0) + *meta_idx = i; +#endif + } +} + +static uint32_t resonance_effective_mode(int in_ch, uint32_t mode_override) +{ + if (mode_override <= RESONANCE_INPUT_MODE_MAX) + return mode_override; + + switch (in_ch) { + case 1: + return 0U; /* RESONANCE_MODE_MONO */ + case 2: + return 1U; /* RESONANCE_MODE_STEREO */ + case 4: + return 4U; /* RESONANCE_MODE_FOA_AMBIX */ + case 6: + return 2U; /* RESONANCE_MODE_SURROUND_51 */ + case 8: + return 3U; /* RESONANCE_MODE_SURROUND_71 */ + default: + return RESONANCE_INPUT_MODE_AUTO; + } +} + +#if CONFIG_IPC_MAJOR_4 +static bool is_sequential_slot_chmap(uint32_t ch_map, int in_ch) +{ + int c; + + for (c = 0; c < in_ch; c++) { + if (((ch_map >> (c * 4)) & 0xFU) != (uint32_t)c) + return false; + } + return true; +} + +static int find_chmap_slot(uint32_t ch_map, int in_ch, uint8_t target, uint8_t alt) +{ + int c; + + for (c = 0; c < in_ch; c++) { + if (((ch_map >> (c * 4)) & 0xFU) == target) + return c; + } + if (alt != CHANNEL_INVALID) { + for (c = 0; c < in_ch; c++) { + if (((ch_map >> (c * 4)) & 0xFU) == alt) + return c; + } + } + return -1; +} +#endif + +static int resonance_setup_in_chmap(struct processing_module *mod, + struct resonance_comp_data *cd, int in_ch) +{ + int c; + + for (c = 0; c < in_ch; c++) + cd->in_perm[c] = (uint8_t)c; + cd->in_identity_map = true; + + /* AmbiX 4-channel ACN/SN3D does not follow speaker-position channel maps. */ + if (resonance_effective_mode(in_ch, cd->mode_override) == RESONANCE_INPUT_MODE_MAX) + return 0; + +#if CONFIG_IPC_MAJOR_4 + { + const struct ipc4_audio_format *fmt0 = + (mod->priv.cfg.nb_input_pins > 0 && mod->priv.cfg.input_pins) ? + &mod->priv.cfg.input_pins[0].audio_fmt : + &mod->priv.cfg.base_cfg.audio_fmt; + uint32_t ch_map = fmt0->ch_map; + + if (fmt0->channels_count != (uint32_t)in_ch || + ch_map == 0 || ch_map == 0xFFFFFFFFU || + is_sequential_slot_chmap(ch_map, in_ch)) + return 0; + + static const uint8_t want_2ch[2] = { CHANNEL_LEFT, CHANNEL_RIGHT }; + static const uint8_t want_6ch[6] = { + CHANNEL_LEFT, CHANNEL_RIGHT, CHANNEL_CENTER, + CHANNEL_LFE, CHANNEL_LEFT_SURROUND, CHANNEL_RIGHT_SURROUND + }; + static const uint8_t alt_6ch[6] = { + CHANNEL_INVALID, CHANNEL_INVALID, CHANNEL_INVALID, + CHANNEL_INVALID, CHANNEL_LEFT_SIDE, CHANNEL_RIGHT_SIDE + }; + static const uint8_t want_8ch[8] = { + CHANNEL_LEFT, CHANNEL_RIGHT, CHANNEL_CENTER, CHANNEL_LFE, + CHANNEL_LEFT_SIDE, CHANNEL_RIGHT_SIDE, + CHANNEL_LEFT_SURROUND, CHANNEL_RIGHT_SURROUND + }; + uint32_t used_mask = 0; + + if (in_ch == 1) { + uint8_t ch0 = ch_map & 0xFU; + + if (ch0 != CHANNEL_LEFT && ch0 != CHANNEL_CENTER && + ch0 != CHANNEL_RIGHT) { + comp_err(mod->dev, + "resonance_audio: unsupported mono ch_map 0x%08x", + ch_map); + return -EINVAL; + } + cd->in_perm[0] = 0; + return 0; + } + + for (c = 0; c < in_ch; c++) { + uint8_t want = (in_ch == 2) ? want_2ch[c] : + (in_ch == 6) ? want_6ch[c] : want_8ch[c]; + uint8_t alt = (in_ch == 6) ? alt_6ch[c] : CHANNEL_INVALID; + int slot = find_chmap_slot(ch_map, in_ch, want, alt); + + if (slot < 0 || (used_mask & BIT(slot))) { + comp_err(mod->dev, + "resonance_audio: unsupported ch_map 0x%08x for ch=%d", + ch_map, in_ch); + return -EINVAL; + } + used_mask |= BIT(slot); + cd->in_perm[c] = (uint8_t)slot; + if (slot != c) + cd->in_identity_map = false; + } + } +#else + (void)mod; +#endif + return 0; +} + +static int resonance_configure_audio(struct processing_module *mod, + struct resonance_comp_data *cd, + struct sof_source *audio_src, + struct sof_sink *snk) +{ + struct comp_dev *dev = mod->dev; + int in_rate = source_get_rate(audio_src); + int out_rate = sink_get_rate(snk); + int in_fmt = source_get_frm_fmt(audio_src); + int out_fmt = sink_get_frm_fmt(snk); + int in_ch = source_get_channels(audio_src); + int out_ch = sink_get_channels(snk); + int ret; + + if (!is_valid_in_channels(in_ch)) { + comp_err(dev, "resonance_audio: unsupported input channels %d", in_ch); + return -EINVAL; + } + if (out_ch != RESONANCE_OUT_CHANNELS) { + comp_err(dev, "resonance_audio: output must be stereo (got %d)", out_ch); + return -EINVAL; + } + if (in_rate != out_rate || (in_rate != 44100 && in_rate != 48000)) { + comp_err(dev, "resonance_audio: unsupported rates in=%d out=%d", + in_rate, out_rate); + return -EINVAL; + } + if (in_fmt != out_fmt || + (in_fmt != SOF_IPC_FRAME_S16_LE && in_fmt != SOF_IPC_FRAME_S32_LE)) { + comp_err(dev, "resonance_audio: unsupported formats in=%d out=%d", + in_fmt, out_fmt); + return -EINVAL; + } + + ret = resonance_setup_in_chmap(mod, cd, in_ch); + if (ret) + return ret; + + cd->sample_rate = in_rate; + cd->in_channels = in_ch; + cd->out_channels = out_ch; + cd->block_frames = (in_rate == 48000) ? + RESONANCE_BLOCK_FRAMES_48K : RESONANCE_BLOCK_FRAMES_DEFAULT; + + comp_info(dev, "resonance_audio: rate=%d in_ch=%d out_ch=%d block=%d", + cd->sample_rate, cd->in_channels, cd->out_channels, + cd->block_frames); + + if (cd->backend->configure) { + resonance_audio_backend_enter(mod); + ret = cd->backend->configure(mod, cd->sample_rate, + cd->block_frames, cd->in_channels, + cd->mode_override, cd->speaker_mode, + cd->room_enable, cd->master_volume); + resonance_audio_backend_exit(mod); + if (ret) { + comp_err(dev, "resonance_audio: backend configure failed %d", ret); + return ret; + } + } + + cd->buffered_in_frames = 0; + memset(cd->out_fifo, 0, + (size_t)cd->block_frames * RESONANCE_OUT_CHANNELS * sizeof(float)); + cd->buffered_out_frames = cd->block_frames; + cd->pose_dirty = false; + cd->speaker_dirty = false; + cd->room_dirty = false; + cd->volume_dirty = false; + cd->configured = true; + return 0; +} + +__cold static int resonance_prepare(struct processing_module *mod, + struct sof_source **sources, int num_of_sources, + struct sof_sink **sinks, int num_of_sinks) +{ + struct resonance_comp_data *cd = module_get_private_data(mod); + struct comp_dev *dev = mod->dev; + int audio_idx, meta_idx; + + assert_can_be_cold(); + + if (num_of_sources < 1 || num_of_sources > 2 || num_of_sinks != 1) { + comp_err(dev, "resonance_audio: need 1 or 2 sources and 1 sink (got %d/%d)", + num_of_sources, num_of_sinks); + return -EINVAL; + } + + resonance_resolve_sources(sources, num_of_sources, &audio_idx, &meta_idx); + +#if CONFIG_IPC_MAJOR_4 + if (meta_idx >= 0 && mod->priv.cfg.nb_input_pins > 1 && mod->priv.cfg.input_pins) + ipc4_update_source_format(sources[meta_idx], + &mod->priv.cfg.input_pins[1].audio_fmt); +#endif + + cd->meta_buf_len = 0; + + if (audio_idx < 0) { + /* Pin 1 metadata pipeline opened before Pin 0 audio; defer configure until bind. */ + cd->configured = false; + return 0; + } + + return resonance_configure_audio(mod, cd, sources[audio_idx], sinks[0]); +} + +static void s32_to_float_interleaved(float *dst, const int32_t *src, + int n_frames, int channels, + const uint8_t *perm, bool identity) +{ + if (identity) { + int total = n_frames * channels; + int i; + + for (i = 0; i < total; i++) + dst[i] = (float)src[i] * RESONANCE_S32_INV_SCALE; + return; + } + + for (int f = 0; f < n_frames; f++) { + const int32_t *in_f = &src[f * channels]; + float *out_f = &dst[f * channels]; + + for (int c = 0; c < channels; c++) + out_f[c] = (float)in_f[perm[c]] * RESONANCE_S32_INV_SCALE; + } +} + +static void s16_to_float_interleaved(float *dst, const int16_t *src, + int n_frames, int channels, + const uint8_t *perm, bool identity) +{ + if (identity) { + int total = n_frames * channels; + int i; + + for (i = 0; i < total; i++) + dst[i] = (float)src[i] * RESONANCE_S16_INV_SCALE; + return; + } + + for (int f = 0; f < n_frames; f++) { + const int16_t *in_f = &src[f * channels]; + float *out_f = &dst[f * channels]; + + for (int c = 0; c < channels; c++) + out_f[c] = (float)in_f[perm[c]] * RESONANCE_S16_INV_SCALE; + } +} + +static void float_to_s32_interleaved(int32_t *dst, const float *src, + int n_frames, int channels) +{ + int total = n_frames * channels; + int i; + + for (i = 0; i < total; i++) { + float f = src[i] * RESONANCE_S32_SCALE; + + if (f >= 2147483520.0f) + f = 2147483520.0f; + else if (f < -2147483648.0f) + f = -2147483648.0f; + dst[i] = (int32_t)f; + } +} + +static void float_to_s16_interleaved(int16_t *dst, const float *src, + int n_frames, int channels) +{ + int total = n_frames * channels; + int i; + + for (i = 0; i < total; i++) { + float f = src[i] * RESONANCE_S16_SCALE; + + if (f > 32767.0f) + f = 32767.0f; + else if (f < -32768.0f) + f = -32768.0f; + dst[i] = (int16_t)f; + } +} + +static void bypass_folddown(const float *in, int in_ch, float *out, int n_frames) +{ + int f; + + for (f = 0; f < n_frames; f++) { + const float *s = &in[f * in_ch]; + float *d = &out[f * RESONANCE_OUT_CHANNELS]; + + if (in_ch == 1) { + d[0] = s[0]; + d[1] = s[0]; + } else { + d[0] = s[0]; + d[1] = s[1]; + } + } +} + +static void flush_pending_controls(struct processing_module *mod, + struct resonance_comp_data *cd) +{ + if (cd->pose_dirty) { + cd->pose_dirty = false; + if (cd->backend->set_pose) + cd->backend->set_pose(mod, cd->head_pos, cd->head_quat); + } + if (cd->speaker_dirty) { + cd->speaker_dirty = false; + if (cd->backend->set_speaker_mode) + cd->backend->set_speaker_mode(mod, cd->speaker_mode); + } + if (cd->room_dirty) { + cd->room_dirty = false; + if (cd->backend->set_room_enable) + cd->backend->set_room_enable(mod, cd->room_enable); + } + if (cd->volume_dirty) { + cd->volume_dirty = false; + if (cd->backend->set_volume) + cd->backend->set_volume(mod, cd->master_volume); + } +} + +static int resonance_apply_pose_cfg(struct processing_module *mod, + struct resonance_comp_data *cd, + const uint8_t *data, size_t size) +{ + struct sof_resonance_pose_cfg cfg; + int i; + + if (size < sizeof(cfg)) { + comp_err(mod->dev, "resonance_audio: pose cfg too small (%zu < %zu)", + size, sizeof(cfg)); + return -EINVAL; + } + + memcpy(&cfg, data, sizeof(cfg)); + if (cfg.magic != RESONANCE_POSE_CFG_MAGIC || + cfg.version != RESONANCE_POSE_CFG_VERSION) { + comp_err(mod->dev, "resonance_audio: invalid pose cfg magic/ver 0x%x/%u", + cfg.magic, cfg.version); + return -EINVAL; + } + + for (i = 0; i < 3; i++) { + if (!is_finite_f32(cfg.head_pos[i])) + return -EINVAL; + } + for (i = 0; i < 4; i++) { + if (!is_finite_f32(cfg.head_quat[i])) + return -EINVAL; + } + if (!is_finite_f32(cfg.master_volume)) + return -EINVAL; + + memcpy(cd->head_pos, cfg.head_pos, sizeof(cd->head_pos)); + memcpy(cd->head_quat, cfg.head_quat, sizeof(cd->head_quat)); + cd->pose_dirty = true; + + if (cfg.master_volume > 0.0f) { + cd->master_volume = cfg.master_volume; + cd->volume_dirty = true; + } + + cd->speaker_mode = (cfg.flags & BIT(0)) != 0; + cd->speaker_dirty = true; + cd->room_enable = (cfg.flags & BIT(1)) != 0; + cd->room_dirty = true; + cd->enabled = (cfg.flags & BIT(2)) != 0; + + if (cfg.input_mode <= RESONANCE_INPUT_MODE_MAX || + cfg.input_mode == RESONANCE_INPUT_MODE_AUTO) + cd->mode_override = cfg.input_mode; + + return 0; +} + +static void resonance_apply_dma_frame(struct processing_module *mod, + struct resonance_comp_data *cd, + const uint8_t *pkt) +{ + struct sof_resonance_pose_dma_frame frame; + + memcpy(&frame, pkt, sizeof(frame)); + if (frame.cfg.magic != RESONANCE_POSE_CFG_MAGIC || + frame.cfg.version != RESONANCE_POSE_CFG_VERSION || + frame.seq == 0 || frame.seq == cd->dma_last_seq) + return; + + if (frame.checksum != 0 && + frame.checksum != resonance_pose_dma_checksum(&frame)) + return; + + if (resonance_apply_pose_cfg(mod, cd, (const uint8_t *)&frame.cfg, + sizeof(frame.cfg)) == 0) { + cd->dma_last_seq = frame.seq; + cd->dma_last_ts_us = frame.timestamp_us; + cd->dma_pkt_count++; + if (cd->dma_pkt_count == 1) + comp_info(mod->dev, + "resonance_audio: DMA pose stream active (seq=%u)", + frame.seq); + } +} + +static void resonance_consume_meta_bytes(struct processing_module *mod, + struct resonance_comp_data *cd, + const uint8_t *data, size_t len) +{ + size_t pos = 0; + + while (pos < len) { + if (cd->meta_buf_len > 0) { + size_t need = RESONANCE_DMA_PACKET_BYTES - cd->meta_buf_len; + size_t take = MIN(len - pos, need); + + memcpy(&cd->meta_buf[cd->meta_buf_len], &data[pos], take); + cd->meta_buf_len += take; + pos += take; + + if (cd->meta_buf_len >= 4) { + uint32_t m; + + memcpy(&m, cd->meta_buf, sizeof(m)); + if (m != RESONANCE_POSE_CFG_MAGIC) { + if (cd->meta_buf_len > 4) + memmove(cd->meta_buf, + &cd->meta_buf[4], + cd->meta_buf_len - 4); + cd->meta_buf_len -= 4; + continue; + } + } + + if (cd->meta_buf_len == RESONANCE_DMA_PACKET_BYTES) { + resonance_apply_dma_frame(mod, cd, cd->meta_buf); + cd->meta_buf_len = 0; + } + continue; + } + + if (len - pos >= 4) { + uint32_t m; + + memcpy(&m, &data[pos], sizeof(m)); + if (m != RESONANCE_POSE_CFG_MAGIC) { + pos += 4; + continue; + } + + if (len - pos >= RESONANCE_DMA_PACKET_BYTES) { + resonance_apply_dma_frame(mod, cd, &data[pos]); + pos += RESONANCE_DMA_PACKET_BYTES; + continue; + } + } + + { + size_t rem = len - pos; + + memcpy(cd->meta_buf, &data[pos], rem); + cd->meta_buf_len = rem; + break; + } + } +} + +static void resonance_drain_metadata_source(struct processing_module *mod, + struct resonance_comp_data *cd, + struct sof_source *meta) +{ + size_t avail = source_get_data_available(meta); + + while (avail > 0) { + size_t chunk = MIN(avail, (size_t)(RESONANCE_DMA_PACKET_BYTES * 4)); + const void *data_ptr = NULL; + const void *buf_start = NULL; + const uint8_t *buf_end; + const uint8_t *r_ptr; + size_t buf_bytes = 0; + size_t rem; + + if (source_get_data(meta, chunk, &data_ptr, &buf_start, &buf_bytes)) + break; + + buf_end = (const uint8_t *)buf_start + buf_bytes; + r_ptr = (const uint8_t *)data_ptr; + rem = chunk; + + while (rem > 0) { + size_t contiguous = (size_t)(buf_end - r_ptr); + size_t span = MIN(rem, contiguous); + + if (!span) + break; + + resonance_consume_meta_bytes(mod, cd, r_ptr, span); + rem -= span; + r_ptr += span; + if (r_ptr >= buf_end) + r_ptr = (const uint8_t *)buf_start; + } + + source_release_data(meta, chunk); + avail -= chunk; + } +} + +static bool resonance_is_ready_to_process(struct processing_module *mod, + struct sof_source **sources, + int num_of_sources, + struct sof_sink **sinks, + int num_of_sinks) +{ + struct resonance_comp_data *cd = module_get_private_data(mod); + int audio_idx, meta_idx; + + if (!cd || num_of_sources < 1 || num_of_sinks < 1) + return false; + + resonance_resolve_sources(sources, num_of_sources, &audio_idx, &meta_idx); + (void)meta_idx; + + if (audio_idx < 0) + return false; + + if (!cd->configured) { + if (resonance_configure_audio(mod, cd, sources[audio_idx], sinks[0])) + return false; + } + + /* Pin 1 metadata is optional; never block Pin 0 audio waiting for metadata. */ + return source_get_data_available(sources[audio_idx]) >= + source_get_min_available(sources[audio_idx]) && + sink_get_free_size(sinks[0]) >= sink_get_min_free_space(sinks[0]); +} + +static int resonance_process(struct processing_module *mod, + struct sof_source **sources, int num_of_sources, + struct sof_sink **sinks, int num_of_sinks) +{ + struct resonance_comp_data *cd = module_get_private_data(mod); + struct sof_source *src; + struct sof_sink *snk; + enum sof_ipc_frame fmt; + size_t sample_bytes; + size_t in_frame_bytes; + size_t out_frame_bytes; + int avail, free_frames, n; + size_t in_nbytes, out_nbytes, src_bytes, snk_bytes; + struct cir_buf_source source_buf; + struct cir_buf_sink sink_buf; + int audio_idx, meta_idx, ret, drain; + + if (num_of_sources < 1 || num_of_sinks < 1) + return 0; + + resonance_resolve_sources(sources, num_of_sources, &audio_idx, &meta_idx); + if (meta_idx >= 0) + resonance_drain_metadata_source(mod, cd, sources[meta_idx]); + + if (audio_idx < 0 || !cd->configured) + return 0; + + src = sources[audio_idx]; + snk = sinks[0]; + fmt = source_get_frm_fmt(src); + sample_bytes = (fmt == SOF_IPC_FRAME_S16_LE) ? sizeof(int16_t) : sizeof(int32_t); + in_frame_bytes = source_get_frame_bytes(src); + out_frame_bytes = sink_get_frame_bytes(snk); + avail = (int)source_get_data_frames_available(src); + free_frames = (int)sink_get_free_frames(snk); + n = MIN(avail, free_frames); + + if (n <= 0) + return 0; + + int max_blocks = (RESONANCE_FIFO_FRAMES - cd->buffered_out_frames) / cd->block_frames; + int max_total_in = max_blocks * cd->block_frames + (cd->block_frames - 1); + int max_in_fifo = RESONANCE_FIFO_FRAMES - cd->buffered_in_frames; + int max_for_out = MAX(max_total_in - cd->buffered_in_frames, 0); + + n = MIN(n, MIN(max_in_fifo, max_for_out)); + if (n <= 0) + return 0; + + in_nbytes = (size_t)n * in_frame_bytes; + out_nbytes = (size_t)n * out_frame_bytes; + + ret = source_get_data(src, in_nbytes, &source_buf.ptr, + &source_buf.buf_start, &src_bytes); + if (ret) + return ret; + source_buf.buf_end = (const char *)source_buf.buf_start + src_bytes; + + ret = sink_get_buffer(snk, out_nbytes, &sink_buf.ptr, + &sink_buf.buf_start, &snk_bytes); + if (ret) { + source_release_data(src, 0); + return ret; + } + sink_buf.buf_end = (char *)sink_buf.buf_start + snk_bytes; + + { + size_t remaining = (size_t)n; + size_t offset = (size_t)cd->buffered_in_frames; + const void *r_ptr = source_buf.ptr; + + while (remaining) { + size_t fmax = circ_buf_frames_without_wrap(r_ptr, source_buf.buf_end, + sample_bytes, cd->in_channels); + size_t f = MIN(remaining, fmax); + float *dst = &cd->in_buf[offset * cd->in_channels]; + + if (fmt == SOF_IPC_FRAME_S32_LE) + s32_to_float_interleaved(dst, r_ptr, (int)f, cd->in_channels, + cd->in_perm, cd->in_identity_map); + else + s16_to_float_interleaved(dst, r_ptr, (int)f, cd->in_channels, + cd->in_perm, cd->in_identity_map); + + remaining -= f; + offset += f; + r_ptr = source_cir_buf_wrap((const char *)r_ptr + f * in_frame_bytes, + source_buf.buf_start, source_buf.buf_end); + } + } + + source_release_data(src, in_nbytes); + cd->buffered_in_frames += n; + + resonance_audio_backend_enter(mod); + flush_pending_controls(mod, cd); + + while (cd->buffered_in_frames >= cd->block_frames && + cd->buffered_out_frames + cd->block_frames <= RESONANCE_FIFO_FRAMES) { + int bs = cd->block_frames; + float *out_dst = &cd->out_fifo[cd->buffered_out_frames * RESONANCE_OUT_CHANNELS]; + + if (cd->enabled && cd->backend->process) { + ret = cd->backend->process(mod, cd->in_buf, cd->in_channels, + out_dst, bs); + if (ret) { + comp_err(mod->dev, "resonance_audio: process err %d", ret); + bypass_folddown(cd->in_buf, cd->in_channels, out_dst, bs); + } + } else { + bypass_folddown(cd->in_buf, cd->in_channels, out_dst, bs); + } + + cd->buffered_out_frames += bs; + cd->buffered_in_frames -= bs; + + if (cd->buffered_in_frames > 0) { + memmove(cd->in_buf, + &cd->in_buf[bs * cd->in_channels], + (size_t)cd->buffered_in_frames * cd->in_channels * sizeof(float)); + } + } + resonance_audio_backend_exit(mod); + + drain = MIN(n, cd->buffered_out_frames); + if (drain > 0) { + size_t remaining = (size_t)drain; + size_t offset = 0; + void *w_ptr = sink_buf.ptr; + + while (remaining) { + size_t fmax = circ_buf_frames_without_wrap(w_ptr, sink_buf.buf_end, + sample_bytes, + RESONANCE_OUT_CHANNELS); + size_t f = MIN(remaining, fmax); + const float *src_f = &cd->out_fifo[offset * RESONANCE_OUT_CHANNELS]; + + if (fmt == SOF_IPC_FRAME_S32_LE) + float_to_s32_interleaved(w_ptr, src_f, (int)f, + RESONANCE_OUT_CHANNELS); + else + float_to_s16_interleaved(w_ptr, src_f, (int)f, + RESONANCE_OUT_CHANNELS); + + remaining -= f; + offset += f; + w_ptr = cir_buf_wrap((char *)w_ptr + f * out_frame_bytes, + sink_buf.buf_start, sink_buf.buf_end); + } + + cd->buffered_out_frames -= drain; + if (cd->buffered_out_frames > 0) { + memmove(cd->out_fifo, + &cd->out_fifo[drain * RESONANCE_OUT_CHANNELS], + (size_t)cd->buffered_out_frames * RESONANCE_OUT_CHANNELS * + sizeof(float)); + } + } + + if (drain < n) { + size_t remaining = (size_t)(n - drain); + void *w_ptr = (char *)sink_buf.ptr + (size_t)drain * out_frame_bytes; + + w_ptr = cir_buf_wrap(w_ptr, sink_buf.buf_start, sink_buf.buf_end); + while (remaining) { + size_t fmax = circ_buf_frames_without_wrap(w_ptr, sink_buf.buf_end, + sample_bytes, + RESONANCE_OUT_CHANNELS); + size_t f = MIN(remaining, fmax); + + memset(w_ptr, 0, f * out_frame_bytes); + remaining -= f; + w_ptr = cir_buf_wrap((char *)w_ptr + f * out_frame_bytes, + sink_buf.buf_start, sink_buf.buf_end); + } + } + + sink_commit_buffer(snk, out_nbytes); + return 0; +} + +static int resonance_apply_switch_ctl(struct processing_module *mod, + struct resonance_comp_data *cd, + uint32_t id, uint32_t val) +{ + switch (id) { + case RESONANCE_CTL_ID_ENABLE: + cd->enabled = (val != 0); + return 0; + case RESONANCE_CTL_ID_SPEAKER_MODE: + cd->speaker_mode = (val != 0); + cd->speaker_dirty = true; + return 0; + case RESONANCE_CTL_ID_ROOM_ENABLE: + cd->room_enable = (val != 0); + cd->room_dirty = true; + return 0; + default: + comp_err(mod->dev, "resonance_audio: unknown switch ctl %u", id); + return -EINVAL; + } +} + +static int resonance_set_config(struct processing_module *mod, uint32_t param_id, + enum module_cfg_fragment_position pos, + uint32_t data_offset_size, + const uint8_t *fragment, size_t fragment_size, + uint8_t *response, size_t response_size) +{ + struct resonance_comp_data *cd = module_get_private_data(mod); + struct comp_dev *dev = mod->dev; + + (void)data_offset_size; + (void)response; + (void)response_size; + + if (pos != MODULE_CFG_FRAGMENT_SINGLE) { + comp_err(dev, "resonance_audio: fragmented config unsupported"); + return -EINVAL; + } + +#if CONFIG_IPC_MAJOR_4 + if (param_id == SOF_IPC4_SWITCH_CONTROL_PARAM_ID) { + const struct sof_ipc4_control_msg_payload *ctl = + (const struct sof_ipc4_control_msg_payload *)fragment; + + if (fragment_size < sizeof(*ctl) + sizeof(struct sof_ipc4_ctrl_value_chan) || + ctl->num_elems != RESONANCE_CTL_NUM_ELEMS) { + comp_err(dev, "resonance_audio: bad switch payload size %zu", + fragment_size); + return -EINVAL; + } + return resonance_apply_switch_ctl(mod, cd, ctl->id, ctl->chanv[0].value); + } + + if (param_id == SOF_IPC4_BYTES_CONTROL_PARAM_ID) { + const struct sof_ipc4_control_msg_payload *ctl = + (const struct sof_ipc4_control_msg_payload *)fragment; + + if (fragment_size < sizeof(*ctl) || + fragment_size < sizeof(*ctl) + ctl->num_elems) { + comp_err(dev, "resonance_audio: bad bytes payload size %zu", + fragment_size); + return -EINVAL; + } + return resonance_apply_pose_cfg(mod, cd, ctl->data, ctl->num_elems); + } +#endif + + return resonance_apply_pose_cfg(mod, cd, fragment, fragment_size); +} + +static int resonance_get_config(struct processing_module *mod, uint32_t config_id, + uint32_t *data_offset_size, uint8_t *fragment, + size_t fragment_size) +{ + struct resonance_comp_data *cd = module_get_private_data(mod); + +#if CONFIG_IPC_MAJOR_4 + if (config_id == SOF_IPC4_SWITCH_CONTROL_PARAM_ID) { + struct sof_ipc4_control_msg_payload *ctl = + (struct sof_ipc4_control_msg_payload *)fragment; + + if (fragment_size < sizeof(*ctl) + sizeof(struct sof_ipc4_ctrl_value_chan)) + return -EINVAL; + + switch (ctl->id) { + case RESONANCE_CTL_ID_ENABLE: + ctl->chanv[0].value = cd->enabled ? 1 : 0; + break; + case RESONANCE_CTL_ID_SPEAKER_MODE: + ctl->chanv[0].value = cd->speaker_mode ? 1 : 0; + break; + case RESONANCE_CTL_ID_ROOM_ENABLE: + ctl->chanv[0].value = cd->room_enable ? 1 : 0; + break; + default: + return -EINVAL; + } + ctl->num_elems = RESONANCE_CTL_NUM_ELEMS; + ctl->chanv[0].channel = 0; + *data_offset_size = sizeof(*ctl) + sizeof(struct sof_ipc4_ctrl_value_chan); + return 0; + } + + if (config_id == SOF_IPC4_BYTES_CONTROL_PARAM_ID) { + struct sof_ipc4_control_msg_payload *ctl = + (struct sof_ipc4_control_msg_payload *)fragment; + struct sof_resonance_pose_cfg cfg = { + .magic = RESONANCE_POSE_CFG_MAGIC, + .version = RESONANCE_POSE_CFG_VERSION, + .master_volume = cd->master_volume, + .input_mode = cd->mode_override, + .flags = (cd->speaker_mode ? BIT(0) : 0) | + (cd->room_enable ? BIT(1) : 0) | + (cd->enabled ? BIT(2) : 0), + }; + + if (fragment_size < sizeof(*ctl) + sizeof(cfg)) + return -EINVAL; + + memcpy(cfg.head_pos, cd->head_pos, sizeof(cfg.head_pos)); + memcpy(cfg.head_quat, cd->head_quat, sizeof(cfg.head_quat)); + memcpy(ctl->data, &cfg, sizeof(cfg)); + ctl->num_elems = sizeof(cfg); + *data_offset_size = sizeof(*ctl) + sizeof(cfg); + return 0; + } +#endif + + (void)cd; + (void)config_id; + (void)data_offset_size; + (void)fragment; + (void)fragment_size; + return -EINVAL; +} + +static int resonance_bind(struct processing_module *mod, + const struct bind_info *bind_data) +{ + struct resonance_comp_data *cd = module_get_private_data(mod); + + if (cd && bind_data->bind_type == COMP_BIND_TYPE_SOURCE) { +#if CONFIG_IPC_MAJOR_4 + if (bind_data->ipc4_data && + bind_data->ipc4_data->extension.r.dst_queue == 1) + cd->meta_buf_len = 0; +#endif + } + return 0; +} + +static int resonance_unbind(struct processing_module *mod, + const struct bind_info *unbind_data) +{ + struct resonance_comp_data *cd = module_get_private_data(mod); + + if (cd && unbind_data->bind_type == COMP_BIND_TYPE_SOURCE) { +#if CONFIG_IPC_MAJOR_4 + if (unbind_data->ipc4_data && + unbind_data->ipc4_data->extension.r.dst_queue == 1) + cd->meta_buf_len = 0; +#endif + } + return 0; +} + +static int resonance_reset(struct processing_module *mod) +{ + struct resonance_comp_data *cd = module_get_private_data(mod); + int ret = 0; + + comp_dbg(mod->dev, "resonance_audio: reset"); + cd->buffered_in_frames = 0; + cd->meta_buf_len = 0; + memset(cd->out_fifo, 0, + (size_t)cd->block_frames * RESONANCE_OUT_CHANNELS * sizeof(float)); + cd->buffered_out_frames = cd->block_frames; + + if (cd->backend->reset) { + resonance_audio_backend_enter(mod); + ret = cd->backend->reset(mod); + resonance_audio_backend_exit(mod); + } + return ret; +} + +__cold static int resonance_free(struct processing_module *mod) +{ + struct resonance_comp_data *cd = module_get_private_data(mod); + + assert_can_be_cold(); + comp_dbg(mod->dev, "resonance_audio: free"); + + if (cd && cd->backend && cd->backend->free) { + resonance_audio_backend_enter(mod); + cd->backend->free(mod); + resonance_audio_backend_exit(mod); + } + + mod_free(mod, cd); + return 0; +} + +static const struct module_interface resonance_audio_interface = { + .init = resonance_init, + .prepare = resonance_prepare, + .is_ready_to_process = resonance_is_ready_to_process, + .process = resonance_process, + .bind = resonance_bind, + .unbind = resonance_unbind, + .set_configuration = resonance_set_config, + .get_configuration = resonance_get_config, + .reset = resonance_reset, + .free = resonance_free, +}; + +static const uint32_t resonance_audio_codec_info_items[] +#if CONFIG_COMP_RESONANCE_AUDIO_MODULE + __section(SOF_CODEC_INFO_SECTION) __used +#endif + = { + SOF_CODEC_INFO_ITEM(SND_AUDIOCODEC_PCM, SOF_IPC_STREAM_PLAYBACK), + SOF_CODEC_INFO_ITEM(SND_AUDIOCODEC_BESPOKE, SOF_IPC_STREAM_PLAYBACK), +}; + +#if CONFIG_COMP_RESONANCE_AUDIO_MODULE + +#include +#include +#include + +static const struct sof_man_module_manifest mod_manifest __section(".module") __used = + SOF_LLEXT_MODULE_MANIFEST("RESAUD", &resonance_audio_interface, 1, + SOF_REG_UUID(resonance_audio), 40); + +SOF_LLEXT_BUILDINFO; + +#else + +DECLARE_TR_CTX(resonance_audio_tr, SOF_UUID(resonance_audio_uuid), LOG_LEVEL_INFO); +DECLARE_MODULE_ADAPTER(resonance_audio_interface, resonance_audio_uuid, resonance_audio_tr); + +static __maybe_unused void sys_comp_resonance_audio_init(void) +{ + sys_comp_module_resonance_audio_interface_init(); + sof_codec_info_add_items(&resonance_audio_interface, + resonance_audio_codec_info_items, + ARRAY_SIZE(resonance_audio_codec_info_items)); +} + +SOF_MODULE_INIT(resonance_audio, sys_comp_resonance_audio_init); + +#endif diff --git a/src/audio/resonance_audio/resonance_audio.cmake b/src/audio/resonance_audio/resonance_audio.cmake new file mode 100644 index 000000000000..bf1c2d431439 --- /dev/null +++ b/src/audio/resonance_audio/resonance_audio.cmake @@ -0,0 +1,225 @@ +# SPDX-License-Identifier: BSD-3-Clause +# +# Cross-build Google Resonance Audio (1st-order HOA + virtual surround + PFFFT) +# into ${RESONANCE_AUDIO_INSTALL_DIR}/lib/libresonance_audio.a for both built-in +# (=y) and modular LLEXT (=m) SOF targets. + +if(NOT DEFINED SOF_RESONANCE_AUDIO_SRC_DIR) + set(SOF_RESONANCE_AUDIO_SRC_DIR "${sof_top_dir}/../modules/audio/resonance-audio" + CACHE PATH "Google Resonance Audio source directory") +endif() +cmake_path(NORMAL_PATH SOF_RESONANCE_AUDIO_SRC_DIR) + +if(NOT EXISTS "${SOF_RESONANCE_AUDIO_SRC_DIR}/resonance_audio/graph/graph_manager.cc") + message(FATAL_ERROR + "resonance_audio: source not found at '${SOF_RESONANCE_AUDIO_SRC_DIR}'.\n" + "Run 'west update' or pass -DSOF_RESONANCE_AUDIO_SRC_DIR=.") +endif() + +if(NOT EXISTS "${SOF_RESONANCE_AUDIO_SRC_DIR}/third_party/eigen/Eigen/Dense") + message(FATAL_ERROR + "resonance_audio: Eigen not found under '${SOF_RESONANCE_AUDIO_SRC_DIR}/third_party/eigen'.") +endif() + +if(NOT EXISTS "${SOF_RESONANCE_AUDIO_SRC_DIR}/third_party/pffft/pffft.c") + message(FATAL_ERROR + "resonance_audio: PFFFT not found under '${SOF_RESONANCE_AUDIO_SRC_DIR}/third_party/pffft'.") +endif() + +if(NOT DEFINED CMAKE_AR) + set(_res_ar "ar") +else() + set(_res_ar "${CMAKE_AR}") +endif() + +set(RESONANCE_AUDIO_INSTALL_DIR "${CMAKE_CURRENT_BINARY_DIR}/resonance-audio-install" + CACHE INTERNAL "resonance_audio: static library install prefix") + +set(_res_mod_dir "${CMAKE_CURRENT_LIST_DIR}") +set(_res_ra_dir "${SOF_RESONANCE_AUDIO_SRC_DIR}/resonance_audio") +set(_res_eigen_dir "${SOF_RESONANCE_AUDIO_SRC_DIR}/third_party/eigen") +set(_res_pffft_dir "${SOF_RESONANCE_AUDIO_SRC_DIR}/third_party/pffft") + +if("${ARCH}" STREQUAL "xtensa") + if(CONFIG_LLEXT_BUILD_PIC) + set(_res_arch_flags "-fPIC -mlongcalls -mtext-section-literals") + else() + set(_res_arch_flags "-fno-pic -fno-pie -mlongcalls -mtext-section-literals") + endif() +else() + set(_res_arch_flags "-fPIC") +endif() + +set(_res_clang_fp_flags "") +if(CMAKE_C_COMPILER_ID MATCHES "Clang") + set(_res_clang_fp_flags "-Xclang -target-feature -Xclang -fp") +endif() + +# Locate C++ stdlib headers when building on Xtensa without linking libstdc++. +set(_res_cxx_sys_inc "") +if(DEFINED CONFIG_SOC_TOOLCHAIN_NAME) + set(_xtensa_target "${CONFIG_SOC_TOOLCHAIN_NAME}") +else() + set(_xtensa_target "intel_ace30_ptl") +endif() + +if(CMAKE_CXX_COMPILER) + get_filename_component(_cxx_bin_dir "${CMAKE_CXX_COMPILER}" DIRECTORY) + get_filename_component(_cxx_tc_dir "${_cxx_bin_dir}" DIRECTORY) + if(EXISTS "${_cxx_tc_dir}/xtensa-${_xtensa_target}_zephyr-elf/include/c++") + set(_sdk_cxx_dir "${_cxx_tc_dir}/xtensa-${_xtensa_target}_zephyr-elf") + elseif(EXISTS "${_cxx_tc_dir}/include/c++") + set(_sdk_cxx_dir "${_cxx_tc_dir}") + endif() +endif() +if(NOT _sdk_cxx_dir AND DEFINED ENV{ZEPHYR_SDK_INSTALL_DIR}) + set(_sdk_cxx_dir "$ENV{ZEPHYR_SDK_INSTALL_DIR}/gnu/xtensa-${_xtensa_target}_zephyr-elf/xtensa-${_xtensa_target}_zephyr-elf") +endif() +if(_sdk_cxx_dir AND EXISTS "${_sdk_cxx_dir}/include/c++") + file(GLOB _sdk_cxx_ver_dirs LIST_DIRECTORIES true "${_sdk_cxx_dir}/include/c++/*") + if(_sdk_cxx_ver_dirs) + list(GET _sdk_cxx_ver_dirs 0 _sdk_cxx_ver_dir) + set(_res_cxx_sys_inc "-isystem ${_sdk_cxx_ver_dir} -isystem ${_sdk_cxx_ver_dir}/xtensa-${_xtensa_target}_zephyr-elf -isystem ${_sdk_cxx_dir}/include") + endif() +endif() + +set(_res_sysroot_inc "") +if(CMAKE_SYSROOT) + set(_res_sysroot_inc "--sysroot=${CMAKE_SYSROOT}") +endif() + +set(_res_pffft_srcs + "${_res_pffft_dir}/pffft.c" + "${_res_pffft_dir}/fftpack.c" +) + +set(_res_cxx_srcs + "${_res_mod_dir}/resonance_wrapper.cpp" + "${_res_mod_dir}/resonance_shims.cpp" + "${_res_mod_dir}/resonance_hrtf_assets.cc" + "${SOF_RESONANCE_AUDIO_SRC_DIR}/platforms/common/room_effects_utils.cc" + "${_res_ra_dir}/ambisonics/ambisonic_binaural_decoder.cc" + "${_res_mod_dir}/overrides/ambisonics/ambisonic_lookup_table.cc" + "${_res_ra_dir}/ambisonics/associated_legendre_polynomials_generator.cc" + "${_res_ra_dir}/ambisonics/foa_rotator.cc" + "${_res_ra_dir}/ambisonics/hoa_rotator.cc" + "${_res_ra_dir}/ambisonics/stereo_from_soundfield_converter.cc" + "${_res_ra_dir}/base/audio_buffer.cc" + "${_res_ra_dir}/base/channel_view.cc" + "${_res_ra_dir}/base/misc_math.cc" + "${_res_ra_dir}/base/simd_utils.cc" + "${_res_ra_dir}/base/spherical_angle.cc" + "${_res_ra_dir}/config/source_config.cc" + "${_res_ra_dir}/dsp/biquad_filter.cc" + "${_res_ra_dir}/dsp/channel_converter.cc" + "${_res_ra_dir}/dsp/circular_buffer.cc" + "${_res_ra_dir}/dsp/delay_filter.cc" + "${_res_ra_dir}/dsp/distance_attenuation.cc" + "${_res_ra_dir}/dsp/fft_manager.cc" + "${_res_ra_dir}/dsp/filter_coefficient_generators.cc" + "${_res_ra_dir}/dsp/fir_filter.cc" + "${_res_ra_dir}/dsp/gain.cc" + "${_res_ra_dir}/dsp/gain_mixer.cc" + "${_res_ra_dir}/dsp/gain_processor.cc" + "${_res_ra_dir}/dsp/mixer.cc" + "${_res_ra_dir}/dsp/mono_pole_filter.cc" + "${_res_ra_dir}/dsp/multi_channel_iir.cc" + "${_res_ra_dir}/dsp/near_field_processor.cc" + "${_res_ra_dir}/dsp/occlusion_calculator.cc" + "${_res_ra_dir}/dsp/partitioned_fft_filter.cc" + "${_res_ra_dir}/dsp/resampler.cc" + "${_res_ra_dir}/dsp/shoe_box_room.cc" + "${_res_ra_dir}/dsp/stereo_panner.cc" + "${_res_ra_dir}/dsp/utils.cc" + "${_res_ra_dir}/graph/ambisonic_binaural_decoder_node.cc" + "${_res_ra_dir}/graph/ambisonic_mixing_encoder_node.cc" + "${_res_ra_dir}/graph/buffered_source_node.cc" + "${_res_ra_dir}/graph/foa_rotator_node.cc" + "${_res_ra_dir}/graph/gain_mixer_node.cc" + "${_res_ra_dir}/graph/gain_node.cc" + "${_res_ra_dir}/graph/graph_manager.cc" + "${_res_ra_dir}/graph/hoa_rotator_node.cc" + "${_res_ra_dir}/graph/mixer_node.cc" + "${_res_ra_dir}/graph/mono_from_soundfield_node.cc" + "${_res_ra_dir}/graph/near_field_effect_node.cc" + "${_res_ra_dir}/graph/occlusion_node.cc" + "${_res_ra_dir}/graph/source_parameters_manager.cc" + "${_res_ra_dir}/graph/stereo_mixing_panner_node.cc" + "${_res_ra_dir}/node/processing_node.cc" + "${_res_ra_dir}/node/sink_node.cc" + "${_res_ra_dir}/node/source_node.cc" + "${_res_ra_dir}/utils/buffer_crossfader.cc" + "${_res_ra_dir}/utils/planar_interleaved_conversion.cc" + "${_res_ra_dir}/utils/sample_type_conversion.cc" + "${_res_ra_dir}/utils/sum_and_difference_processor.cc" +) +set(_res_room_reverb_def "") +if(CONFIG_RESONANCE_AUDIO_ROOM_REVERB) + set(_res_room_reverb_def "-DCONFIG_RESONANCE_AUDIO_ROOM_REVERB=1") + list(APPEND _res_cxx_srcs + "${_res_ra_dir}/dsp/reflections_processor.cc" + "${_res_ra_dir}/dsp/reverb_onset_compensator.cc" + "${_res_ra_dir}/dsp/reverb_onset_update_processor.cc" + "${_res_ra_dir}/dsp/spectral_reverb.cc" + "${_res_ra_dir}/graph/reflections_node.cc" + "${_res_ra_dir}/graph/reverb_node.cc" + ) +endif() + +string(JOIN " " _res_pffft_srcs_str ${_res_pffft_srcs}) +string(JOIN " " _res_cxx_srcs_str ${_res_cxx_srcs}) + +set(_res_cxx_compiler "${CMAKE_CXX_COMPILER}") +if(NOT _res_cxx_compiler) + set(_res_cxx_compiler "${CMAKE_C_COMPILER}") +endif() + +file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/resonance-audio-build.sh.tmp" +"#!/bin/sh +set -e +INST=\"${RESONANCE_AUDIO_INSTALL_DIR}\" +OBJ=\"${CMAKE_CURRENT_BINARY_DIR}/resonance-audio-obj\" + +rm -rf \"\$OBJ\" \"\$INST/lib/libresonance_audio_dsp.a\" +mkdir -p \"\$OBJ\" \"\$INST/lib\" \"\$INST/include\" + +COMMON_FLAGS=\"-O3 ${_res_arch_flags} ${_res_clang_fp_flags} ${_res_sysroot_inc} -DNDEBUG -D_GNU_SOURCE -DM_PI=3.14159265358979323846 -DPFFFT_SIMD_DISABLE -DDISABLE_SIMD -DEIGEN_MPL2_ONLY -DEIGEN_NO_DEBUG -DEIGEN_DONT_VECTORIZE\" +INCS=\"-I${_res_mod_dir}/overrides -I${_res_mod_dir} -I${SOF_RESONANCE_AUDIO_SRC_DIR} -I${_res_ra_dir} -I${_res_eigen_dir} -I${_res_pffft_dir}\" +CFLAGS=\"\$COMMON_FLAGS \$INCS -Dmalloc=res_shim_malloc -Dcalloc=res_shim_calloc -Drealloc=res_shim_realloc -Dfree=res_shim_free -Wno-unused-function -Wno-double-promotion\" +CXXFLAGS=\"-std=c++17 -fno-exceptions -fno-rtti -fno-threadsafe-statics -include ${_res_mod_dir}/resonance_preinc.h ${_res_room_reverb_def} \$COMMON_FLAGS ${_res_cxx_sys_inc} \$INCS -Wno-unused-function -Wno-double-promotion -Wno-deprecated-declarations -Wno-sign-compare\" + +idx=0 +for f in ${_res_pffft_srcs_str}; do + bn=\$(basename \"\$f\" .c) + ${CMAKE_C_COMPILER} \$CFLAGS -c \"\$f\" -o \"\$OBJ/\${idx}_\${bn}.o\" + idx=\$((idx + 1)) +done + +for f in ${_res_cxx_srcs_str}; do + bn=\$(basename \"\$f\") + ${_res_cxx_compiler} \$CXXFLAGS -c \"\$f\" -o \"\$OBJ/\${idx}_\${bn}.o\" + idx=\$((idx + 1)) +done + +LIBSTDCXX_A=\$(${_res_cxx_compiler} -print-file-name=libstdc++.a 2>/dev/null || true) +if [ -n \"\$LIBSTDCXX_A\" ] && [ -f \"\$LIBSTDCXX_A\" ]; then + (cd \"\$OBJ\" && ${_res_ar} x \"\$LIBSTDCXX_A\" list.o tree.o 2>/dev/null || true) +fi + +${_res_ar} rcs \"\$INST/lib/libresonance_audio_dsp.a\" \"\$OBJ\"/*.o +cp \"${_res_mod_dir}/resonance_wrapper.h\" \"\$INST/include/\" +") + +configure_file("${CMAKE_CURRENT_BINARY_DIR}/resonance-audio-build.sh.tmp" + "${CMAKE_CURRENT_BINARY_DIR}/resonance-audio-build.sh" COPYONLY) + +add_custom_command( + OUTPUT "${RESONANCE_AUDIO_INSTALL_DIR}/lib/libresonance_audio_dsp.a" + COMMAND sh "${CMAKE_CURRENT_BINARY_DIR}/resonance-audio-build.sh" + DEPENDS "${CMAKE_CURRENT_BINARY_DIR}/resonance-audio-build.sh" + ${_res_pffft_srcs} + ${_res_cxx_srcs} + VERBATIM) + +add_custom_target(resonance_audio_ext + DEPENDS "${RESONANCE_AUDIO_INSTALL_DIR}/lib/libresonance_audio_dsp.a") diff --git a/src/audio/resonance_audio/resonance_audio.h b/src/audio/resonance_audio/resonance_audio.h new file mode 100644 index 000000000000..d564916228c5 --- /dev/null +++ b/src/audio/resonance_audio/resonance_audio.h @@ -0,0 +1,138 @@ +/* SPDX-License-Identifier: BSD-3-Clause + * + * Google Resonance Audio spatializer module for SOF (IPC4). + * + * Phase 1: Virtual surround (Mono, Stereo, 5.1, 7.1) and 1st-order HOA + * (4-ch AmbiX) to 2-channel binaural stereo output, controlled via + * ALSA switch and bytes kcontrols (IPC4 LARGE_CONFIG_SET). + */ +#ifndef __SOF_AUDIO_RESONANCE_AUDIO_H__ +#define __SOF_AUDIO_RESONANCE_AUDIO_H__ + +#include +#include +#include + +#define RESONANCE_CHANNELS_MAX 8 +#define RESONANCE_OUT_CHANNELS 2 +#define RESONANCE_BLOCK_FRAMES_48K 48 +#define RESONANCE_BLOCK_FRAMES_DEFAULT 64 +#define RESONANCE_FIFO_FRAMES (512) + +/* IPC4 switch control IDs matching resonance-audio.conf mixer controls. */ +#define RESONANCE_CTL_ID_ENABLE 0 +#define RESONANCE_CTL_ID_SPEAKER_MODE 1 +#define RESONANCE_CTL_ID_ROOM_ENABLE 2 +#define RESONANCE_CTL_NUM_ELEMS 1 + +/* IPC4 bytes control ID / config magic ("RESN"). */ +#define RESONANCE_POSE_CFG_MAGIC 0x4E534552U +#define RESONANCE_POSE_CFG_VERSION 1U +#define RESONANCE_DMA_PACKET_BYTES 128U +#define RESONANCE_INPUT_MODE_MAX 4U +#define RESONANCE_INPUT_MODE_AUTO 0xFFU + +/** + * struct sof_resonance_pose_cfg - Runtime spatial pose & mode configuration + * sent via SOF_IPC4_BYTES_CONTROL_PARAM_ID kcontrol. + */ +struct sof_resonance_pose_cfg { + uint32_t magic; + uint32_t version; + float head_pos[3]; /* x, y, z (meters) */ + float head_quat[4]; /* x, y, z, w */ + float master_volume; /* linear gain, <=0 keeps current */ + uint32_t input_mode; /* enum resonance_input_mode or 0xff = auto from channels */ + uint32_t flags; /* bit0: speaker_mode, bit1: room_reverb, bit2: enabled */ +} __packed; + +/** + * struct sof_resonance_pose_dma_frame - Fixed 128-byte spatial metadata packet + * streamed via compressed mmap DMA ring into Pin 1 of resonance_audio. + */ +struct sof_resonance_pose_dma_frame { + struct sof_resonance_pose_cfg cfg; /* 48B @ 0 */ + uint32_t seq; /* non-zero monotonic sequence number @ 48 */ + uint32_t reserved0; /* reserved (0) @ 52 */ + uint64_t timestamp_us; /* monotonic host timestamp (us) @ 56 */ + uint32_t checksum; /* FNV-1a over [0..63] or 0 to skip @ 64 */ + uint8_t reserved[60]; /* zero-padded to 128B HDA burst @ 68..127 */ +} __packed; + +static inline uint32_t resonance_pose_dma_checksum(const struct sof_resonance_pose_dma_frame *f) +{ + const uint8_t *p = (const uint8_t *)f; + uint32_t h = 2166136261U; + size_t i; + + for (i = 0; i < 64; i++) { + h ^= p[i]; + h *= 16777619U; + } + return h ? h : 1U; +} + +struct resonance_backend { + const char *name; + int (*init)(struct processing_module *mod); + int (*configure)(struct processing_module *mod, int sample_rate_hz, + int block_frames, int in_channels, uint32_t mode_override, + bool speaker_mode, bool room_enable, float master_volume); + int (*process)(struct processing_module *mod, const float *in_interleaved, + int in_channels, float *out_interleaved, int num_frames); + void (*set_pose)(struct processing_module *mod, const float pos[3], + const float quat[4]); + void (*set_speaker_mode)(struct processing_module *mod, bool enabled); + void (*set_room_enable)(struct processing_module *mod, bool enabled); + void (*set_volume)(struct processing_module *mod, float volume); + int (*reset)(struct processing_module *mod); + void (*free)(struct processing_module *mod); +}; + +struct resonance_comp_data { + const struct resonance_backend *backend; + void *backend_ctx; + + int sample_rate; + int in_channels; + int out_channels; + int block_frames; + + bool configured; + bool enabled; + bool speaker_mode; + bool room_enable; + bool pose_dirty; + bool speaker_dirty; + bool room_dirty; + bool volume_dirty; + bool in_identity_map; + + uint32_t mode_override; + uint8_t in_perm[RESONANCE_CHANNELS_MAX]; + float head_pos[3]; + float head_quat[4]; + float master_volume; + + int buffered_in_frames; + int buffered_out_frames; + float in_buf[RESONANCE_FIFO_FRAMES * RESONANCE_CHANNELS_MAX]; + float out_fifo[RESONANCE_FIFO_FRAMES * RESONANCE_OUT_CHANNELS]; + float tmp_out[RESONANCE_FIFO_FRAMES * RESONANCE_OUT_CHANNELS]; + + /* Phase 2: Pin 1 compressed mmap DMA metadata tracking & framing buffer */ + uint32_t dma_last_seq; + uint64_t dma_pkt_count; + uint64_t dma_last_ts_us; + size_t meta_buf_len; + uint8_t meta_buf[RESONANCE_DMA_PACKET_BYTES]; +}; + +extern const struct resonance_backend resonance_backend; + +void resonance_audio_set_active_mod(struct processing_module *mod); +struct processing_module *resonance_audio_get_active_mod(void); +void resonance_audio_backend_enter(struct processing_module *mod); +void resonance_audio_backend_exit(struct processing_module *mod); + +#endif /* __SOF_AUDIO_RESONANCE_AUDIO_H__ */ diff --git a/src/audio/resonance_audio/resonance_audio.toml b/src/audio/resonance_audio/resonance_audio.toml new file mode 100644 index 000000000000..6ee549cc1506 --- /dev/null +++ b/src/audio/resonance_audio/resonance_audio.toml @@ -0,0 +1,24 @@ +#ifndef LOAD_TYPE +#define LOAD_TYPE "0" +#endif + + REM # Google Resonance Audio spatializer module config. + REM # Pin 0: multi-ch audio input (1/2/4/6/8 ch), Pin 1: optional DMA spatial metadata. + REM # Output pin 0: stereo binaural output. + [[module.entry]] + name = "RESAUD" + uuid = UUIDREG_STR_RESONANCE_AUDIO + affinity_mask = "0x1" + instance_count = "8" + domain_types = "1" + load_type = LOAD_TYPE + module_type = "9" + init_config = "1" + auto_start = "0" + sched_caps = [1, 0x00008000] + REM # pin = [dir, type, sample rate, size, container, channel-cfg] + pin = [0, 0, 0xfeef, 0xf, 0xf, 0x45ff, 0, 0, 0xfeef, 0xf, 0xf, 0x45ff, 1, 0, 0xfeef, 0xf, 0xf, 0x45ff] + REM # mod_cfg [PAR_0 PAR_1 PAR_2 PAR_3 IS_BYTES CPS IBS OBS MOD_FLAGS CPC OBLS] + mod_cfg = [0, 0, 0, 0, 0, 2000000, 16384, 4096, 0, 4000, 0] + + index = __COUNTER__ diff --git a/src/audio/resonance_audio/resonance_hrtf_assets.cc b/src/audio/resonance_audio/resonance_hrtf_assets.cc new file mode 100644 index 000000000000..af2b69891695 --- /dev/null +++ b/src/audio/resonance_audio/resonance_hrtf_assets.cc @@ -0,0 +1,257 @@ +/* SPDX-License-Identifier: BSD-3-Clause + * + * Embedded 1st-order SADIE SH-HRIR asset loader for Resonance Audio on SOF DSP. + * Replaces upstream wav.cc / wav_reader.cc / hrtf_assets.cc to eliminate + * , , and static std::unordered_map constructors. + * + * Embedded HRIR WAV data is from third_party/SADIE_hrtf_database (Apache-2.0). + */ +#include "dsp/sh_hrir_creator.h" + +#include +#include + +#include "ambisonics/utils.h" +#include "base/logging.h" +#include "dsp/resampler.h" +#include "utils/planar_interleaved_conversion.h" + +namespace vraudio { +namespace { + +/* SADIE Subject_002 1st-order spherical harmonic HRIR (48 kHz, 4 ch, 16-bit PCM, 2092 bytes). */ +alignas(4) static const uint8_t kShHrirOrder1Wav[] = { + 0x52, 0x49, 0x46, 0x46, 0x24, 0x08, 0x00, 0x00, 0x57, 0x41, 0x56, 0x45, + 0x66, 0x6d, 0x74, 0x20, 0x10, 0x00, 0x00, 0x00, 0x01, 0x00, 0x04, 0x00, + 0x80, 0xbb, 0x00, 0x00, 0x00, 0xdc, 0x05, 0x00, 0x08, 0x00, 0x10, 0x00, + 0x64, 0x61, 0x74, 0x61, 0x00, 0x08, 0x00, 0x00, + 0xfe, 0xff, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf6, 0xff, 0x10, 0x00, + 0xfd, 0xff, 0x02, 0x00, 0xfb, 0xff, 0x0b, 0x00, 0xff, 0xff, 0x01, 0x00, + 0xfe, 0xff, 0x07, 0x00, 0xff, 0xff, 0x01, 0x00, 0xfe, 0xff, 0x0c, 0x00, + 0xff, 0xff, 0x01, 0x00, 0xff, 0xff, 0x01, 0x00, 0xfd, 0xff, 0x00, 0x00, + 0xfb, 0xff, 0x01, 0x00, 0x02, 0x00, 0xfe, 0xff, 0x08, 0x00, 0x04, 0x00, + 0xf9, 0xff, 0x00, 0x00, 0xf8, 0xff, 0xfa, 0xff, 0x02, 0x00, 0xfc, 0xff, + 0x18, 0x00, 0x10, 0x00, 0x05, 0x00, 0x04, 0x00, 0xee, 0xff, 0xe7, 0xff, + 0xf3, 0xff, 0x00, 0x00, 0xfb, 0xff, 0xf4, 0xff, 0x1a, 0x00, 0xf9, 0xff, + 0xcc, 0xff, 0xc0, 0xff, 0xd5, 0xff, 0x04, 0x00, 0xfd, 0xfd, 0xf8, 0xfd, + 0x1d, 0x00, 0xce, 0xff, 0x1d, 0xfc, 0x12, 0xfc, 0x1a, 0x00, 0x41, 0x00, + 0xf1, 0x01, 0xf1, 0x01, 0x4e, 0xfe, 0x87, 0x00, 0xb4, 0x0d, 0xa5, 0x0d, + 0xd0, 0xfc, 0x75, 0xfe, 0x37, 0x01, 0x25, 0x01, 0xe7, 0x07, 0x5b, 0xfe, + 0x49, 0xf5, 0x3e, 0xf5, 0x14, 0x0a, 0x6f, 0x07, 0x14, 0xfd, 0x03, 0xfd, + 0x2c, 0xee, 0xa4, 0x02, 0xc0, 0xf5, 0xb5, 0xf5, 0x3b, 0xfc, 0xfd, 0xf0, + 0x68, 0xfd, 0x6b, 0xfd, 0x91, 0x0d, 0xd0, 0x00, 0xb8, 0xf4, 0xce, 0xf4, + 0x61, 0xf3, 0xe2, 0x04, 0xf3, 0xe6, 0x3a, 0xe7, 0x88, 0x05, 0x5e, 0xf7, + 0xdc, 0xfd, 0x4f, 0xfe, 0x94, 0x08, 0xcd, 0x06, 0x6a, 0x02, 0xf7, 0x02, + 0x06, 0xf8, 0x7a, 0xfe, 0x2b, 0x1c, 0xfd, 0x1c, 0x7c, 0xfb, 0xad, 0xfd, + 0x6e, 0x18, 0xa1, 0x19, 0x09, 0xfd, 0x07, 0x10, 0x06, 0xfd, 0xe3, 0xfe, + 0x49, 0x15, 0x5d, 0x06, 0x26, 0x0c, 0xcd, 0x0d, 0x0a, 0x01, 0x4a, 0x01, + 0xa0, 0x03, 0x3b, 0x04, 0x51, 0xeb, 0x6a, 0xfd, 0x41, 0x05, 0x00, 0x06, + 0x34, 0xff, 0x26, 0xf8, 0x24, 0x05, 0xac, 0x04, 0xba, 0x04, 0x02, 0xfa, + 0xb3, 0x03, 0x97, 0x01, 0xe2, 0x05, 0x50, 0x00, 0xd9, 0x09, 0xb2, 0x0b, + 0x88, 0x03, 0xe6, 0x00, 0x2d, 0x00, 0xb6, 0x04, 0x11, 0x06, 0x31, 0xfd, + 0x78, 0x01, 0xe6, 0x06, 0xa5, 0xf9, 0x2c, 0x01, 0xb5, 0xf8, 0x00, 0x03, + 0x8e, 0xf6, 0xba, 0xfc, 0x68, 0xf9, 0x39, 0x01, 0x6e, 0x00, 0xff, 0xff, + 0xcf, 0xfa, 0xc7, 0x00, 0x0f, 0xfc, 0x26, 0x03, 0xac, 0xfb, 0x0c, 0x04, + 0x32, 0x05, 0xe6, 0xfd, 0x98, 0x04, 0x82, 0x02, 0x1d, 0x02, 0x28, 0x01, + 0x04, 0x06, 0xdc, 0xfa, 0x3a, 0xfd, 0xf7, 0x01, 0xf9, 0x05, 0x6a, 0xfe, + 0x07, 0x00, 0x2d, 0x00, 0x98, 0xff, 0x68, 0xf8, 0xd0, 0xfe, 0x91, 0x00, + 0x3c, 0x04, 0xf3, 0xf7, 0x34, 0x03, 0x95, 0x03, 0x81, 0x01, 0x22, 0xfa, + 0x87, 0x01, 0x6c, 0xff, 0x31, 0x00, 0xa1, 0xfd, 0xc2, 0x01, 0xf1, 0xfc, + 0x1f, 0x03, 0x5b, 0xfd, 0x9d, 0x00, 0x43, 0xff, 0xfb, 0xfe, 0xd2, 0xfb, + 0x03, 0xff, 0x2f, 0xfd, 0xc2, 0x01, 0x8e, 0xfc, 0xee, 0xff, 0x98, 0xff, + 0x1d, 0xff, 0x10, 0xf8, 0x23, 0xff, 0x66, 0x01, 0x20, 0x00, 0xcb, 0xfc, + 0x23, 0x01, 0x37, 0x02, 0xf7, 0xfd, 0xce, 0xfb, 0xfd, 0x00, 0x62, 0xff, + 0x3e, 0xfe, 0x5d, 0xfe, 0xae, 0x00, 0xe0, 0xfc, 0xc2, 0x00, 0x7b, 0xff, + 0x96, 0x00, 0x20, 0xff, 0xe2, 0xfe, 0xed, 0xfc, 0x0c, 0x00, 0x21, 0xff, + 0xc5, 0x00, 0x31, 0xfd, 0xcb, 0xfe, 0x7d, 0x00, 0x91, 0xfe, 0x80, 0xfa, + 0x7b, 0xff, 0xce, 0x00, 0x7d, 0xfe, 0x0c, 0xfe, 0x93, 0x01, 0xdc, 0xff, + 0xbe, 0xfd, 0x33, 0xfd, 0xd7, 0x00, 0x5f, 0xff, 0xc4, 0xfe, 0xbc, 0xfe, + 0x5f, 0x00, 0x8c, 0xff, 0x99, 0xfe, 0xc3, 0xfd, 0x4f, 0x00, 0x07, 0xff, + 0xba, 0xfe, 0x2d, 0xfd, 0x0d, 0x00, 0x47, 0xff, 0x62, 0x00, 0x34, 0xfe, + 0xad, 0xfe, 0x23, 0x01, 0xee, 0xfd, 0xd0, 0xfb, 0x3d, 0xff, 0x96, 0x00, + 0x7d, 0xfe, 0x40, 0xfe, 0x09, 0x00, 0xfe, 0x00, 0xee, 0xfd, 0x6c, 0xfd, + 0x1e, 0x00, 0xe9, 0x00, 0x66, 0xfe, 0xf1, 0xfe, 0xef, 0x00, 0x51, 0xff, + 0x02, 0xff, 0x53, 0xfe, 0x4b, 0xff, 0x4e, 0xff, 0xa5, 0xff, 0xf1, 0xfd, + 0x41, 0xff, 0x0a, 0x00, 0xc4, 0xfe, 0xeb, 0xfd, 0xe0, 0xff, 0xc7, 0xff, + 0xe9, 0xfd, 0x7c, 0xfd, 0x83, 0xff, 0x7b, 0x00, 0x7d, 0xfe, 0x45, 0xff, + 0x4d, 0x00, 0x83, 0x00, 0x47, 0xfd, 0x1b, 0xfe, 0xca, 0x00, 0xd1, 0xfe, + 0x2b, 0xff, 0xab, 0xff, 0xfd, 0xff, 0xe2, 0xff, 0xe0, 0xfe, 0x4b, 0xfe, + 0x11, 0x00, 0xed, 0xff, 0xc2, 0xfe, 0x7d, 0xfe, 0xb1, 0x00, 0xaa, 0xff, + 0xdc, 0xfe, 0x98, 0xfe, 0x92, 0xff, 0xb2, 0x00, 0x3a, 0xfe, 0xd7, 0xfd, + 0xba, 0xff, 0xe8, 0xff, 0x44, 0xfe, 0xf4, 0xfe, 0x08, 0x00, 0x73, 0xff, + 0x46, 0xfe, 0x8c, 0xfe, 0xd7, 0xff, 0xf1, 0xff, 0xea, 0xfe, 0x80, 0xff, + 0x4b, 0x00, 0xa6, 0xff, 0x60, 0xfe, 0xf7, 0xfe, 0xed, 0xff, 0x61, 0xff, + 0x8f, 0xff, 0xca, 0xff, 0xc1, 0xff, 0x2a, 0x00, 0x6c, 0xfe, 0xe6, 0xfe, + 0x00, 0x00, 0xc8, 0xff, 0x28, 0xfe, 0x0b, 0xff, 0xb5, 0xff, 0x03, 0x00, + 0xde, 0xfe, 0xd8, 0xff, 0x60, 0xff, 0x91, 0x00, 0x19, 0xfe, 0x1e, 0xff, + 0x4e, 0x00, 0x97, 0xff, 0xdb, 0xfe, 0x17, 0x00, 0x16, 0x00, 0xfc, 0xff, + 0xcf, 0xfe, 0x5c, 0xff, 0xaa, 0xff, 0x4d, 0x00, 0xb0, 0xfe, 0xc5, 0xff, + 0x54, 0x00, 0x98, 0xff, 0x61, 0xfe, 0xae, 0xff, 0xab, 0xff, 0x04, 0x00, + 0xc6, 0xfe, 0xce, 0xff, 0xc3, 0xff, 0x3c, 0x00, 0x1d, 0xfe, 0xf2, 0xff, + 0x2d, 0x00, 0x8d, 0xff, 0x83, 0xfe, 0x34, 0x00, 0xcc, 0xff, 0x29, 0x00, + 0xfd, 0xfe, 0x4d, 0x00, 0xee, 0xff, 0x28, 0x00, 0x2b, 0xfe, 0xb0, 0xff, + 0x12, 0x00, 0x99, 0xff, 0x33, 0xff, 0x84, 0x00, 0xa7, 0xff, 0x55, 0x00, + 0xa1, 0xfe, 0xc5, 0xff, 0xc2, 0xff, 0xf4, 0xff, 0x81, 0xfe, 0x38, 0x00, + 0x29, 0x00, 0xac, 0xff, 0xe3, 0xfe, 0x76, 0x00, 0xb3, 0xff, 0x52, 0x00, + 0xa6, 0xfe, 0x25, 0x00, 0x1f, 0x00, 0xee, 0xff, 0x93, 0xfe, 0x6a, 0x00, + 0x36, 0x00, 0xbc, 0xff, 0xe0, 0xfe, 0x3f, 0x00, 0x9e, 0xff, 0x6b, 0x00, + 0xbe, 0xfe, 0x31, 0x00, 0x19, 0x00, 0xf3, 0xff, 0x58, 0xfe, 0x02, 0x00, + 0xf8, 0xff, 0xd5, 0xff, 0x0a, 0xff, 0x6d, 0x00, 0xcc, 0xff, 0x6d, 0x00, + 0x70, 0xfe, 0xfb, 0xff, 0x41, 0x00, 0xbf, 0xff, 0xcd, 0xfe, 0x62, 0x00, + 0x0e, 0x00, 0xf4, 0xff, 0x20, 0xff, 0x3a, 0x00, 0xe4, 0xff, 0x4c, 0x00, + 0x92, 0xfe, 0xe0, 0xff, 0x41, 0x00, 0xcc, 0xff, 0x0a, 0xff, 0x68, 0x00, + 0x0b, 0x00, 0x31, 0x00, 0x06, 0xff, 0x0a, 0x00, 0xfc, 0xff, 0x49, 0x00, + 0xca, 0xfe, 0x4c, 0x00, 0x6a, 0x00, 0xb9, 0xff, 0xff, 0xfe, 0x6d, 0x00, + 0x06, 0x00, 0x0b, 0x00, 0x21, 0xff, 0x4e, 0x00, 0xfc, 0xff, 0x10, 0x00, + 0xa0, 0xfe, 0x1e, 0x00, 0x3b, 0x00, 0x8c, 0xff, 0x1c, 0xff, 0x5a, 0x00, + 0xdf, 0xff, 0x22, 0x00, 0x13, 0xff, 0x24, 0x00, 0x05, 0x00, 0xff, 0xff, + 0xcf, 0xfe, 0x11, 0x00, 0x24, 0x00, 0xb7, 0xff, 0x62, 0xff, 0x60, 0x00, + 0xcb, 0xff, 0x55, 0x00, 0x08, 0xff, 0xdd, 0xff, 0x14, 0x00, 0xfa, 0xff, + 0x26, 0xff, 0x2b, 0x00, 0x35, 0x00, 0xe8, 0xff, 0x62, 0xff, 0x20, 0x00, + 0xd0, 0xff, 0x5c, 0x00, 0x25, 0xff, 0xf3, 0xff, 0x1e, 0x00, 0xf9, 0xff, + 0x24, 0xff, 0x2b, 0x00, 0x16, 0x00, 0xea, 0xff, 0x5e, 0xff, 0x1b, 0x00, + 0xbe, 0xff, 0x37, 0x00, 0x11, 0xff, 0xfe, 0xff, 0x18, 0x00, 0xc3, 0xff, + 0x23, 0xff, 0x28, 0x00, 0x09, 0x00, 0xe8, 0xff, 0x6b, 0xff, 0x2a, 0x00, + 0xe1, 0xff, 0x27, 0x00, 0x00, 0xff, 0xf5, 0xff, 0x22, 0x00, 0xb1, 0xff, + 0x60, 0xff, 0x56, 0x00, 0xf2, 0xff, 0x0e, 0x00, 0x59, 0xff, 0x09, 0x00, + 0xde, 0xff, 0x20, 0x00, 0x21, 0xff, 0x02, 0x00, 0x24, 0x00, 0xc4, 0xff, + 0x76, 0xff, 0x3e, 0x00, 0xe7, 0xff, 0x27, 0x00, 0x5c, 0xff, 0xf0, 0xff, + 0xec, 0xff, 0x16, 0x00, 0x3d, 0xff, 0x16, 0x00, 0x2d, 0x00, 0xc9, 0xff, + 0x76, 0xff, 0x29, 0x00, 0xd4, 0xff, 0x27, 0x00, 0x5f, 0xff, 0xfd, 0xff, + 0xf6, 0xff, 0xfb, 0xff, 0x3f, 0xff, 0x13, 0x00, 0x25, 0x00, 0xd0, 0xff, + 0x95, 0xff, 0x35, 0x00, 0xcf, 0xff, 0x35, 0x00, 0x4b, 0xff, 0xe7, 0xff, + 0x04, 0x00, 0xdc, 0xff, 0x54, 0xff, 0x18, 0x00, 0x15, 0x00, 0xe4, 0xff, + 0x8a, 0xff, 0x1e, 0x00, 0xc9, 0xff, 0x37, 0x00, 0x4e, 0xff, 0xf4, 0xff, + 0x0b, 0x00, 0xd2, 0xff, 0x83, 0xff, 0x41, 0x00, 0x15, 0x00, 0xf4, 0xff, + 0x78, 0xff, 0xfb, 0xff, 0xe6, 0xff, 0x30, 0x00, 0x58, 0xff, 0xf6, 0xff, + 0x09, 0x00, 0xd7, 0xff, 0x75, 0xff, 0x1c, 0x00, 0xed, 0xff, 0xf6, 0xff, + 0x7c, 0xff, 0xf3, 0xff, 0xf6, 0xff, 0x24, 0x00, 0x57, 0xff, 0xf7, 0xff, + 0x0a, 0x00, 0xd9, 0xff, 0x67, 0xff, 0x01, 0x00, 0xe3, 0xff, 0x03, 0x00, + 0x61, 0xff, 0xdb, 0xff, 0x0a, 0x00, 0x16, 0x00, 0x4d, 0xff, 0xf1, 0xff, + 0xff, 0xff, 0xdb, 0xff, 0x93, 0xff, 0x23, 0x00, 0xd8, 0xff, 0x11, 0x00, + 0x88, 0xff, 0x03, 0x00, 0x0b, 0x00, 0x19, 0x00, 0x7f, 0xff, 0x21, 0x00, + 0x0e, 0x00, 0xfa, 0xff, 0xa3, 0xff, 0x24, 0x00, 0xee, 0xff, 0x1b, 0x00, + 0x99, 0xff, 0x15, 0x00, 0xf8, 0xff, 0x0e, 0x00, 0x8a, 0xff, 0x27, 0x00, + 0xf0, 0xff, 0xf0, 0xff, 0xaf, 0xff, 0x1e, 0x00, 0xf8, 0xff, 0x12, 0x00, + 0xab, 0xff, 0x23, 0x00, 0x04, 0x00, 0x05, 0x00, 0x9b, 0xff, 0x2e, 0x00, + 0xf5, 0xff, 0xf5, 0xff, 0xcc, 0xff, 0x38, 0x00, 0x04, 0x00, 0x1a, 0x00, + 0xa2, 0xff, 0x24, 0x00, 0xf8, 0xff, 0x00, 0x00, 0xa9, 0xff, 0x3b, 0x00, + 0xe7, 0xff, 0xff, 0xff, 0xc4, 0xff, 0x33, 0x00, 0x00, 0x00, 0x19, 0x00, + 0x98, 0xff, 0x25, 0x00, 0xf5, 0xff, 0xff, 0xff, 0xb4, 0xff, 0x45, 0x00, + 0xed, 0xff, 0x05, 0x00, 0xc1, 0xff, 0x2a, 0x00, 0x05, 0x00, 0x15, 0x00, + 0xae, 0xff, 0x27, 0x00, 0xef, 0xff, 0x00, 0x00, 0xc8, 0xff, 0x39, 0x00, + 0xea, 0xff, 0x0b, 0x00, 0xcb, 0xff, 0x23, 0x00, 0x07, 0x00, 0x15, 0x00, + 0xb3, 0xff, 0x1a, 0x00, 0xec, 0xff, 0x01, 0x00, 0xd5, 0xff, 0x2a, 0x00, + 0xf4, 0xff, 0x12, 0x00, 0xc9, 0xff, 0x16, 0x00, 0x06, 0x00, 0x0b, 0x00, + 0xbc, 0xff, 0x14, 0x00, 0xeb, 0xff, 0xfe, 0xff, 0xe3, 0xff, 0x27, 0x00, + 0x01, 0x00, 0x12, 0x00, 0xc5, 0xff, 0x0b, 0x00, 0x06, 0x00, 0x05, 0x00, + 0xc9, 0xff, 0x14, 0x00, 0xef, 0xff, 0x02, 0x00, 0xe1, 0xff, 0x19, 0x00, + 0x03, 0x00, 0x16, 0x00, 0xc1, 0xff, 0x06, 0x00, 0x02, 0x00, 0x02, 0x00, + 0xce, 0xff, 0x14, 0x00, 0xef, 0xff, 0x00, 0x00, 0xe1, 0xff, 0x16, 0x00, + 0x06, 0x00, 0x13, 0x00, 0xc3, 0xff, 0x07, 0x00, 0x01, 0x00, 0xfd, 0xff, + 0xd4, 0xff, 0x14, 0x00, 0xee, 0xff, 0x04, 0x00, 0xe0, 0xff, 0x10, 0x00, + 0x06, 0x00, 0x10, 0x00, 0xc1, 0xff, 0x01, 0x00, 0xfa, 0xff, 0xf8, 0xff, + 0xdb, 0xff, 0x14, 0x00, 0xf3, 0xff, 0x05, 0x00, 0xdc, 0xff, 0x09, 0x00, + 0x09, 0x00, 0x0b, 0x00, 0xc3, 0xff, 0x02, 0x00, 0xf8, 0xff, 0xf7, 0xff, + 0xe1, 0xff, 0x12, 0x00, 0xf8, 0xff, 0x08, 0x00, 0xda, 0xff, 0x04, 0x00, + 0x07, 0x00, 0x0a, 0x00, 0xc8, 0xff, 0x02, 0x00, 0xf4, 0xff, 0xf9, 0xff, + 0xe4, 0xff, 0x0d, 0x00, 0xf9, 0xff, 0x0e, 0x00, 0xd5, 0xff, 0xfe, 0xff, + 0x07, 0x00, 0x08, 0x00, 0xcb, 0xff, 0x03, 0x00, 0xf4, 0xff, 0xfb, 0xff, + 0xe6, 0xff, 0x0c, 0x00, 0xfd, 0xff, 0x0e, 0x00, 0xd2, 0xff, 0xfe, 0xff, + 0x03, 0x00, 0x03, 0x00, 0xd1, 0xff, 0x06, 0x00, 0xf1, 0xff, 0xfd, 0xff, + 0xe5, 0xff, 0x09, 0x00, 0xff, 0xff, 0x0f, 0x00, 0xce, 0xff, 0xfc, 0xff, + 0xff, 0xff, 0x01, 0x00, 0xd4, 0xff, 0x07, 0x00, 0xf3, 0xff, 0xff, 0xff, + 0xe4, 0xff, 0x07, 0x00, 0x01, 0x00, 0x0d, 0x00, 0xce, 0xff, 0xfc, 0xff, + 0xfd, 0xff, 0xfe, 0xff, 0xda, 0xff, 0x09, 0x00, 0xf5, 0xff, 0x02, 0x00, + 0xe2, 0xff, 0x04, 0x00, 0x02, 0x00, 0x0d, 0x00, 0xcd, 0xff, 0xfc, 0xff, + 0xfb, 0xff, 0xfc, 0xff, 0xdf, 0xff, 0x08, 0x00, 0xf6, 0xff, 0x04, 0x00, + 0xdf, 0xff, 0xff, 0xff, 0x03, 0x00, 0x0a, 0x00, 0xd0, 0xff, 0xfd, 0xff, + 0xf9, 0xff, 0xfb, 0xff, 0xe2, 0xff, 0x07, 0x00, 0xf9, 0xff, 0x06, 0x00, + 0xdd, 0xff, 0xfe, 0xff, 0x03, 0x00, 0x07, 0x00, 0xd3, 0xff, 0xff, 0xff, + 0xf8, 0xff, 0xfb, 0xff, 0xe4, 0xff, 0x06, 0x00, 0xfb, 0xff, 0x07, 0x00, + 0xdb, 0xff, 0xfc, 0xff, 0x01, 0x00, 0x04, 0x00, 0xd5, 0xff, 0x00, 0x00, + 0xf8, 0xff, 0xfc, 0xff, 0xe7, 0xff, 0x05, 0x00, 0xfd, 0xff, 0x09, 0x00, + 0xd9, 0xff, 0xfb, 0xff, 0x01, 0x00, 0x02, 0x00, 0xda, 0xff, 0x02, 0x00, + 0xf7, 0xff, 0xfd, 0xff, 0xe6, 0xff, 0x03, 0x00, 0xff, 0xff, 0x09, 0x00, + 0xd8, 0xff, 0xfb, 0xff, 0xff, 0xff, 0xff, 0xff, 0xde, 0xff, 0x04, 0x00, + 0xf8, 0xff, 0xff, 0xff, 0xe6, 0xff, 0x02, 0x00, 0x00, 0x00, 0x08, 0x00, + 0xd8, 0xff, 0xfd, 0xff, 0xfd, 0xff, 0xfe, 0xff, 0xe1, 0xff, 0x05, 0x00, + 0xf9, 0xff, 0x00, 0x00, 0xe5, 0xff, 0x01, 0x00, 0x00, 0x00, 0x07, 0x00, + 0xd9, 0xff, 0xfe, 0xff, 0xfc, 0xff, 0xfd, 0xff, 0xe4, 0xff, 0x06, 0x00, + 0xfa, 0xff, 0x02, 0x00, 0xe3, 0xff, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, + 0xdb, 0xff, 0x00, 0x00, 0xfb, 0xff, 0xfc, 0xff, 0xe7, 0xff, 0x06, 0x00, + 0xfc, 0xff, 0x04, 0x00, 0xe1, 0xff, 0xff, 0xff, 0x00, 0x00, 0x04, 0x00, + 0xdd, 0xff, 0x02, 0x00, 0xfa, 0xff, 0xfd, 0xff, 0xe7, 0xff, 0x05, 0x00, + 0xfc, 0xff, 0x05, 0x00, 0xe0, 0xff, 0xff, 0xff, 0xff, 0xff, 0x02, 0x00, + 0xdf, 0xff, 0x03, 0x00, 0xfa, 0xff, 0xfe, 0xff, 0xe8, 0xff, 0x05, 0x00, + 0xfe, 0xff, 0x05, 0x00, 0xe0, 0xff, 0xff, 0xff, 0xfe, 0xff, 0x01, 0x00, + 0xe1, 0xff, 0x04, 0x00, 0xfb, 0xff, 0xff, 0xff, 0xe8, 0xff, 0x04, 0x00, + 0xff, 0xff, 0x06, 0x00, 0xde, 0xff, 0xff, 0xff, 0xfe, 0xff, 0x00, 0x00, + 0xe1, 0xff, 0x05, 0x00, 0xfb, 0xff, 0x01, 0x00, 0xe2, 0xff, 0x03, 0x00, + 0xff, 0xff, 0x04, 0x00, 0xdb, 0xff, 0x01, 0x00, 0xfd, 0xff, 0x00, 0x00, + 0xdd, 0xff, 0x04, 0x00, 0xfd, 0xff, 0x01, 0x00, 0xdc, 0xff, 0x02, 0x00, + 0xfe, 0xff, 0x03, 0x00, 0xd9, 0xff, 0x02, 0x00, 0xfd, 0xff, 0x00, 0x00, + 0xdb, 0xff, 0x03, 0x00, 0xfd, 0xff, 0x02, 0x00, 0xdb, 0xff, 0x02, 0x00, + 0xfe, 0xff, 0x02, 0x00, 0xdb, 0xff, 0x02, 0x00, 0xfd, 0xff, 0x01, 0x00, + 0xdd, 0xff, 0x02, 0x00, 0xfd, 0xff, 0x02, 0x00, 0xde, 0xff, 0x02, 0x00, + 0xfe, 0xff, 0x02, 0x00, 0xe1, 0xff, 0x01, 0x00, 0xfe, 0xff, 0x01, 0x00, + 0xe3, 0xff, 0x01, 0x00, 0xfe, 0xff, 0x01, 0x00 +}; + +static inline uint16_t read_le16(const uint8_t* p) { + return static_cast(p[0]) | (static_cast(p[1]) << 8); +} + +static inline uint32_t read_le32(const uint8_t* p) { + return static_cast(p[0]) | + (static_cast(p[1]) << 8) | + (static_cast(p[2]) << 16) | + (static_cast(p[3]) << 24); +} + +} // namespace + +std::unique_ptr CreateShHrirsFromAssets( + const std::string& filename, int target_sample_rate_hz, + Resampler* resampler) { + (void)filename; + DCHECK(resampler); + + /* Standard 44-byte canonical RIFF/WAVE header in kShHrirOrder1Wav. */ + constexpr size_t kWavHeaderBytes = 44; + CHECK_GE(sizeof(kShHrirOrder1Wav), kWavHeaderBytes); + + const uint16_t num_channels = read_le16(kShHrirOrder1Wav + 22); + const int wav_sample_rate_hz = static_cast(read_le32(kShHrirOrder1Wav + 24)); + const uint32_t data_bytes = read_le32(kShHrirOrder1Wav + 40); + const size_t total_samples = data_bytes / sizeof(int16_t); + const size_t sh_hrir_length = total_samples / num_channels; + + CHECK(IsValidAmbisonicOrder(num_channels)); + CHECK_GE(sizeof(kShHrirOrder1Wav), kWavHeaderBytes + data_bytes); + CHECK_GT(wav_sample_rate_hz, 0); + CHECK_GT(target_sample_rate_hz, 0); + + std::vector pcm_samples(total_samples); + std::memcpy(pcm_samples.data(), kShHrirOrder1Wav + kWavHeaderBytes, data_bytes); + + std::unique_ptr sh_hrirs( + new AudioBuffer(num_channels, sh_hrir_length)); + FillAudioBuffer(pcm_samples, num_channels, sh_hrirs.get()); + + if (wav_sample_rate_hz != target_sample_rate_hz) { + CHECK(Resampler::AreSampleRatesSupported(wav_sample_rate_hz, + target_sample_rate_hz)); + resampler->ResetState(); + resampler->SetRateAndNumChannels(wav_sample_rate_hz, target_sample_rate_hz, + num_channels); + std::unique_ptr resampled_sh_hrirs(new AudioBuffer( + num_channels, resampler->GetNextOutputLength(sh_hrir_length))); + resampler->Process(*sh_hrirs, resampled_sh_hrirs.get()); + return resampled_sh_hrirs; + } + + return sh_hrirs; +} + +} // namespace vraudio diff --git a/src/audio/resonance_audio/resonance_preinc.h b/src/audio/resonance_audio/resonance_preinc.h new file mode 100644 index 000000000000..868cf915aff4 --- /dev/null +++ b/src/audio/resonance_audio/resonance_preinc.h @@ -0,0 +1,26 @@ +/* SPDX-License-Identifier: BSD-3-Clause */ +#ifndef __RESONANCE_PREINC_H__ +#define __RESONANCE_PREINC_H__ + +#include + +extern "C" { +void *res_shim_malloc(size_t size); +void *res_shim_calloc(size_t nmemb, size_t size); +void *res_shim_realloc(void *ptr, size_t size); +void res_shim_free(void *ptr); +} + +namespace std { +using ::res_shim_malloc; +using ::res_shim_calloc; +using ::res_shim_realloc; +using ::res_shim_free; +} + +#define malloc res_shim_malloc +#define calloc res_shim_calloc +#define realloc res_shim_realloc +#define free res_shim_free + +#endif /* __RESONANCE_PREINC_H__ */ diff --git a/src/audio/resonance_audio/resonance_shims.c b/src/audio/resonance_audio/resonance_shims.c new file mode 100644 index 000000000000..3735d97e0996 --- /dev/null +++ b/src/audio/resonance_audio/resonance_shims.c @@ -0,0 +1,557 @@ +/* SPDX-License-Identifier: BSD-3-Clause + * + * C runtime / libc / math shims for Google Resonance Audio on SOF DSP + * (both built-in and LLEXT contexts). + */ + +#include +#include +#include +#include +#include + +#if defined(UNIT_TEST) || defined(CONFIG_ZEPHYR_POSIX) +#include +#endif + +#if !defined(LLEXT_MODULE) && !defined(LL_EXTENSION_BUILD) +#if defined(__ZEPHYR__) +#include +#include +#endif +#include +#if defined(__ZEPHYR__) && !defined(CONFIG_ZEPHYR_POSIX) +#include +static K_MUTEX_DEFINE(res_alloc_klock); +#if CONFIG_SOF_USERSPACE_LL +static APP_SYSUSER_BSS SYS_MUTEX_DEFINE(res_alloc_ulock); +#endif +#elif defined(__ZEPHYR__) +#include +static K_MUTEX_DEFINE(res_alloc_klock); +#endif +static APP_SYSUSER_BSS struct processing_module *active_res_mod; +#else +static struct processing_module *active_res_mod; +#endif + +#define RES_ALLOC_MAGIC 0x52455341U /* "RESA" */ +#define RES_ALLOC_HDR_SIZE ((sizeof(struct res_alloc_hdr) + 15U) & ~15U) + +struct res_alloc_hdr { + uint32_t magic; + size_t size; + struct processing_module *owner; +}; + +static void res_alloc_lock(void) +{ +#if defined(__ZEPHYR__) && !defined(LLEXT_MODULE) && !defined(LL_EXTENSION_BUILD) +#if !defined(CONFIG_ZEPHYR_POSIX) && CONFIG_SOF_USERSPACE_LL + if (k_is_user_context()) { + sys_mutex_lock(&res_alloc_ulock, K_FOREVER); + return; + } +#endif + k_mutex_lock(&res_alloc_klock, K_FOREVER); +#endif +} + +static void res_alloc_unlock(void) +{ +#if defined(__ZEPHYR__) && !defined(LLEXT_MODULE) && !defined(LL_EXTENSION_BUILD) +#if !defined(CONFIG_ZEPHYR_POSIX) && CONFIG_SOF_USERSPACE_LL + if (k_is_user_context()) { + sys_mutex_unlock(&res_alloc_ulock); + return; + } +#endif + k_mutex_unlock(&res_alloc_klock); +#endif +} + +void resonance_audio_backend_enter(struct processing_module *mod) +{ + res_alloc_lock(); + active_res_mod = mod; +} + +void resonance_audio_backend_exit(struct processing_module *mod) +{ + if (active_res_mod == mod) + active_res_mod = NULL; + res_alloc_unlock(); +} + +void resonance_audio_set_active_mod(struct processing_module *mod) +{ + active_res_mod = mod; +} + +struct processing_module *resonance_audio_get_active_mod(void) +{ + return active_res_mod; +} + +void resonance_panic(void) +{ +#if defined(UNIT_TEST) || defined(CONFIG_ZEPHYR_POSIX) + abort(); +#elif defined(LL_EXTENSION_BUILD) || defined(LLEXT_MODULE) + __builtin_trap(); +#else + k_panic(); +#endif +} + +#if defined(LL_EXTENSION_BUILD) || defined(LLEXT_MODULE) +void abort(void) +{ + resonance_panic(); + __builtin_unreachable(); +} +#endif + +static void res_raw_free_for(struct processing_module *mod, void *ptr) +{ + if (mod) + mod_free(mod, ptr); + else + rfree(ptr); +} + +static void *res_malloc_for(struct processing_module *mod, size_t size) +{ + struct res_alloc_hdr *hdr; + size_t total; + + if (size == 0) + size = 1; + + total = RES_ALLOC_HDR_SIZE + size; + hdr = mod ? mod_alloc(mod, total) : rmalloc(SOF_MEM_FLAG_USER, total); + if (!hdr) + return NULL; + + hdr->magic = RES_ALLOC_MAGIC; + hdr->size = size; + hdr->owner = mod; + return (uint8_t *)hdr + RES_ALLOC_HDR_SIZE; +} + +void *res_shim_malloc(size_t size) +{ + return res_malloc_for(active_res_mod, size); +} + +void res_shim_free(void *ptr) +{ + struct res_alloc_hdr *hdr; + + if (!ptr) + return; + + hdr = (struct res_alloc_hdr *)((uint8_t *)ptr - RES_ALLOC_HDR_SIZE); + if (hdr->magic == RES_ALLOC_MAGIC) { + struct processing_module *owner = hdr->owner; + + hdr->magic = 0; + res_raw_free_for(owner, hdr); + } else { + res_raw_free_for(active_res_mod, ptr); + } +} + +void *res_shim_calloc(size_t nmemb, size_t size) +{ + size_t total = nmemb * size; + void *p; + + if (nmemb != 0 && total / nmemb != size) + return NULL; + + p = res_shim_malloc(total); + if (p && total > 0) + memset(p, 0, total); + return p; +} + +void *res_shim_realloc(void *ptr, size_t size) +{ + struct res_alloc_hdr *hdr; + size_t copy_sz; + void *new_ptr; + + if (!ptr) + return res_shim_malloc(size); + + if (size == 0) { + res_shim_free(ptr); + return NULL; + } + + hdr = (struct res_alloc_hdr *)((uint8_t *)ptr - RES_ALLOC_HDR_SIZE); + if (hdr->magic != RES_ALLOC_MAGIC) + return NULL; + + new_ptr = res_malloc_for(hdr->owner, size); + if (!new_ptr) + return NULL; + + copy_sz = hdr->size < size ? hdr->size : size; + memcpy(new_ptr, ptr, copy_sz); + res_shim_free(ptr); + return new_ptr; +} + +#if defined(LL_EXTENSION_BUILD) || defined(LLEXT_MODULE) +void *malloc(size_t size) +{ + return res_shim_malloc(size); +} + +void free(void *ptr) +{ + res_shim_free(ptr); +} + +void *calloc(size_t nmemb, size_t size) +{ + return res_shim_calloc(nmemb, size); +} + +void *realloc(void *ptr, size_t size) +{ + return res_shim_realloc(ptr, size); +} + +static int res_llext_errno; + +int *z_errno_wrap(void) +{ + return &res_llext_errno; +} + +int *__errno(void) +{ + return &res_llext_errno; +} +#endif + +#if !defined(UNIT_TEST) && !defined(CONFIG_ZEPHYR_POSIX) +/* ============================ PRNG ============================== */ + +static uint32_t res_rng_state = 0x12345678U; + +void srand(unsigned int seed) +{ + res_rng_state = seed ? seed : 0x12345678U; +} + +int rand(void) +{ + res_rng_state = res_rng_state * 1664525U + 1013904223U; + return (int)((res_rng_state >> 1) & 0x7fffffffU); +} + +/* ============================ Math ============================== */ + +float fabsf(float x) +{ + return (x < 0.0f) ? -x : x; +} + +float floorf(float x) +{ + int i = (int)x; + + if (x < 0.0f && (float)i != x) + i--; + return (float)i; +} + +double floor(double x) +{ + long long i = (long long)x; + + if (x < 0.0 && (double)i != x) + i--; + return (double)i; +} + +float ceilf(float x) +{ + int i = (int)x; + + if (x > 0.0f && (float)i != x) + i++; + return (float)i; +} + +float roundf(float x) +{ + return (x >= 0.0f) ? floorf(x + 0.5f) : ceilf(x - 0.5f); +} + +static inline float res_ldexp2(int n) +{ + union { float f; uint32_t i; } u; + + if (n < -126) + return 0.0f; + if (n > 127) + n = 127; + u.i = (uint32_t)(n + 127) << 23; + return u.f; +} + +float log2f(float x) +{ + union { float f; uint32_t i; } u = { .f = x }; + int e; + float m, z; + + if (x <= 0.0f) + return -127.0f; + + e = (int)((u.i >> 23) & 0xff) - 127; + u.i = (u.i & 0x007fffffU) | 0x3f800000U; + m = u.f; + z = m - 1.0f; + return (float)e + z * (1.44269504f - z * (0.72134752f - z * 0.48089834f)); +} + +float logf(float x) +{ + return log2f(x) * 0.6931471805599453f; +} + +static float res_exp2f(float x) +{ + int n; + float f, p; + + if (x > 127.0f) + return 3.40282347e+38f; + if (x < -126.0f) + return 0.0f; + + n = (int)x; + if (x < 0.0f && (float)n != x) + n--; + f = x - (float)n; + p = 1.0f + f * (0.6931472f + f * (0.2402265f + f * 0.0555041f)); + return p * res_ldexp2(n); +} + +float expf(float x) +{ + return res_exp2f(x * 1.4426950408889634f); +} + +#if defined(LL_EXTENSION_BUILD) || defined(LLEXT_MODULE) || !defined(CONFIG_MINIMAL_LIBC) +float sqrtf(float x) +{ + union { float f; uint32_t i; } u = { .f = x }; + float y; + + if (x <= 0.0f) + return 0.0f; + + u.i = (u.i >> 1) + 0x1fc00000U; + y = u.f; + y = 0.5f * (y + x / y); + y = 0.5f * (y + x / y); + y = 0.5f * (y + x / y); + return y; +} +#else +float sqrtf(float x); +#endif + +float powf(float x, float y) +{ + if (y == 0.0f) + return 1.0f; + if (x == 0.0f) + return (y > 0.0f) ? 0.0f : 1.0f; + if (y == 1.0f) + return x; + if (y == 2.0f) + return x * x; + if (y == 0.5f) + return sqrtf(x); + if (x < 0.0f) { + long yi = (long)y; + + if ((float)yi == y) { + float mag = powf(-x, y); + + return (yi & 1L) ? -mag : mag; + } + return 0.0f; + } + return res_exp2f(y * log2f(x)); +} + +#if defined(LL_EXTENSION_BUILD) || defined(LLEXT_MODULE) || !defined(CONFIG_MINIMAL_LIBC) +double sqrt(double x) +{ + union { double d; uint64_t i; } u = { .d = x }; + double y; + + if (x <= 0.0) + return 0.0; + + u.i = (u.i >> 1) + 0x1ff8000000000000ULL; + y = u.d; + y = 0.5 * (y + x / y); + y = 0.5 * (y + x / y); + y = 0.5 * (y + x / y); + y = 0.5 * (y + x / y); + return y; +} +#else +double sqrt(double x); +#endif + +double pow(double x, double y) +{ + long long yi; + + if (y == 0.0) + return 1.0; + if (x == 0.0) + return (y > 0.0) ? 0.0 : 1.0; + if (y == 1.0) + return x; + if (y == 2.0) + return x * x; + if (y == 0.5) + return sqrt(x); + + yi = (long long)y; + if ((double)yi == y && yi >= -1024 && yi <= 1024) { + unsigned long long n = (yi < 0) ? (unsigned long long)(-yi) + : (unsigned long long)yi; + double base = (yi < 0) ? (1.0 / x) : x; + double res = 1.0; + + while (n) { + if (n & 1ULL) + res *= base; + n >>= 1; + if (n) + base *= base; + } + return res; + } + + if (x < 0.0) + return 0.0; + + return (double)powf((float)x, (float)y); +} + +static inline void res_sincosf_poly(float z, float *s_out, float *c_out) +{ + float z2 = z * z; + + *s_out = z * (1.0f + z2 * (-0.166666667f + z2 * (0.008333333f - z2 * 0.0001984127f))); + *c_out = 1.0f + z2 * (-0.5f + z2 * (0.041666667f + z2 * (-0.0013888889f + z2 * 0.0000248016f))); +} + +float sinf(float x) +{ + const float inv_half_pi = 0.636619772367581343f; + const float half_pi_hi = 1.5707963267948966f; + int k = (int)roundf(x * inv_half_pi); + float z = x - (float)k * half_pi_hi; + float s, c; + + res_sincosf_poly(z, &s, &c); + switch ((k % 4 + 4) % 4) { + case 0: return s; + case 1: return c; + case 2: return -s; + case 3: default: return -c; + } +} + +float cosf(float x) +{ + const float inv_half_pi = 0.636619772367581343f; + const float half_pi_hi = 1.5707963267948966f; + int k = (int)roundf(x * inv_half_pi); + float z = x - (float)k * half_pi_hi; + float s, c; + + res_sincosf_poly(z, &s, &c); + switch ((k % 4 + 4) % 4) { + case 0: return c; + case 1: return -s; + case 2: return -c; + case 3: default: return s; + } +} + +float tanf(float x) +{ + float c = cosf(x); + + if (fabsf(c) < 1e-7f) + return (c >= 0.0f) ? 1e7f : -1e7f; + return sinf(x) / c; +} + +float sinhf(float x) +{ + float ep = expf(x); + float em = expf(-x); + + return 0.5f * (ep - em); +} + +static float res_atanf_unit(float x) +{ + float x2 = x * x; + + return x * (0.9998660f + x2 * (-0.3302995f + x2 * (0.1801410f + + x2 * (-0.0851330f + x2 * 0.0208351f)))); +} + +float atan2f(float y, float x) +{ + const float pi = 3.1415926535897932f; + const float half_pi = 1.5707963267948966f; + float ax = fabsf(x); + float ay = fabsf(y); + float a; + + if (ax == 0.0f && ay == 0.0f) + return 0.0f; + + if (ax >= ay) { + a = res_atanf_unit(ay / ax); + } else { + a = half_pi - res_atanf_unit(ax / ay); + } + + if (x < 0.0f) + a = pi - a; + if (y < 0.0f) + a = -a; + return a; +} + +float acosf(float x) +{ + const float half_pi = 1.5707963267948966f; + + if (x >= 1.0f) + return 0.0f; + if (x <= -1.0f) + return 3.1415926535897932f; + return half_pi - atan2f(x, sqrtf(1.0f - x * x)); +} +#endif diff --git a/src/audio/resonance_audio/resonance_shims.cpp b/src/audio/resonance_audio/resonance_shims.cpp new file mode 100644 index 000000000000..a461abc22167 --- /dev/null +++ b/src/audio/resonance_audio/resonance_shims.cpp @@ -0,0 +1,208 @@ +/* SPDX-License-Identifier: BSD-3-Clause + * + * Minimal C++17 runtime shims for Google Resonance Audio on SOF DSP + * (eliminates libstdc++.a unwinding/locale/iostream bloat). + */ + +#include +#include +#include +#include +#include +#include +#include + +extern "C" { +void *res_shim_malloc(size_t size); +void res_shim_free(void *ptr); +void resonance_panic(void); +} + +void *operator new(std::size_t size) +{ + void *p = res_shim_malloc(size); + + if (!p) + resonance_panic(); + return p; +} + +void *operator new[](std::size_t size) +{ + void *p = res_shim_malloc(size); + + if (!p) + resonance_panic(); + return p; +} + +void *operator new(std::size_t size, const std::nothrow_t &) noexcept +{ + return res_shim_malloc(size); +} + +void *operator new[](std::size_t size, const std::nothrow_t &) noexcept +{ + return res_shim_malloc(size); +} + +void operator delete(void *ptr) noexcept +{ + res_shim_free(ptr); +} + +void operator delete[](void *ptr) noexcept +{ + res_shim_free(ptr); +} + +void operator delete(void *ptr, std::size_t size) noexcept +{ + (void)size; + res_shim_free(ptr); +} + +void operator delete[](void *ptr, std::size_t size) noexcept +{ + (void)size; + res_shim_free(ptr); +} + +void operator delete(void *ptr, const std::nothrow_t &) noexcept +{ + res_shim_free(ptr); +} + +void operator delete[](void *ptr, const std::nothrow_t &) noexcept +{ + res_shim_free(ptr); +} + +#if __cpp_aligned_new +void *operator new(std::size_t size, std::align_val_t align) +{ + std::size_t a = static_cast(align); + + if (a < sizeof(void *)) + a = sizeof(void *); + + void *orig = res_shim_malloc(size + a + sizeof(void *)); + + if (!orig) + resonance_panic(); + + std::uintptr_t raw = reinterpret_cast(orig) + sizeof(void *); + void *aligned = reinterpret_cast((raw + a - 1) & ~(a - 1)); + + reinterpret_cast(aligned)[-1] = orig; + return aligned; +} + +void *operator new[](std::size_t size, std::align_val_t align) +{ + return ::operator new(size, align); +} + +void operator delete(void *ptr, std::align_val_t) noexcept +{ + if (!ptr) + return; + res_shim_free(reinterpret_cast(ptr)[-1]); +} + +void operator delete[](void *ptr, std::align_val_t align) noexcept +{ + ::operator delete(ptr, align); +} + +void operator delete(void *ptr, std::size_t, std::align_val_t align) noexcept +{ + ::operator delete(ptr, align); +} + +void operator delete[](void *ptr, std::size_t, std::align_val_t align) noexcept +{ + ::operator delete(ptr, align); +} +#endif + +extern "C" { +void *__dso_handle = nullptr; +int __cxa_atexit(void (*)(void *), void *, void *) { return 0; } +void __cxa_pure_virtual() { resonance_panic(); } +} + +#if !defined(UNIT_TEST) && !defined(CONFIG_ZEPHYR_POSIX) +namespace std { +void __throw_bad_alloc() { resonance_panic(); } +void __throw_bad_array_new_length() { resonance_panic(); } +void __throw_length_error(char const *) { resonance_panic(); } +void __throw_logic_error(char const *) { resonance_panic(); } +void __throw_out_of_range(char const *) { resonance_panic(); } +void __throw_out_of_range_fmt(char const *, ...) { resonance_panic(); } +void __throw_bad_function_call() { resonance_panic(); } +void __throw_system_error(int) { resonance_panic(); } +template char *basic_string::_M_create(basic_string::size_type &, + basic_string::size_type); +template void basic_string::reserve(basic_string::size_type); +template basic_string &basic_string::_M_replace( + basic_string::size_type, basic_string::size_type, + const char *, basic_string::size_type); +template void basic_string::_M_replace_cold( + char *, basic_string::size_type, const char *, + basic_string::size_type, basic_string::size_type); +template void basic_string::_M_mutate( + basic_string::size_type, basic_string::size_type, + const char *, basic_string::size_type); +template void basic_string::_M_assign(const basic_string &); + +bool _Sp_make_shared_tag::_S_eq(const type_info &) noexcept +{ + return false; +} + +namespace __detail { + +static const unsigned long kResPrimes[] = { + 2UL, 5UL, 11UL, 23UL, 47UL, 97UL, 199UL, 409UL, 823UL, 1741UL, + 3469UL, 6949UL, 14033UL, 28411UL, 57557UL, 116731UL, 236897UL +}; + +std::size_t _Prime_rehash_policy::_M_next_bkt(std::size_t n) const +{ + const std::size_t count = sizeof(kResPrimes) / sizeof(kResPrimes[0]); + std::size_t res = kResPrimes[count - 1]; + + for (std::size_t i = 0; i < count; ++i) { + if (kResPrimes[i] >= n) { + res = kResPrimes[i]; + break; + } + } + _M_next_resize = static_cast( + static_cast(res) * _M_max_load_factor); + if (_M_next_resize == 0) + _M_next_resize = res; + return res; +} + +std::pair _Prime_rehash_policy::_M_need_rehash( + std::size_t n_bkt, std::size_t n_elt, std::size_t n_ins) const +{ + if (n_elt + n_ins > _M_next_resize) { + float min_bkts = static_cast(n_elt + n_ins) / _M_max_load_factor; + std::size_t min_bkt_i = static_cast(min_bkts) + 1U; + + if (min_bkt_i >= n_bkt) + return { true, _M_next_bkt(min_bkt_i) }; + + _M_next_resize = static_cast( + static_cast(n_bkt) * _M_max_load_factor); + return { false, 0 }; + } + return { false, 0 }; +} + +} // namespace __detail +} +#endif diff --git a/src/audio/resonance_audio/resonance_wrapper.cpp b/src/audio/resonance_audio/resonance_wrapper.cpp new file mode 100644 index 000000000000..46ad978006cd --- /dev/null +++ b/src/audio/resonance_audio/resonance_wrapper.cpp @@ -0,0 +1,281 @@ +/* SPDX-License-Identifier: BSD-3-Clause + * + * C++17 bridge wrapping Resonance Audio SystemSettings + GraphManager directly + * (avoiding LocklessTaskQueue's 25,600-slot allocation and 64-bit atomics). + * Caps spatialization at 1st-order HOA (4 internal channels). + */ +#include "resonance_wrapper.h" + +#include +#include +#include +#include + +#include "base/audio_buffer.h" +#include "base/constants_and_types.h" +#include "base/misc_math.h" +#include "base/spherical_angle.h" +#include "dsp/distance_attenuation.h" +#include "graph/graph_manager.h" +#include "graph/system_settings.h" +#include "platforms/common/room_effects_utils.h" +#include "platforms/common/room_properties.h" +#include "utils/planar_interleaved_conversion.h" + +namespace { + +constexpr size_t kMaxVirtualSpeakers = 8; + +/* Standard ITU-R BS.775-3 azimuth angles (degrees) matching BinauralSurroundRendererImpl. */ +constexpr float kMonoAngles[] = {0.0f}; +constexpr float kStereoAngles[] = {30.0f, -30.0f}; +constexpr float kSurround51Angles[] = {30.0f, -30.0f, 0.0f, 0.0f, 110.0f, -110.0f}; +constexpr float kSurround71Angles[] = {30.0f, -30.0f, 0.0f, 0.0f, 90.0f, -90.0f, 150.0f, -150.0f}; + +/* Default shoebox room matching Resonance Audio AESTD1001.1.01-10 surround reverb. */ +void ConfigureDefaultRoom(vraudio::SystemSettings* settings, + vraudio::GraphManager* graph) { + vraudio::RoomProperties room_props; + room_props.position[0] = 0.0f; + room_props.position[1] = 0.0f; + room_props.position[2] = 0.0f; + room_props.rotation[0] = 0.0f; + room_props.rotation[1] = 0.0f; + room_props.rotation[2] = 0.0f; + room_props.rotation[3] = 1.0f; + room_props.dimensions[0] = 5.0f; + room_props.dimensions[1] = 3.0f; + room_props.dimensions[2] = 5.0f; + room_props.material_names[0] = vraudio::MaterialName::kAcousticCeilingTiles; + room_props.material_names[1] = vraudio::MaterialName::kAcousticCeilingTiles; + room_props.material_names[2] = vraudio::MaterialName::kPlasterRough; + room_props.material_names[3] = vraudio::MaterialName::kParquetOnConcrete; + room_props.material_names[4] = vraudio::MaterialName::kAcousticCeilingTiles; + room_props.material_names[5] = vraudio::MaterialName::kAcousticCeilingTiles; + room_props.reflection_scalar = 1.0f; + room_props.reverb_gain = 1.0f; + room_props.reverb_time = 1.0f; + room_props.reverb_brightness = 0.0f; + + settings->SetReflectionProperties(vraudio::ComputeReflectionProperties(room_props)); + settings->SetReverbProperties(vraudio::ComputeReverbProperties(room_props)); + graph->UpdateRoomReflections(); + graph->UpdateRoomReverb(); +} + +} // namespace + +struct resonance_inst { + resonance_cfg cfg; + std::unique_ptr settings; + std::unique_ptr graph; + std::vector source_ids; + size_t expected_in_channels = 0; + float gain_compensation = 1.0f; +}; + +static vraudio::SourceId CreateVirtualSpeaker(resonance_inst* inst, + vraudio::SourceId id, + float azimuth_deg) { + auto pos = vraudio::SphericalAngle::FromDegrees(azimuth_deg, 0.0f) + .GetWorldPositionOnUnitSphere(); + inst->settings->GetSourceParametersManager()->Register(id); + auto* params = inst->settings->GetSourceParametersManager()->GetMutableParameters(id); + if (params) { + params->object_transform.position = pos; + params->distance_rolloff_model = vraudio::DistanceRolloffModel::kNone; + params->distance_attenuation = 1.0f; + params->gain = 1.0f; + } + /* Ambisonic order = 1 (4 internal FOA channels), HRTF enabled, direct rendering enabled. */ + inst->graph->CreateSoundObjectSource(id, 1, true, true); + return id; +} + +extern "C" { + +resonance_inst_t* resonance_create(const struct resonance_cfg* cfg) { + if (!cfg || cfg->sample_rate_hz <= 0 || cfg->frames_per_buffer < 32) { + return nullptr; + } + + auto inst = std::make_unique(); + inst->cfg = *cfg; + inst->settings = std::make_unique( + vraudio::kNumStereoChannels, cfg->frames_per_buffer, cfg->sample_rate_hz); + inst->settings->SetStereoSpeakerMode(cfg->stereo_speaker_mode); + inst->graph = std::make_unique(*inst->settings); + + ConfigureDefaultRoom(inst->settings.get(), inst->graph.get()); + inst->graph->EnableRoomEffects(cfg->room_reverb_enable); + + const float* angles = nullptr; + size_t num_speakers = 0; + + switch (cfg->mode) { + case RESONANCE_MODE_MONO: + angles = kMonoAngles; + num_speakers = 1; + inst->expected_in_channels = 1; + inst->gain_compensation = 0.5f; + break; + case RESONANCE_MODE_STEREO: + angles = kStereoAngles; + num_speakers = 2; + inst->expected_in_channels = 2; + inst->gain_compensation = 0.5f; + break; + case RESONANCE_MODE_SURROUND_51: + angles = kSurround51Angles; + num_speakers = 6; + inst->expected_in_channels = 6; + inst->gain_compensation = 0.5f; + break; + case RESONANCE_MODE_SURROUND_71: + angles = kSurround71Angles; + num_speakers = 8; + inst->expected_in_channels = 8; + inst->gain_compensation = 0.5f; + break; + case RESONANCE_MODE_FOA_AMBIX: + inst->expected_in_channels = vraudio::kNumFirstOrderAmbisonicChannels; + inst->gain_compensation = 1.0f; + { + const vraudio::SourceId id = 0; + inst->settings->GetSourceParametersManager()->Register(id); + auto* params = + inst->settings->GetSourceParametersManager()->GetMutableParameters(id); + if (params) { + params->gain = 1.0f; + } + inst->graph->CreateAmbisonicSource(id, vraudio::kNumFirstOrderAmbisonicChannels); + inst->source_ids.push_back(id); + } + break; + default: + return nullptr; + } + + if (angles && num_speakers > 0 && num_speakers <= kMaxVirtualSpeakers) { + inst->source_ids.reserve(num_speakers); + for (size_t i = 0; i < num_speakers; ++i) { + inst->source_ids.push_back( + CreateVirtualSpeaker(inst.get(), static_cast(i), angles[i])); + } + } + + const float vol = (cfg->master_volume > 0.0f) ? cfg->master_volume : 1.0f; + inst->settings->SetMasterGain(vol * inst->gain_compensation); + return inst.release(); +} + +int resonance_process(resonance_inst_t* inst, const float* in_interleaved, + size_t in_channels, float* out_interleaved, + size_t num_frames) { + if (!inst || !inst->graph || !in_interleaved || !out_interleaved) { + return -1; + } + if (in_channels != inst->expected_in_channels || + num_frames != inst->cfg.frames_per_buffer) { + return -1; + } + + if (inst->cfg.mode == RESONANCE_MODE_FOA_AMBIX) { + vraudio::AudioBuffer* buf = inst->graph->GetMutableAudioBuffer(inst->source_ids[0]); + if (!buf) { + return -1; + } + vraudio::FillAudioBuffer(in_interleaved, num_frames, in_channels, buf); + } else { + /* Deinterleave each channel directly into its virtual speaker mono AudioBuffer. */ + for (size_t ch = 0; ch < in_channels; ++ch) { + vraudio::AudioBuffer* buf = + inst->graph->GetMutableAudioBuffer(inst->source_ids[ch]); + if (!buf) { + return -1; + } + float* dst = (*buf)[0].begin(); + for (size_t f = 0; f < num_frames; ++f) { + dst[f] = in_interleaved[f * in_channels + ch]; + } + } + } + + if (inst->graph->GetRoomEffectsEnabled()) { + inst->graph->UpdateRoomReflections(); + inst->graph->UpdateRoomReverb(); + } + + const float master_gain = inst->settings->GetMasterGain(); + const auto& listener_pos = inst->settings->GetHeadPosition(); + const float refl_gain = inst->settings->GetReflectionProperties().gain; + const float rev_gain = inst->settings->GetReverbProperties().gain; + inst->settings->GetSourceParametersManager()->ProcessAllParameters( + [master_gain, refl_gain, rev_gain, &listener_pos]( + vraudio::SourceParameters* parameters) { + vraudio::UpdateAttenuationParameters(master_gain, refl_gain, rev_gain, + listener_pos, parameters); + }); + + inst->graph->Process(); + const vraudio::AudioBuffer* stereo = inst->graph->GetStereoBuffer(); + if (!stereo) { + std::memset(out_interleaved, 0, + num_frames * vraudio::kNumStereoChannels * sizeof(float)); + return 0; + } + + const float* left = (*stereo)[0].begin(); + const float* right = (*stereo)[1].begin(); + for (size_t f = 0; f < num_frames; ++f) { + out_interleaved[f * 2 + 0] = left[f]; + out_interleaved[f * 2 + 1] = right[f]; + } + return 0; +} + +void resonance_set_head_pose(resonance_inst_t* inst, const float pos[3], + const float quat[4]) { + if (!inst || !inst->settings) { + return; + } + if (pos) { + inst->settings->SetHeadPosition( + vraudio::WorldPosition(pos[0], pos[1], pos[2])); + } + if (quat) { + /* WorldRotation = Eigen::Quaternion(w, x, y, z); external ABI is (x, y, z, w). */ + vraudio::WorldRotation q(quat[3], quat[0], quat[1], quat[2]); + if (q.squaredNorm() > 1e-12f) { + q.normalize(); + } else { + q = vraudio::WorldRotation::Identity(); + } + inst->settings->SetHeadRotation(q); + } +} + +void resonance_set_stereo_speaker_mode(resonance_inst_t* inst, bool enabled) { + if (inst && inst->settings) { + inst->settings->SetStereoSpeakerMode(enabled); + } +} + +void resonance_set_master_volume(resonance_inst_t* inst, float volume) { + if (inst && inst->settings) { + inst->settings->SetMasterGain( + std::max(0.0f, volume) * inst->gain_compensation); + } +} + +void resonance_set_room_enabled(resonance_inst_t* inst, bool enabled) { + if (inst && inst->graph) { + inst->graph->EnableRoomEffects(enabled); + } +} + +void resonance_free(resonance_inst_t* inst) { + delete inst; +} + +} // extern "C" diff --git a/src/audio/resonance_audio/resonance_wrapper.h b/src/audio/resonance_audio/resonance_wrapper.h new file mode 100644 index 000000000000..cdb28b800331 --- /dev/null +++ b/src/audio/resonance_audio/resonance_wrapper.h @@ -0,0 +1,50 @@ +/* SPDX-License-Identifier: BSD-3-Clause + * + * Pure-C ABI wrapper for Google Resonance Audio spatializer. + */ +#ifndef __RESONANCE_WRAPPER_H__ +#define __RESONANCE_WRAPPER_H__ + +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct resonance_inst resonance_inst_t; + +enum resonance_input_mode { + RESONANCE_MODE_MONO = 0, /* 1ch -> virtual center -> 2ch binaural */ + RESONANCE_MODE_STEREO = 1, /* 2ch (+/-30 deg) -> 2ch binaural */ + RESONANCE_MODE_SURROUND_51 = 2, /* 6ch (L,R,C,LFE,LS,RS) -> 2ch binaural */ + RESONANCE_MODE_SURROUND_71 = 3, /* 8ch (L,R,C,LFE,LS1,RS1,LS2,RS2) -> 2ch binaural */ + RESONANCE_MODE_FOA_AMBIX = 4, /* 4ch AmbiX (ACN/SN3D) -> 2ch binaural */ +}; + +struct resonance_cfg { + int sample_rate_hz; + size_t frames_per_buffer; + enum resonance_input_mode mode; + bool stereo_speaker_mode; + bool room_reverb_enable; + float master_volume; +}; + +resonance_inst_t *resonance_create(const struct resonance_cfg *cfg); +int resonance_process(resonance_inst_t *inst, const float *in_interleaved, + size_t in_channels, float *out_interleaved, + size_t num_frames); +void resonance_set_head_pose(resonance_inst_t *inst, const float pos[3], + const float quat[4]); +void resonance_set_stereo_speaker_mode(resonance_inst_t *inst, bool enabled); +void resonance_set_master_volume(resonance_inst_t *inst, float volume); +void resonance_set_room_enabled(resonance_inst_t *inst, bool enabled); +void resonance_free(resonance_inst_t *inst); + +#ifdef __cplusplus +} +#endif + +#endif /* __RESONANCE_WRAPPER_H__ */ diff --git a/test/ztest/unit/audio/resonance_audio/CMakeLists.txt b/test/ztest/unit/audio/resonance_audio/CMakeLists.txt new file mode 100644 index 000000000000..3addf37edae8 --- /dev/null +++ b/test/ztest/unit/audio/resonance_audio/CMakeLists.txt @@ -0,0 +1,164 @@ +# SPDX-License-Identifier: BSD-3-Clause + +cmake_minimum_required(VERSION 3.20.0) + +find_package(Zephyr REQUIRED HINTS $ENV{ZEPHYR_BASE}) +project(sof_unit_audio_resonance_audio) + +set(SOF_ROOT "${PROJECT_SOURCE_DIR}/../../../../../") +set(sof_top_dir ${SOF_ROOT}) + +if(NOT DEFINED SOF_RESONANCE_AUDIO_SRC_DIR) + set(SOF_RESONANCE_AUDIO_SRC_DIR "${SOF_ROOT}/../modules/audio/resonance-audio") +endif() +cmake_path(NORMAL_PATH SOF_RESONANCE_AUDIO_SRC_DIR) + +include(${SOF_ROOT}/scripts/cmake/misc.cmake) +include(${SOF_ROOT}/scripts/cmake/uuid-registry.cmake) + +set(_res_mod_dir "${SOF_ROOT}/src/audio/resonance_audio") +set(_res_ra_dir "${SOF_RESONANCE_AUDIO_SRC_DIR}/resonance_audio") +set(_res_eigen_dir "${SOF_RESONANCE_AUDIO_SRC_DIR}/third_party/eigen") +set(_res_pffft_dir "${SOF_RESONANCE_AUDIO_SRC_DIR}/third_party/pffft") + +target_include_directories(app PRIVATE + ${_res_mod_dir}/overrides + ${_res_mod_dir} + ${SOF_ROOT}/zephyr/include + ${SOF_ROOT}/src/include + ${SOF_ROOT}/src/kernel/include + ${SOF_ROOT}/src/kernel/platform/posix/include + ${SOF_ROOT}/src/platform/posix/include + ${SOF_ROOT}/src/audio + ${SOF_ROOT}/tools/rimage/src/include + ${SOF_ROOT}/test/cmocka/include + ${PROJECT_BINARY_DIR}/include/generated + ${SOF_RESONANCE_AUDIO_SRC_DIR} + ${_res_ra_dir} + ${_res_eigen_dir} + ${_res_pffft_dir} +) + +target_compile_definitions(app PRIVATE + -DCONFIG_ZEPHYR_POSIX=1 + -DCONFIG_LIBRARY=1 + -DUNIT_TEST=1 + -DNDEBUG=1 +) + +set(_res_pffft_srcs + "${_res_pffft_dir}/pffft.c" + "${_res_pffft_dir}/fftpack.c" +) + +set(_res_cxx_srcs + "${_res_mod_dir}/resonance_wrapper.cpp" + "${_res_mod_dir}/resonance_shims.cpp" + "${_res_mod_dir}/resonance_hrtf_assets.cc" + "${SOF_RESONANCE_AUDIO_SRC_DIR}/platforms/common/room_effects_utils.cc" + "${_res_ra_dir}/ambisonics/ambisonic_binaural_decoder.cc" + "${_res_mod_dir}/overrides/ambisonics/ambisonic_lookup_table.cc" + "${_res_ra_dir}/ambisonics/associated_legendre_polynomials_generator.cc" + "${_res_ra_dir}/ambisonics/foa_rotator.cc" + "${_res_ra_dir}/ambisonics/hoa_rotator.cc" + "${_res_ra_dir}/ambisonics/stereo_from_soundfield_converter.cc" + "${_res_ra_dir}/base/audio_buffer.cc" + "${_res_ra_dir}/base/channel_view.cc" + "${_res_ra_dir}/base/misc_math.cc" + "${_res_ra_dir}/base/simd_utils.cc" + "${_res_ra_dir}/base/spherical_angle.cc" + "${_res_ra_dir}/config/source_config.cc" + "${_res_ra_dir}/dsp/biquad_filter.cc" + "${_res_ra_dir}/dsp/channel_converter.cc" + "${_res_ra_dir}/dsp/circular_buffer.cc" + "${_res_ra_dir}/dsp/delay_filter.cc" + "${_res_ra_dir}/dsp/distance_attenuation.cc" + "${_res_ra_dir}/dsp/fft_manager.cc" + "${_res_ra_dir}/dsp/filter_coefficient_generators.cc" + "${_res_ra_dir}/dsp/fir_filter.cc" + "${_res_ra_dir}/dsp/gain.cc" + "${_res_ra_dir}/dsp/gain_mixer.cc" + "${_res_ra_dir}/dsp/gain_processor.cc" + "${_res_ra_dir}/dsp/mixer.cc" + "${_res_ra_dir}/dsp/mono_pole_filter.cc" + "${_res_ra_dir}/dsp/multi_channel_iir.cc" + "${_res_ra_dir}/dsp/near_field_processor.cc" + "${_res_ra_dir}/dsp/occlusion_calculator.cc" + "${_res_ra_dir}/dsp/partitioned_fft_filter.cc" + "${_res_ra_dir}/dsp/resampler.cc" + "${_res_ra_dir}/dsp/shoe_box_room.cc" + "${_res_ra_dir}/dsp/stereo_panner.cc" + "${_res_ra_dir}/dsp/utils.cc" + "${_res_ra_dir}/graph/ambisonic_binaural_decoder_node.cc" + "${_res_ra_dir}/graph/ambisonic_mixing_encoder_node.cc" + "${_res_ra_dir}/graph/buffered_source_node.cc" + "${_res_ra_dir}/graph/foa_rotator_node.cc" + "${_res_ra_dir}/graph/gain_mixer_node.cc" + "${_res_ra_dir}/graph/gain_node.cc" + "${_res_ra_dir}/graph/graph_manager.cc" + "${_res_ra_dir}/graph/hoa_rotator_node.cc" + "${_res_ra_dir}/graph/mixer_node.cc" + "${_res_ra_dir}/graph/mono_from_soundfield_node.cc" + "${_res_ra_dir}/graph/near_field_effect_node.cc" + "${_res_ra_dir}/graph/occlusion_node.cc" + "${_res_ra_dir}/graph/source_parameters_manager.cc" + "${_res_ra_dir}/graph/stereo_mixing_panner_node.cc" + "${_res_ra_dir}/node/processing_node.cc" + "${_res_ra_dir}/node/sink_node.cc" + "${_res_ra_dir}/node/source_node.cc" + "${_res_ra_dir}/utils/buffer_crossfader.cc" + "${_res_ra_dir}/utils/planar_interleaved_conversion.cc" + "${_res_ra_dir}/utils/sample_type_conversion.cc" + "${_res_ra_dir}/utils/sum_and_difference_processor.cc" +) + +set(_res_clang_warn_opts "") +if(CMAKE_C_COMPILER_ID MATCHES "Clang" OR CMAKE_CXX_COMPILER_ID MATCHES "Clang") + set(_res_clang_warn_opts "-Wno-#warnings") +endif() + +set_source_files_properties(${_res_pffft_srcs} PROPERTIES + COMPILE_DEFINITIONS "PFFFT_SIMD_DISABLE=1;_GNU_SOURCE=1;M_PI=3.14159265358979323846" + COMPILE_OPTIONS "-Wno-unused-function;-Wno-double-promotion;${_res_clang_warn_opts}" +) + +set_source_files_properties(${_res_cxx_srcs} PROPERTIES + COMPILE_DEFINITIONS "PFFFT_SIMD_DISABLE=1;DISABLE_SIMD=1;EIGEN_MPL2_ONLY=1;EIGEN_NO_DEBUG=1;EIGEN_DONT_VECTORIZE=1" + COMPILE_OPTIONS "-std=c++17;-fno-exceptions;-fno-rtti;-Wno-unused-function;-Wno-double-promotion;-Wno-deprecated-declarations;-Wno-sign-compare;${_res_clang_warn_opts}" +) + +target_sources(app PRIVATE + resonance_audio_ztest.c + resonance_audio_test_alloc.c + ${SOF_ROOT}/test/ztest/unit/common/sof_context.c + ${_res_mod_dir}/resonance_audio.c + ${_res_mod_dir}/resonance_audio-real.c + ${_res_mod_dir}/resonance_shims.c + ${_res_pffft_srcs} + ${_res_cxx_srcs} + ${SOF_ROOT}/src/audio/module_adapter/module_adapter.c + ${SOF_ROOT}/src/audio/module_adapter/module_adapter_ipc4.c + ${SOF_ROOT}/src/audio/module_adapter/module/generic.c + ${SOF_ROOT}/src/audio/buffers/comp_buffer.c + ${SOF_ROOT}/src/audio/buffers/audio_buffer.c + ${SOF_ROOT}/src/audio/source_api_helper.c + ${SOF_ROOT}/src/audio/sink_api_helper.c + ${SOF_ROOT}/src/audio/sink_source_utils.c + ${SOF_ROOT}/src/math/numbers.c + ${SOF_ROOT}/src/audio/audio_stream.c + ${SOF_ROOT}/src/audio/component.c + ${SOF_ROOT}/src/audio/data_blob.c + ${SOF_ROOT}/src/module/audio/source_api.c + ${SOF_ROOT}/src/module/audio/sink_api.c + ${SOF_ROOT}/src/ipc/ipc4/helper.c + ${SOF_ROOT}/src/ipc/ipc-common.c + ${SOF_ROOT}/src/ipc/ipc-helper.c + ${SOF_ROOT}/src/lib/objpool.c +) + +set_source_files_properties( + ${SOF_ROOT}/src/ipc/ipc4/helper.c + PROPERTIES COMPILE_OPTIONS "-Wno-unused-variable" +) + +sof_append_relative_path_definitions(app) diff --git a/test/ztest/unit/audio/resonance_audio/prj.conf b/test/ztest/unit/audio/resonance_audio/prj.conf new file mode 100644 index 000000000000..780f89752f13 --- /dev/null +++ b/test/ztest/unit/audio/resonance_audio/prj.conf @@ -0,0 +1,16 @@ +# SPDX-License-Identifier: BSD-3-Clause + +CONFIG_ZTEST=y +CONFIG_CPP=y +CONFIG_STD_CPP17=y +CONFIG_REQUIRES_FULL_LIBCPP=y +CONFIG_SOF_FULL_ZEPHYR_APPLICATION=n +CONFIG_LIBRARY=y +CONFIG_IPC_MAJOR_4=y +CONFIG_STATIC_PIPELINE=n +CONFIG_LOG=y +CONFIG_COMP_RESONANCE_AUDIO=y +CONFIG_COMP_RESONANCE_AUDIO_STUB=n +CONFIG_RESONANCE_AUDIO_ROOM_REVERB=n +CONFIG_FORMAT_S16LE=y +CONFIG_FORMAT_S32LE=y diff --git a/test/ztest/unit/audio/resonance_audio/resonance_audio_test_alloc.c b/test/ztest/unit/audio/resonance_audio/resonance_audio_test_alloc.c new file mode 100644 index 000000000000..003f56b189d4 --- /dev/null +++ b/test/ztest/unit/audio/resonance_audio/resonance_audio_test_alloc.c @@ -0,0 +1,63 @@ +// SPDX-License-Identifier: BSD-3-Clause + +#include + +#include +#include +#include +#undef malloc +#undef calloc +#undef realloc +#undef free +#include + +void *rmalloc_align(uint32_t flags, size_t bytes, uint32_t alignment) +{ + (void)flags; + (void)alignment; + return malloc(bytes); +} + +void *rmalloc(uint32_t flags, size_t bytes) +{ + (void)flags; + return malloc(bytes); +} + +void *rzalloc(uint32_t flags, size_t bytes) +{ + (void)flags; + return calloc(bytes, 1); +} + +void *rballoc_align(uint32_t flags, size_t bytes, uint32_t alignment) +{ + (void)flags; + (void)alignment; + return malloc(bytes); +} + +void rfree(void *ptr) +{ + free(ptr); +} + +void *sof_heap_alloc(struct k_heap *heap, uint32_t flags, size_t bytes, + size_t alignment) +{ + (void)heap; + (void)flags; + (void)alignment; + return malloc(bytes); +} + +void sof_heap_free(struct k_heap *heap, void *addr) +{ + (void)heap; + free(addr); +} + +struct k_heap *sof_sys_user_heap_get(void) +{ + return NULL; +} diff --git a/test/ztest/unit/audio/resonance_audio/resonance_audio_ztest.c b/test/ztest/unit/audio/resonance_audio/resonance_audio_ztest.c new file mode 100644 index 000000000000..a40c4a8d6e11 --- /dev/null +++ b/test/ztest/unit/audio/resonance_audio/resonance_audio_ztest.c @@ -0,0 +1,810 @@ +// SPDX-License-Identifier: BSD-3-Clause +/* + * Unit tests for the Google Resonance Audio SOF module. + */ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "resonance_audio.h" + +extern void sys_comp_module_resonance_audio_interface_init(void); + +struct res_test_ctx { + struct comp_dev *dev; + struct comp_buffer *in_buf; + struct comp_buffer *out_buf; + int rate; + int in_ch; + uint32_t fmt; +}; + +struct res_extended_cfg { + struct ipc4_base_module_cfg base_cfg; + struct ipc4_base_module_cfg_ext base_cfg_ext; + struct ipc4_input_pin_format input_pins[1]; + struct ipc4_output_pin_format output_pins[1]; +} __packed __aligned(4); + +static struct ipc4_audio_format make_ipc4_fmt(uint32_t rate, uint32_t fmt, uint16_t ch) +{ + uint32_t bits = (fmt == SOF_IPC_FRAME_S32_LE) ? IPC4_DEPTH_32BIT : IPC4_DEPTH_16BIT; + + return (struct ipc4_audio_format){ + .sampling_frequency = rate, + .depth = bits, + .ch_map = 0x76543210, + .ch_cfg = (ch == 1) ? IPC4_CHANNEL_CONFIG_MONO : + (ch == 2) ? IPC4_CHANNEL_CONFIG_STEREO : + (ch == 6) ? IPC4_CHANNEL_CONFIG_5_POINT_1 : IPC4_CHANNEL_CONFIG_QUATRO, + .interleaving_style = IPC4_CHANNELS_INTERLEAVED, + .channels_count = ch, + .valid_bit_depth = bits, + .s_type = IPC4_TYPE_SIGNED_INTEGER, + }; +} + +static struct comp_buffer *create_buf(struct comp_dev *dev, uint32_t queue_id, + uint32_t fmt, uint16_t ch, uint32_t rate, + uint32_t size_bytes, bool is_source) +{ + struct sof_ipc_buffer desc = { + .size = size_bytes, + }; + struct comp_buffer *buf = buffer_new(NULL, &desc, BUFFER_USAGE_NOT_SHARED); + + if (!buf) + return NULL; + + memset(buf->stream.addr, 0, size_bytes); + buf->stream.runtime_stream_params.id = queue_id << 16; + if (is_source) { + buf->source = calloc(1, sizeof(*buf->source)); + if (!buf->source) { + buffer_free(buf); + return NULL; + } + if (dev) + list_item_append(&buf->sink_list, &dev->bsource_list); + buf->source->state = COMP_STATE_PREPARE; + } else { + buf->sink = calloc(1, sizeof(*buf->sink)); + if (!buf->sink) { + buffer_free(buf); + return NULL; + } + if (dev) + list_item_append(&buf->source_list, &dev->bsink_list); + buf->sink->state = COMP_STATE_PREPARE; + } + + audio_stream_set_frm_fmt(&buf->stream, fmt); + audio_stream_set_channels(&buf->stream, ch); + audio_stream_set_rate(&buf->stream, rate); + return buf; +} + +static void destroy_ctx(struct res_test_ctx *ctx) +{ + if (!ctx) + return; + if (ctx->in_buf) + list_item_del(&ctx->in_buf->sink_list); + if (ctx->out_buf) + list_item_del(&ctx->out_buf->source_list); + if (ctx->dev) { + free(comp_mod(ctx->dev)->stream_params); + ctx->dev->drv->ops.free(ctx->dev); + } + if (ctx->in_buf) { + free(ctx->in_buf->source); + buffer_free(ctx->in_buf); + } + if (ctx->out_buf) { + free(ctx->out_buf->sink); + buffer_free(ctx->out_buf); + } + free(ctx); +} + +static int set_switch_ctl(struct processing_module *mod, uint16_t id, uint32_t val) +{ + const struct module_interface *ops = mod->dev->drv->adapter_ops; + struct { + struct sof_ipc4_control_msg_payload ctl; + struct sof_ipc4_ctrl_value_chan chan; + } __packed __aligned(4) msg = { + .ctl = { + .id = id, + .num_elems = RESONANCE_CTL_NUM_ELEMS, + }, + .chan = { .channel = 0, .value = val }, + }; + + return ops->set_configuration(mod, SOF_IPC4_SWITCH_CONTROL_PARAM_ID, + MODULE_CFG_FRAGMENT_SINGLE, 0, + (const uint8_t *)&msg, sizeof(msg), NULL, 0); +} + +static int get_switch_ctl(struct processing_module *mod, uint16_t id, uint32_t *val) +{ + const struct module_interface *ops = mod->dev->drv->adapter_ops; + struct { + struct sof_ipc4_control_msg_payload ctl; + struct sof_ipc4_ctrl_value_chan chan; + } __packed __aligned(4) msg = { + .ctl = { + .id = id, + .num_elems = RESONANCE_CTL_NUM_ELEMS, + }, + }; + uint32_t data_offset = 0; + int ret; + + ret = ops->get_configuration(mod, SOF_IPC4_SWITCH_CONTROL_PARAM_ID, + &data_offset, (uint8_t *)&msg, sizeof(msg)); + if (!ret && val) + *val = msg.chan.value; + return ret; +} + +static int set_pose_ctl(struct processing_module *mod, + const struct sof_resonance_pose_cfg *cfg) +{ + const struct module_interface *ops = mod->dev->drv->adapter_ops; + struct { + struct sof_ipc4_control_msg_payload ctl; + struct sof_resonance_pose_cfg cfg; + } __packed __aligned(4) msg; + + memset(&msg, 0, sizeof(msg)); + msg.ctl.id = 0; + msg.ctl.num_elems = sizeof(*cfg); + memcpy(&msg.cfg, cfg, sizeof(*cfg)); + + return ops->set_configuration(mod, SOF_IPC4_BYTES_CONTROL_PARAM_ID, + MODULE_CFG_FRAGMENT_SINGLE, 0, + (const uint8_t *)&msg, sizeof(msg), NULL, 0); +} + +static struct res_test_ctx *setup_res_ctx_chmap(int rate, int in_ch, uint32_t fmt, + uint32_t ch_map, uint32_t buf_frames, + int *prep_ret) +{ + const struct sof_uuid uuid = SOF_REG_UUID(resonance_audio); + const struct comp_driver *driver = comp_driver_find(&uuid, SOF_COMP_MODULE_ADAPTER); + struct res_test_ctx *ctx = calloc(1, sizeof(*ctx)); + struct processing_module *mod; + struct sof_source *sources[1]; + struct sof_sink *sinks[1]; + uint32_t samp_sz = (fmt == SOF_IPC_FRAME_S32_LE) ? 4 : 2; + uint32_t block_frames = 48; + uint32_t in_blk_bytes = block_frames * (uint32_t)in_ch * samp_sz; + uint32_t out_blk_bytes = block_frames * RESONANCE_OUT_CHANNELS * samp_sz; + struct ipc4_audio_format in_fmt = make_ipc4_fmt((uint32_t)rate, fmt, (uint16_t)in_ch); + struct ipc4_audio_format out_fmt = make_ipc4_fmt((uint32_t)rate, fmt, RESONANCE_OUT_CHANNELS); + + in_fmt.ch_map = ch_map; + struct res_extended_cfg mod_cfg = { + .base_cfg = { + .ibs = in_blk_bytes, + .obs = out_blk_bytes, + .audio_fmt = in_fmt, + }, + .base_cfg_ext = { + .nb_input_pins = 1, + .nb_output_pins = 1, + }, + .input_pins = { + { .pin_index = 0, .ibs = in_blk_bytes, .audio_fmt = in_fmt }, + }, + .output_pins = { + { .pin_index = 0, .obs = out_blk_bytes, .audio_fmt = out_fmt }, + }, + }; + struct ipc_config_process spec = { + .size = sizeof(mod_cfg), + .data = (const uint8_t *)&mod_cfg, + }; + struct comp_ipc_config ipc_cfg = { + .id = 1, + .proc_domain = COMP_PROCESSING_DOMAIN_DP, + .type = SOF_COMP_MODULE_ADAPTER, + .ipc_config_size = spec.size, + }; + int ret; + + zassert_not_null(driver, "resonance_audio driver not registered"); + zassert_not_null(ctx); + ctx->rate = rate; + ctx->in_ch = in_ch; + ctx->fmt = fmt; + + ctx->dev = driver->ops.create(driver, &ipc_cfg, &spec); + zassert_not_null(ctx->dev, "Failed to create resonance_audio component"); + + ctx->dev->frames = block_frames; + ctx->dev->period = 1000; + mod = comp_mod(ctx->dev); + mod->stream_params = calloc(1, sizeof(*mod->stream_params)); + zassert_not_null(mod->stream_params); + + ctx->in_buf = create_buf(ctx->dev, 0, fmt, in_ch, rate, + buf_frames * (uint32_t)in_ch * samp_sz, true); + ctx->out_buf = create_buf(ctx->dev, 0, fmt, RESONANCE_OUT_CHANNELS, rate, + buf_frames * RESONANCE_OUT_CHANNELS * samp_sz, false); + zassert_not_null(ctx->in_buf); + zassert_not_null(ctx->out_buf); + + sources[0] = audio_buffer_get_source(&ctx->in_buf->audio_buffer); + sinks[0] = audio_buffer_get_sink(&ctx->out_buf->audio_buffer); + source_set_min_available(sources[0], in_blk_bytes); + sink_set_min_free_space(sinks[0], out_blk_bytes); + + ret = mod->dev->drv->adapter_ops->prepare(mod, sources, 1, sinks, 1); + if (prep_ret) + *prep_ret = ret; + else + zassert_equal(ret, 0, "prepare() failed: %d", ret); + return ctx; +} + +static struct res_test_ctx *setup_res_ctx(int rate, int in_ch, uint32_t fmt) +{ + return setup_res_ctx_chmap(rate, in_ch, fmt, 0x76543210, 48 * 8, NULL); +} + +static void pump_frames_s16(struct res_test_ctx *ctx, const int16_t *in_pcm, + int16_t *out_pcm, int num_frames) +{ + struct processing_module *mod = comp_mod(ctx->dev); + struct sof_source *sources[1] = { audio_buffer_get_source(&ctx->in_buf->audio_buffer) }; + struct sof_sink *sinks[1] = { audio_buffer_get_sink(&ctx->out_buf->audio_buffer) }; + size_t in_bytes = (size_t)num_frames * ctx->in_ch * sizeof(int16_t); + size_t out_bytes = (size_t)num_frames * RESONANCE_OUT_CHANNELS * sizeof(int16_t); + struct audio_stream *in_s = &ctx->in_buf->stream; + struct audio_stream *out_s = &ctx->out_buf->stream; + uint8_t *wptr; + uint8_t *rptr; + size_t avail_sz; + int ret; + + wptr = audio_stream_get_wptr(in_s); + memcpy(wptr, in_pcm, in_bytes); + audio_stream_produce(in_s, in_bytes); + + zassert_true(mod->dev->drv->adapter_ops->is_ready_to_process(mod, sources, 1, sinks, 1)); + ret = mod->dev->drv->adapter_ops->process(mod, sources, 1, sinks, 1); + zassert_equal(ret, 0, "process() failed: %d", ret); + + avail_sz = audio_stream_get_avail_bytes(out_s); + zassert_equal(avail_sz, out_bytes, "expected %zu out bytes got %zu", out_bytes, avail_sz); + rptr = audio_stream_get_rptr(out_s); + memcpy(out_pcm, rptr, out_bytes); + audio_stream_consume(out_s, out_bytes); +} + +static void pump_frames_s32(struct res_test_ctx *ctx, const int32_t *in_pcm, + int32_t *out_pcm, int num_frames) +{ + struct processing_module *mod = comp_mod(ctx->dev); + struct sof_source *sources[1] = { audio_buffer_get_source(&ctx->in_buf->audio_buffer) }; + struct sof_sink *sinks[1] = { audio_buffer_get_sink(&ctx->out_buf->audio_buffer) }; + size_t in_bytes = (size_t)num_frames * ctx->in_ch * sizeof(int32_t); + size_t out_bytes = (size_t)num_frames * RESONANCE_OUT_CHANNELS * sizeof(int32_t); + struct audio_stream *in_s = &ctx->in_buf->stream; + struct audio_stream *out_s = &ctx->out_buf->stream; + uint8_t *wptr; + uint8_t *rptr; + int ret; + + wptr = audio_stream_get_wptr(in_s); + memcpy(wptr, in_pcm, in_bytes); + audio_stream_produce(in_s, in_bytes); + + ret = mod->dev->drv->adapter_ops->process(mod, sources, 1, sinks, 1); + zassert_equal(ret, 0, "process() failed: %d", ret); + + zassert_equal(audio_stream_get_avail_bytes(out_s), out_bytes); + rptr = audio_stream_get_rptr(out_s); + memcpy(out_pcm, rptr, out_bytes); + audio_stream_consume(out_s, out_bytes); +} + +ZTEST(resonance_audio_suite, test_stereo_binaural_asymmetry_s16) +{ + struct res_test_ctx *ctx = setup_res_ctx(48000, 2, SOF_IPC_FRAME_S16_LE); + int16_t in_blk[48 * 2]; + int16_t out_blk[48 * 2]; + double left_energy = 0.0; + double right_energy = 0.0; + int b, f; + + for (b = 0; b < 12; b++) { + for (f = 0; f < 48; f++) { + float s = sinf(2.0f * 3.14159265f * 1000.0f * + (float)(b * 48 + f) / 48000.0f); + in_blk[f * 2 + 0] = (int16_t)(s * 16000.0f); + in_blk[f * 2 + 1] = 0; + } + pump_frames_s16(ctx, in_blk, out_blk, 48); + if (b >= 4) { + for (f = 0; f < 48; f++) { + left_energy += (double)out_blk[f * 2 + 0] * out_blk[f * 2 + 0]; + right_energy += (double)out_blk[f * 2 + 1] * out_blk[f * 2 + 1]; + } + } + } + + zassert_true(left_energy > 1e6, "Expected non-zero binaural left energy"); + zassert_true(left_energy > right_energy * 1.5, + "Left virtual speaker should be louder in left ear (L=%f R=%f)", + left_energy, right_energy); + + destroy_ctx(ctx); +} + +ZTEST(resonance_audio_suite, test_surround_51_s32) +{ + struct res_test_ctx *ctx = setup_res_ctx(48000, 6, SOF_IPC_FRAME_S32_LE); + int32_t in_blk[48 * 6]; + int32_t out_blk[48 * 2]; + double left_energy = 0.0; + double right_energy = 0.0; + int b, f; + + for (b = 0; b < 10; b++) { + memset(in_blk, 0, sizeof(in_blk)); + for (f = 0; f < 48; f++) { + float s = sinf(2.0f * 3.14159265f * 800.0f * + (float)(b * 48 + f) / 48000.0f); + /* Drive Right Surround (channel 5 in AAC 5.1 layout: L,R,C,LFE,LS,RS) */ + in_blk[f * 6 + 5] = (int32_t)(s * 1073741824.0f); + } + pump_frames_s32(ctx, in_blk, out_blk, 48); + if (b >= 3) { + for (f = 0; f < 48; f++) { + double l = (double)(out_blk[f * 2 + 0] >> 16); + double r = (double)(out_blk[f * 2 + 1] >> 16); + + left_energy += l * l; + right_energy += r * r; + } + } + } + + zassert_true(right_energy > left_energy * 1.5, + "5.1 RS channel should produce higher right-ear energy (L=%f R=%f)", + left_energy, right_energy); + + destroy_ctx(ctx); +} + +ZTEST(resonance_audio_suite, test_foa_head_rotation_kcontrol) +{ + struct res_test_ctx *ctx = setup_res_ctx(48000, 4, SOF_IPC_FRAME_S16_LE); + struct processing_module *mod = comp_mod(ctx->dev); + struct sof_resonance_pose_cfg pose = { + .magic = RESONANCE_POSE_CFG_MAGIC, + .version = RESONANCE_POSE_CFG_VERSION, + .head_pos = { 0.0f, 0.0f, 0.0f }, + /* +90 deg yaw around world +Y axis: listener turns left, front source moves right. */ + .head_quat = { 0.0f, 0.7071068f, 0.0f, 0.7071068f }, + .master_volume = 1.0f, + .input_mode = 4, /* RESONANCE_MODE_FOA_AMBIX */ + .flags = BIT(2), /* enabled */ + }; + int16_t in_blk[48 * 4]; + int16_t out_blk[48 * 2]; + double left_e = 0.0, right_e = 0.0; + int b, f; + + zassert_equal(set_pose_ctl(mod, &pose), 0); + + for (b = 0; b < 12; b++) { + for (f = 0; f < 48; f++) { + float s = sinf(2.0f * 3.14159265f * 1000.0f * + (float)(b * 48 + f) / 48000.0f); + int16_t v = (int16_t)(s * 12000.0f); + /* AmbiX ACN: W=0, Y=1, Z=2, X=3 -> front plane wave has W + X */ + in_blk[f * 4 + 0] = v; + in_blk[f * 4 + 1] = 0; + in_blk[f * 4 + 2] = 0; + in_blk[f * 4 + 3] = v; + } + pump_frames_s16(ctx, in_blk, out_blk, 48); + if (b >= 4) { + for (f = 0; f < 48; f++) { + left_e += (double)out_blk[f * 2 + 0] * out_blk[f * 2 + 0]; + right_e += (double)out_blk[f * 2 + 1] * out_blk[f * 2 + 1]; + } + } + } + + zassert_true(fabs(left_e - right_e) > (left_e + right_e) * 0.2, + "90-deg head rotation should break L/R symmetry (L=%f R=%f)", + left_e, right_e); + + destroy_ctx(ctx); +} + +ZTEST(resonance_audio_suite, test_switch_controls_and_bypass) +{ + struct res_test_ctx *ctx = setup_res_ctx(48000, 2, SOF_IPC_FRAME_S16_LE); + struct processing_module *mod = comp_mod(ctx->dev); + uint32_t val = 99; + int16_t in_blk[48 * 2]; + int16_t out_blk[48 * 2]; + int f; + + zassert_equal(set_switch_ctl(mod, RESONANCE_CTL_ID_SPEAKER_MODE, 1), 0); + zassert_equal(get_switch_ctl(mod, RESONANCE_CTL_ID_SPEAKER_MODE, &val), 0); + zassert_equal(val, 1U); + + zassert_equal(set_switch_ctl(mod, RESONANCE_CTL_ID_ROOM_ENABLE, 1), 0); + zassert_equal(get_switch_ctl(mod, RESONANCE_CTL_ID_ROOM_ENABLE, &val), 0); + zassert_equal(val, 1U); + + zassert_equal(set_switch_ctl(mod, RESONANCE_CTL_ID_ENABLE, 0), 0); + zassert_equal(get_switch_ctl(mod, RESONANCE_CTL_ID_ENABLE, &val), 0); + zassert_equal(val, 0U); + + for (f = 0; f < 48; f++) { + in_blk[f * 2 + 0] = (int16_t)(1000 + f); + in_blk[f * 2 + 1] = (int16_t)(-1000 - f); + } + /* Flush initial 1-block silence lookahead FIFO, then verify clean passthrough. */ + pump_frames_s16(ctx, in_blk, out_blk, 48); + pump_frames_s16(ctx, in_blk, out_blk, 48); + zassert_equal(out_blk[0], in_blk[0]); + zassert_equal(out_blk[1], in_blk[1]); + + zassert_equal(mod->dev->drv->adapter_ops->reset(mod), 0); + destroy_ctx(ctx); +} + +ZTEST(resonance_audio_suite, test_dma_metadata_pin1_and_nonblocking) +{ + const struct sof_uuid uuid = SOF_REG_UUID(resonance_audio); + const struct comp_driver *driver = comp_driver_find(&uuid, SOF_COMP_MODULE_ADAPTER); + struct res_test_ctx *ctx = calloc(1, sizeof(*ctx)); + struct comp_buffer *meta_buf; + struct processing_module *mod; + struct sof_source *sources[2]; + struct sof_sink *sinks[1]; + uint32_t in_blk_bytes = 48 * 4 * sizeof(int16_t); + uint32_t out_blk_bytes = 48 * 2 * sizeof(int16_t); + uint32_t meta_blk_bytes = 48 * 2 * sizeof(int32_t); + struct ipc4_audio_format in_fmt = make_ipc4_fmt(48000, SOF_IPC_FRAME_S16_LE, 4); + struct ipc4_audio_format meta_fmt = make_ipc4_fmt(48000, SOF_IPC_FRAME_S32_LE, 2); + struct ipc4_audio_format out_fmt = make_ipc4_fmt(48000, SOF_IPC_FRAME_S16_LE, 2); + struct { + struct ipc4_base_module_cfg base_cfg; + struct ipc4_base_module_cfg_ext base_cfg_ext; + struct ipc4_input_pin_format input_pins[2]; + struct ipc4_output_pin_format output_pins[1]; + } __packed __aligned(4) mod_cfg = { + .base_cfg = { + .ibs = in_blk_bytes, + .obs = out_blk_bytes, + .audio_fmt = in_fmt, + }, + .base_cfg_ext = { + .nb_input_pins = 2, + .nb_output_pins = 1, + }, + .input_pins = { + { .pin_index = 0, .ibs = in_blk_bytes, .audio_fmt = in_fmt }, + { .pin_index = 1, .ibs = meta_blk_bytes, .audio_fmt = meta_fmt }, + }, + .output_pins = { + { .pin_index = 0, .obs = out_blk_bytes, .audio_fmt = out_fmt }, + }, + }; + struct ipc_config_process spec = { + .size = sizeof(mod_cfg), + .data = (const uint8_t *)&mod_cfg, + }; + struct comp_ipc_config ipc_cfg = { + .id = 2, + .proc_domain = COMP_PROCESSING_DOMAIN_DP, + .type = SOF_COMP_MODULE_ADAPTER, + .ipc_config_size = spec.size, + }; + struct sof_resonance_pose_dma_frame dma_pkt; + int16_t in_blk[48 * 4]; + int16_t out_blk[48 * 2]; + double left_e = 0.0, right_e = 0.0; + int b, f, ret; + + zassert_not_null(driver); + zassert_not_null(ctx); + ctx->rate = 48000; + ctx->in_ch = 4; + ctx->fmt = SOF_IPC_FRAME_S16_LE; + + ctx->dev = driver->ops.create(driver, &ipc_cfg, &spec); + zassert_not_null(ctx->dev); + ctx->dev->frames = 48; + ctx->dev->period = 1000; + mod = comp_mod(ctx->dev); + mod->stream_params = calloc(1, sizeof(*mod->stream_params)); + zassert_not_null(mod->stream_params); + + ctx->in_buf = create_buf(ctx->dev, 0, SOF_IPC_FRAME_S16_LE, 4, 48000, + in_blk_bytes * 8, true); + meta_buf = create_buf(ctx->dev, 1, SOF_IPC_FRAME_S32_LE, 2, 48000, + meta_blk_bytes * 8, true); + ctx->out_buf = create_buf(ctx->dev, 0, SOF_IPC_FRAME_S16_LE, 2, 48000, + out_blk_bytes * 8, false); + zassert_not_null(ctx->in_buf); + zassert_not_null(meta_buf); + zassert_not_null(ctx->out_buf); + + /* Pass Pin 1 before Pin 0 in sources[] to test IPC4 queue-ID resolution. */ + sources[0] = audio_buffer_get_source(&meta_buf->audio_buffer); + sources[1] = audio_buffer_get_source(&ctx->in_buf->audio_buffer); + sinks[0] = audio_buffer_get_sink(&ctx->out_buf->audio_buffer); + source_set_min_available(sources[0], RESONANCE_DMA_PACKET_BYTES); + source_set_min_available(sources[1], in_blk_bytes); + sink_set_min_free_space(sinks[0], out_blk_bytes); + + ret = mod->dev->drv->adapter_ops->prepare(mod, sources, 2, sinks, 1); + zassert_equal(ret, 0); + + /* Empty Pin 1 metadata must NOT block Pin 0 audio processing. */ + for (f = 0; f < 48 * 4; f++) + in_blk[f] = 0; + memcpy(audio_stream_get_wptr(&ctx->in_buf->stream), in_blk, in_blk_bytes); + audio_stream_produce(&ctx->in_buf->stream, in_blk_bytes); + zassert_true(mod->dev->drv->adapter_ops->is_ready_to_process(mod, sources, 2, sinks, 1)); + ret = mod->dev->drv->adapter_ops->process(mod, sources, 2, sinks, 1); + zassert_equal(ret, 0); + zassert_equal(audio_stream_get_avail_bytes(&ctx->out_buf->stream), out_blk_bytes); + audio_stream_consume(&ctx->out_buf->stream, out_blk_bytes); + + /* Feed 8-byte zero padding + 128-byte DMA pose frame (+90 deg yaw) into Pin 1. */ + memset(&dma_pkt, 0, sizeof(dma_pkt)); + dma_pkt.cfg.magic = RESONANCE_POSE_CFG_MAGIC; + dma_pkt.cfg.version = RESONANCE_POSE_CFG_VERSION; + dma_pkt.cfg.head_quat[1] = 0.7071068f; + dma_pkt.cfg.head_quat[3] = 0.7071068f; + dma_pkt.cfg.master_volume = 1.0f; + dma_pkt.cfg.input_mode = 4; + dma_pkt.cfg.flags = BIT(2); + dma_pkt.seq = 1; + dma_pkt.timestamp_us = 123456; + dma_pkt.checksum = resonance_pose_dma_checksum(&dma_pkt); + + memset(audio_stream_get_wptr(&meta_buf->stream), 0, 8); + audio_stream_produce(&meta_buf->stream, 8); + memcpy(audio_stream_get_wptr(&meta_buf->stream), &dma_pkt, sizeof(dma_pkt)); + audio_stream_produce(&meta_buf->stream, sizeof(dma_pkt)); + + for (b = 0; b < 12; b++) { + for (f = 0; f < 48; f++) { + float s = sinf(2.0f * 3.14159265f * 1000.0f * + (float)(b * 48 + f) / 48000.0f); + int16_t v = (int16_t)(s * 12000.0f); + + in_blk[f * 4 + 0] = v; + in_blk[f * 4 + 1] = 0; + in_blk[f * 4 + 2] = 0; + in_blk[f * 4 + 3] = v; + } + memcpy(audio_stream_get_wptr(&ctx->in_buf->stream), in_blk, in_blk_bytes); + audio_stream_produce(&ctx->in_buf->stream, in_blk_bytes); + ret = mod->dev->drv->adapter_ops->process(mod, sources, 2, sinks, 1); + zassert_equal(ret, 0); + memcpy(out_blk, audio_stream_get_rptr(&ctx->out_buf->stream), out_blk_bytes); + audio_stream_consume(&ctx->out_buf->stream, out_blk_bytes); + + if (b >= 4) { + for (f = 0; f < 48; f++) { + left_e += (double)out_blk[f * 2 + 0] * out_blk[f * 2 + 0]; + right_e += (double)out_blk[f * 2 + 1] * out_blk[f * 2 + 1]; + } + } + } + + zassert_equal(audio_stream_get_avail_bytes(&meta_buf->stream), 0U, + "Pin 1 metadata buffer must be completely drained"); + zassert_true(fabs(left_e - right_e) > (left_e + right_e) * 0.2, + "DMA +90-deg head rotation should break L/R symmetry (L=%f R=%f)", + left_e, right_e); + + list_item_del(&meta_buf->sink_list); + free(meta_buf->source); + buffer_free(meta_buf); + destroy_ctx(ctx); +} + +ZTEST(resonance_audio_suite, test_pose_input_mode_auto_reset) +{ + struct res_test_ctx *ctx = setup_res_ctx(48000, 2, SOF_IPC_FRAME_S16_LE); + struct processing_module *mod = comp_mod(ctx->dev); + struct sof_resonance_pose_cfg cfg = { + .magic = RESONANCE_POSE_CFG_MAGIC, + .version = RESONANCE_POSE_CFG_VERSION, + .head_quat = { 0.0f, 0.0f, 0.0f, 1.0f }, + .master_volume = 1.0f, + .input_mode = 0, /* explicit MONO */ + .flags = BIT(2), + }; + int16_t in_blk[48 * 2]; + int16_t out_blk[48 * 2]; + double energy = 0.0; + int f; + + zassert_equal(set_pose_ctl(mod, &cfg), 0); + cfg.input_mode = RESONANCE_INPUT_MODE_AUTO; + zassert_equal(set_pose_ctl(mod, &cfg), 0); + zassert_equal(mod->dev->drv->adapter_ops->reset(mod), 0); + + for (f = 0; f < 48; f++) { + in_blk[f * 2 + 0] = 10000; + in_blk[f * 2 + 1] = -5000; + } + pump_frames_s16(ctx, in_blk, out_blk, 48); + pump_frames_s16(ctx, in_blk, out_blk, 48); + for (f = 0; f < 48 * 2; f++) + energy += fabs((double)out_blk[f]); + zassert_true(energy > 1000.0, "Auto reset to stereo should produce audio"); + + destroy_ctx(ctx); +} + +ZTEST(resonance_audio_suite, test_up_down_mixer_51_chmap_and_invalid_chmap) +{ + /* up_down_mixer 5.1 ch_map: L(0), C(1), R(2), LS(3), RS(4), LFE(7) = 0xFF743210 */ + struct res_test_ctx *ctx = setup_res_ctx_chmap(48000, 6, SOF_IPC_FRAME_S16_LE, + 0xFF743210, 48 * 8, NULL); + struct res_test_ctx *bad_ctx; + int16_t in_blk[48 * 6]; + int16_t out_blk[48 * 2]; + double left_e = 0.0, right_e = 0.0; + int bad_ret = 0; + int b, f; + + memset(in_blk, 0, sizeof(in_blk)); + for (b = 0; b < 8; b++) { + for (f = 0; f < 48; f++) { + float s = sinf(2.0f * 3.14159265f * 1000.0f * + (float)(b * 48 + f) / 48000.0f); + /* Drive slot 1 (Center in L,C,R,LS,RS,LFE). If unremapped, */ + /* Center would go to Right (30/-30 deg) instead of symmetric Center. */ + in_blk[f * 6 + 1] = (int16_t)(s * 14000.0f); + } + pump_frames_s16(ctx, in_blk, out_blk, 48); + if (b >= 3) { + for (f = 0; f < 48; f++) { + left_e += (double)out_blk[f * 2 + 0] * out_blk[f * 2 + 0]; + right_e += (double)out_blk[f * 2 + 1] * out_blk[f * 2 + 1]; + } + } + } + zassert_true(left_e > 1e7 && right_e > 1e7, "Remapped Center must render audio"); + zassert_true(fabs(left_e - right_e) < (left_e + right_e) * 0.05, + "Remapped Center must be symmetric (L=%f R=%f)", left_e, right_e); + destroy_ctx(ctx); + + bad_ctx = setup_res_ctx_chmap(48000, 6, SOF_IPC_FRAME_S16_LE, + 0xFF000000, 48 * 8, &bad_ret); + zassert_equal(bad_ret, -EINVAL, "Incomplete 6ch map must be rejected"); + destroy_ctx(bad_ctx); +} + +ZTEST(resonance_audio_suite, test_large_batch_512_frames_no_gap) +{ + struct res_test_ctx *ctx = setup_res_ctx_chmap(48000, 2, SOF_IPC_FRAME_S16_LE, + 0xFFFFFF10, 1024, NULL); + struct processing_module *mod = comp_mod(ctx->dev); + struct sof_source *sources[1]; + struct sof_sink *sinks[1]; + int16_t in_blk[512 * 2]; + int16_t out_blk[512 * 2]; + int total_out = 0; + int zero_run = 0, max_zero_run = 0; + int f, iter; + + sources[0] = audio_buffer_get_source(&ctx->in_buf->audio_buffer); + sinks[0] = audio_buffer_get_sink(&ctx->out_buf->audio_buffer); + + for (f = 0; f < 512; f++) { + float s = sinf(2.0f * 3.14159265f * 1000.0f * (float)f / 48000.0f); + int16_t v = (int16_t)(s * 12000.0f); + + in_blk[f * 2 + 0] = v; + in_blk[f * 2 + 1] = v; + } + /* Bypass so output exactly reflects lookahead + continuous signal with zero gaps. */ + zassert_equal(set_switch_ctl(mod, RESONANCE_CTL_ID_ENABLE, 0), 0); + + memcpy(audio_stream_get_wptr(&ctx->in_buf->stream), in_blk, sizeof(in_blk)); + audio_stream_produce(&ctx->in_buf->stream, sizeof(in_blk)); + + for (iter = 0; iter < 4 && total_out < 512; iter++) { + uint32_t avail_out; + int n_got; + + zassert_equal(mod->dev->drv->adapter_ops->process(mod, sources, 1, sinks, 1), 0); + avail_out = audio_stream_get_avail_bytes(&ctx->out_buf->stream); + if (avail_out > 0) { + n_got = (int)(avail_out / (2 * sizeof(int16_t))); + memcpy(&out_blk[total_out * 2], + audio_stream_get_rptr(&ctx->out_buf->stream), avail_out); + audio_stream_consume(&ctx->out_buf->stream, avail_out); + total_out += n_got; + } + } + + zassert_equal(total_out, 512, "Expected 512 output frames, got %d", total_out); + /* Skip initial 48-frame lookahead silence, then verify no >= 8-frame zero gap exists. */ + for (f = 48; f < 512; f++) { + if (out_blk[f * 2] == 0 && out_blk[f * 2 + 1] == 0) { + zero_run++; + if (zero_run > max_zero_run) + max_zero_run = zero_run; + } else { + zero_run = 0; + } + } + zassert_true(max_zero_run < 8, + "Detected unexpected %d-frame silent gap after 512-frame batch", + max_zero_run); + destroy_ctx(ctx); +} + +ZTEST(resonance_audio_suite, test_multi_instance_isolation) +{ + struct res_test_ctx *ctx_a = setup_res_ctx(48000, 4, SOF_IPC_FRAME_S16_LE); + struct res_test_ctx *ctx_b = setup_res_ctx(48000, 6, SOF_IPC_FRAME_S16_LE); + int16_t in_a[48 * 4]; + int16_t out_a[48 * 2]; + double energy = 0.0; + int b, f; + + /* Free instance B while keeping instance A alive and running. */ + destroy_ctx(ctx_b); + + memset(in_a, 0, sizeof(in_a)); + for (b = 0; b < 6; b++) { + for (f = 0; f < 48; f++) { + in_a[f * 4 + 0] = (int16_t)(8000.0f * + sinf(2.0f * 3.14159265f * 1000.0f * (float)(b * 48 + f) / 48000.0f)); + } + pump_frames_s16(ctx_a, in_a, out_a, 48); + if (b >= 2) { + for (f = 0; f < 48 * 2; f++) + energy += (double)out_a[f] * out_a[f]; + } + } + zassert_true(energy > 1e6, "Instance A must remain intact after freeing instance B"); + destroy_ctx(ctx_a); +} + +static void *resonance_suite_setup(void) +{ + sys_comp_module_resonance_audio_interface_init(); + return NULL; +} + +ZTEST_SUITE(resonance_audio_suite, NULL, resonance_suite_setup, NULL, NULL, NULL); diff --git a/test/ztest/unit/audio/resonance_audio/testcase.yaml b/test/ztest/unit/audio/resonance_audio/testcase.yaml new file mode 100644 index 000000000000..aa80963b73cf --- /dev/null +++ b/test/ztest/unit/audio/resonance_audio/testcase.yaml @@ -0,0 +1,16 @@ +# SPDX-License-Identifier: BSD-3-Clause + +common: + tags: + - SOF + - unit_test + - audio + - resonance_audio + integration_platforms: + - native_sim + arch_exclude: xtensa + +tests: + sof.unit.audio.resonance_audio: + platform_allow: + - native_sim diff --git a/tools/rimage/config/ptl.toml.h b/tools/rimage/config/ptl.toml.h index cfa07c7c8806..ec40b07ae12b 100644 --- a/tools/rimage/config/ptl.toml.h +++ b/tools/rimage/config/ptl.toml.h @@ -205,6 +205,10 @@ index = __COUNTER__ #include