Sound Dose Evaluator Architecture#
The Sound Dose Evaluator is an autonomous, real-time auditory safety subsystem in Sound Open Firmware (SOF). Designed to comply with international consumer audio health regulations—specifically IEC 62368-1 and WHO-ITU H.870—the Sound Dose module continuously analyzes audio streams routed to headphones and headsets. It computes spectral energy exposure in real time, translates digital audio levels into physical sound pressure levels (\(\text{dBSPL}\)), tracks cumulative exposure across rolling temporal windows, and autonomously reports exposure metrics to the host operating system while providing artifact-free dynamic attenuation when safe exposure limits are exceeded.
Auditory Health Physiology & International Regulatory Mandates#
Prolonged exposure to high sound pressure levels induces irreversible physiological damage to the human auditory system. The human inner ear contains the cochlea, a fluid-filled, spiral-shaped cavity lined with the basilar membrane. Transduction of acoustic vibrations into neural impulses is performed by approximately 15,000 hair cells:
Inner Hair Cells (IHCs): Primary sensory transducers that release neurotransmitters to auditory nerve fibers in response to stereocilia deflection.
Outer Hair Cells (OHCs): Electromotile amplifiers that actively alter their length via the motor protein prestin, providing up to 50 dB of mechanical amplification for quiet sounds and sharpening frequency selectivity.
When exposed to excessive acoustic energy, outer hair cells undergo intense metabolic overload. This causes severe oxidative stress, marked accumulation of reactive oxygen species (ROS), intracellular calcium excitotoxicity, mitochondrial swelling, and structural rupture of stereocilia tip-links. While moderate over-exposure leads to a Temporary Threshold Shift (TTS) that recovers over several hours as cellular homeostasis is restored, repeated or severe acoustic trauma results in permanent hair cell apoptosis and spiral ganglion synaptic decoupling—causing irreversible Permanent Threshold Shift (PTS), high-frequency sensorineural hearing loss, and chronic tinnitus.
Figure 126 Figure 167: Auditory Perception & Hearing Damage Risk Curve: Sound Pressure Level vs Maximum Safe Exposure Time (IEC 62368-1 / WHO-ITU H.870)#
Calculated Sound Dose (CSD) and the 3 dB Exchange Rule#
To protect consumers against premature hearing loss, the International Electrotechnical Commission (IEC 62368-1 Clause 10.6) and the World Health Organization together with the International Telecommunication Union (WHO-ITU H.870) established standardized personal audio safety requirements:
Calculated Sound Dose (CSD): The total acoustic energy absorbed by the human ear, integrated over a rolling 7-day window. A reference weekly dose of 100% CSD corresponds to continuous exposure of 80 dBA for 40 hours per week, representing an acoustic energy dosage of:
\[\text{Dose}_{\text{ref}} = (20\,\mu\text{Pa} \cdot 10^{80/20})^2 \cdot 40\,\text{hours} \approx 1.6\,\text{Pa}^2\text{h}\]The 3 dB Equal Energy Exchange Principle: Acoustic sound intensity doubles with every \(+3\,\text{dB}\) increase. Therefore, the permissible exposure duration before reaching 100% CSD is halved for every 3 dB increase in sound pressure level:
\[T_{\text{safe}}(\text{MEL}) = 40\,\text{hours} \cdot 10^{\frac{80 - \text{MEL}}{10}}\]Mandatory Protective Actions: * Advisory Warning (80% CSD): The system alerts the user that they are approaching their maximum weekly sound exposure budget. * Mandatory Attenuation (100% CSD): The audio framework automatically engages a dynamic volume limiter, attenuating playback down to a safe exposure level (< 80 dBA). The user cannot override this attenuation without acknowledging a formal hearing hazard prompt. * Instantaneous Exposure Cap: Listening levels exceeding 100 dBA are strictly restricted in continuous duration to prevent acute acoustic trauma.
IEC 61672-1 Class 1 A-Weighting Filter Cascade#
The human ear does not perceive all acoustic frequencies with equal sensitivity. As demonstrated by the Robinson-Dadson and ISO 226 equal-loudness contours, human hearing is significantly less sensitive at low frequencies (< 500 Hz) and ultra-high frequencies (> 10 kHz), while exhibiting peak resonance between 2 kHz and 4 kHz due to the acoustic dimensions of the ear canal.
To ensure that the calculated sound energy reflects true physiological hearing hazard, raw digital PCM samples must be processed through an A-weighting frequency curve defined by IEC 61672-1.
Continuous-Domain Transfer Function#
The standardized continuous-time A-weighting frequency response \(R_A(f)\) is defined analytically as:
The weighting in decibels \(A(f)\) is normalized to 0 dB at 1000 Hz:
Figure 127 Figure 168: IEC 61672-1 Class 1 A-Weighting Acoustic Filter Frequency Response Curve & Direct Form I Biquad Cascade#
Discrete Direct Form I Realization in SOF#
In SOF, the continuous A-weighting curve is bilinear-transformed and mapped into a sequence of cascaded second-order IIR biquad sections. SOF adopts the Direct Form I (DF1) structure because it exhibits superior numerical immunity against coefficient quantization and limit cycles in fixed-point DSP arithmetic:
Key structural characteristics:
Pre-Computed Header Blobs: To avoid runtime transcendental math on the DSP, filter coefficient sets are pre-computed for standard audio rates and packaged into firmware headers:
sound_dose_iir_48k.h: Optimized for 48 kHz operation.sound_dose_iir_44k.h: Optimized for 44.1 kHz operation.
Per-Channel State Isolation: Dedicated delay registers and history buffers (
cd->delay_lines) are dynamically allocated for each audio channel (up toPLATFORM_MAX_CHANNELS), preventing cross-channel phase contamination.
Fixed-Point Real-Time Energy Accumulation Architecture#
The Sound Dose module processes audio frames in fixed-point representation. Depending on the pipeline configuration, samples arrive in either signed 16-bit (S16_LE in \(Q1.15\) format) or signed 32-bit (S32_LE in \(Q1.31\) format).
Sample Processing and Squaring#
For each incoming audio frame:
Protective Gain Application: The input sample \(x[n]\) is scaled by the module’s active internal gain \(g \in Q2.30\):
\[x_{\text{scaled}}[n] = \text{sat}_{16}\left( \frac{g \cdot x[n]}{2^{30}} \right)\]This scaled sample is written directly to the output sink buffer, ensuring that protective gain adjustments apply to the listening path without latency.
A-Weighting Filtering: In parallel, \(x_{\text{scaled}}[n]\) is passed through the channel’s Direct Form I biquad cascade, yielding the frequency-weighted sample \(y_A[n]\).
Instantaneous Power Calculation: The weighted sample is squared to determine instantaneous acoustic power:
\[P_i[n] = y_A[n] \cdot y_A[n]\]In fixed-point math, multiplying two \(Q1.15\) numbers produces a \(Q2.30\) result. For 32-bit audio, multiplying two \(Q1.31\) numbers yields a \(Q2.62\) intermediate result.
64-Bit Energy Accumulation#
To eliminate numerical overflow during prolonged listening, the instantaneous power values are accumulated across time in a dedicated 64-bit signed integer for each channel:
A 64-bit integer provides massive dynamic headroom. Even if full-scale white noise or square waves are played continuously at 48 kHz, accumulating \(2^{30}\) power units per sample over a full 1-second period (48,000 samples) consumes only:
This mathematical headroom guarantees that accumulator overflow is physically impossible.
1-Second Periodic Trigger & Logarithmic Mean Conversion#
The Sound Dose Evaluator operates on a synchronized 1-second reporting window. The DSP tracks total processed frames within the current accumulation epoch (cd->frames_count). When cd->frames_count >= cd->report_count (e.g. 48,000 frames at 48 kHz), the 1-second conversion routine is triggered.
Figure 128 Figure 169: Fixed-Point 64-Bit Energy Integration and Logarithmic dBFS/MEL Conversion Flowchart#
The Logarithmic Math Pipeline#
Converting a 64-bit integer energy sum into standardized decibels relative to full scale (\(\text{dBFS}\)) requires careful mathematical scaling in fixed-point arithmetic:
Downscaling for 32-Bit Logarithm: The total accumulated energy \(E_{\text{sum}} = \sum_{\text{ch}} E_{\text{ch}}\) is right-shifted by 19 bits (
SOUND_DOSE_ENERGY_SHIFT) to ensure it fits comfortably within an unsigned 32-bit integer:\[\text{arg}_{\text{log}} = \max\left( 1, \left\lfloor \frac{E_{\text{sum}}}{2^{19}} \right\rfloor \right)\]Base-2 Logarithm: The DSP invokes
base2_logarithm(arg_log), which utilizes binary leading-zero count and polynomial approximation to produce \(\log_2(\text{arg}_{\text{log}})\) in signed \(Q16.16\) fixed-point format.Fixed Offset Compensation: Because the original samples were in \(Q1.15\) (squared to \(Q2.30\)) and downshifted by 19 bits, the logarithm must be corrected by:
\[\Delta_{\text{scale}} = 65536 \cdot (19 - 30) = -11 \cdot 65536\]Mean Power Normalization: To convert accumulated total energy over the 1-second epoch into mean continuous power per sample, the logarithm of the reciprocal frame count is added:
\[\Delta_{\text{mean}} = \log_2\left( \frac{1}{f_s} \right) \cdot 2^{16}\]where \(\Delta_{\text{mean}} = -1019134\) for 48 kHz and \(-1011122\) for 44.1 kHz.
Base-2 to Decibel Transformation: Decibels are base-10 logarithmic measures (\(10 \log_{10}(P)\)). The base-2 logarithm is converted via multiplication with \(\frac{10}{\log_2(10)}\) in \(Q29\) fixed-point format:
\[\text{multiplier} = \left\lfloor \frac{10}{\log_2(10)} \cdot 2^{29} \right\rfloor = 1616142483\]Filter and Sine Reference Offsets: * Filter Offset: \(+3.00\,\text{dB}\) (
SOUND_DOSE_WEIGHT_FILTERS_OFFS_Q16) accounts for insertion gain characteristics of the discrete A-weighting filter cascade. * Full-Scale Offset: \(+3.01\,\text{dB}\) (SOUND_DOSE_DFBS_OFFS_Q16) ensures that a full-scale digital sine wave (\(0\,\text{dBFS}\)) computes precisely to \(0.00\,\text{dBFS}\) RMS power.Binaural Multichannel Correction: Summing power across multiple channels inflates total acoustic energy. In a headphone listening scenario, each ear receives acoustic power from its corresponding channel. To model binaural loudness perception accurately, a correction factor of \(-1.5\,\text{dB}\) per channel (
SOUND_DOSE_MEL_CHANNELS_SUM_FIX) is applied, subtracting \(-3.0\,\text{dB}\) for standard stereo streams.
Momentary Exposure Level (MEL) Derivation & Acoustic Calibration#
While digital decibels relative to full scale (\(\text{dBFS}\)) quantify the electrical signal inside the DSP, auditory health is dictated by physical sound pressure level in air (\(\text{dBSPL}\)) at the user’s eardrum.
The Momentary Exposure Level (MEL) is the 1-second A-weighted sound pressure level (\(\text{dBA}\)) delivered by the headphones. In SOF, all exposure levels are stored as centi-decibels (\(0.01\,\text{dB}\) precision, where \(85.00\,\text{dB} = 8500\)).
The MEL is derived directly from three distinct variables:
Parameter |
Topology ID / Control |
Unit |
Functional Description |
|---|---|---|---|
|
Telemetry Payload |
centi-dBFS |
1-second RMS A-weighted digital signal level (\(-100.00\) to \(0.00\,\text{dBFS}\)). |
|
Setup Parameter (0) |
centi-dB |
Electro-acoustic sensitivity of DAC, power amplifier, and target headphone transducer (e.g. \(0\,\text{dBFS} = 100\,\text{dBSPL}\) at maximum volume). |
|
Volume Parameter (1) |
centi-dB |
Dynamic attenuation introduced by user-facing volume sliders relative to maximum gain (e.g. \(-12.00\,\text{dB} = -1200\)). |
|
Gain Parameter (2) |
centi-dB |
Autonomous protective attenuation commanded by the host dose daemon (e.g. \(-6.00\,\text{dB}\)). |
High-Precision Stream Time Tracking#
The Sound Dose module generates microsecond-accurate stream timestamps to allow host exposure daemons to correlate sound exposure with real-world clocks:
To prevent 64-bit integer division in the DSP’s high-priority execution context, the rate reciprocal is pre-calculated in \(Q26\) fixed-point format (SOUND_DOSE_1M_OVER_48K_Q26). Multiplication is performed in split 32x32-to-64-bit arithmetic to provide 96-bit internal precision, eliminating timestamp jitter or drift across weeks of continuous playback.
Figure 129 Figure 170: Calculated Sound Dose (CSD) Accumulation & 7-Day Rolling Weekly Exposure Dose Budgeting#
Asynchronous IPC4 Event Notification & Host Exposure Management#
Traditional audio telemetry frameworks rely on periodic host polling, forcing the host CPU to wake up frequently and query hardware registers over memory buses. This wastes power and degrades battery life on mobile devices.
The Sound Dose module utilizes an unsolicited event notification model under the SOF IPC4 framework:
Autonomous Periodic Notification: Exactly once every second, the DSP constructs an unsolicited IPC message:
Notification Type:
SOF_IPC4_MODULE_NOTIFICATIONGlobal Classification:
SOF_IPC4_GLB_NOTIFICATIONEvent ID:
SOF_AUDIO_FEATURE_SOUND_DOSE_MELTarget: Firmware-generated message directed to host mailbox
Payload Encapsulation: The message encapsulates the
struct sof_audio_featurecontainer holding the activestruct sof_sound_doserecord:stream_time_us: 64-bit microsecond timestampmel_value: 1-second Momentary Exposure Level (centi-dBA)dbfs_value: 1-second digital audio level (centi-dBFS)current_sens_dbfs_dbspl: Configured acoustic sensitivitycurrent_volume_offset: Active volume attenuationcurrent_gain: Current autonomous protection gain
Figure 130 Figure 171: Sound Open Firmware Sound Dose Processing Pipeline & Periodic Asynchronous Notification State Machine#
Host Sound Dose Daemon Integration#
In modern operating systems (such as Linux with PipeWire, ChromeOS, or Android Audio HAL), an unprivileged user-space Sound Dose Daemon listens on the ALSA control event interface for SOF_AUDIO_FEATURE_SOUND_DOSE_MEL notifications:
Exposure Integration: When a notification arrives, the daemon reads
mel_valueand adds the 1-second energy slice to rolling daily and weekly exposure databases.Persistent Tracking: Because headphones may be unplugged and plugged back in, or the device rebooted, the host daemon maintains persistent logs across sessions to guarantee continuous 7-day CSD tracking.
Closed-Loop Feedback: If the weekly dose reaches 100%, the daemon issues a hardware control command back to the DSP to clamp playback loudness.
Closed-Loop Dynamic Protection: Smooth Attenuation Ramping#
When the user exceeds their safe exposure threshold, the system must reduce listening volume. However, abruptly clamping digital gain creates audible clicks, pops, and sudden discontinuities that severely degrade user experience. Furthermore, if volume reduction is implemented merely by moving the standard user mixer slider, the user can easily drag the slider back up, defeating auditory safety safeguards.
The Sound Dose module resolves both challenges through autonomous internal attenuation paired with smooth exponential gain ramping.
Decoupled Protection Gain Control#
Sound Dose provides a dedicated byte control (SOF_SOUND_DOSE_GAIN_PARAM_ID) that accepts attenuation requests between \(-100.00\,\text{dB}\) and \(0.00\,\text{dB}\). This control is intentionally hidden from standard user-accessible ALSA mixer volume controls. When the host exposure daemon detects dangerous exposure levels, it issues an attenuation command (e.g. \(-6.00\,\text{dB}\)) directly to this parameter. The user volume slider remains intact, but the effective output is clamped.
Exponential Gain Slew Ramping#
To transition smoothly between gain targets without audio artifacts, the DSP applies an exponential slew rate of 0.05 dB per frame in \(Q2.30\) fixed-point arithmetic:
Ramping Down (Attenuation): When a lower target gain is commanded (
new_gain < gain), the gain is scaled downward each frame:\[g[n] = \max\left( g_{\text{target}},\, \frac{g[n-1] \cdot \text{GAIN\_DOWN}}{2^{30}} \right)\]where:
\[\text{GAIN\_DOWN} = \left\lfloor 10^{-0.05 / 20} \cdot 2^{30} \right\rfloor = 1067578625\]Ramping Up (Recovery): When the user or daemon restores gain (
new_gain > gain), the gain is scaled upward each frame:\[g[n] = \min\left( g_{\text{target}},\, \frac{g[n-1] \cdot \text{GAIN\_UP}}{2^{30}} \right)\]where:
\[\text{GAIN\_UP} = \left\lfloor 10^{+0.05 / 20} \cdot 2^{30} \right\rfloor = 1079940603\]
At a 48 kHz sampling rate, ramping gain down by 6 dB requires 120 frames, completing in just 2.5 milliseconds—fast enough to protect the user’s ears immediately, yet completely free of audible clicks or pops.
Figure 131 Figure 172: Closed-Loop Host-DSP Protective Feedback: Dynamic Gain Attenuation and Volume Limiting#
ALSA Topology 2 Integration & End-to-End Headphone Protection Audio Graph#
In ALSA Topology 2, the Sound Dose module is defined under Class.Widget."sound_dose" with its unique UUID. It is typically positioned as the final processing block in the playback pipeline immediately prior to the DAI Copier, ensuring that all upstream volume adjustments, software equalizers, and dynamic range compressors are accounted for in the dose evaluation.
Widget Definition#
The widget class is defined in topology2/include/components/sound_dose.conf:
Class.Widget."sound_dose" {
DefineAttribute."index" { type "integer" }
DefineAttribute."instance" { type "integer" }
<include/components/widget-common.conf>
attributes {
!constructor [ "index", "instance" ]
!mandatory [
"num_input_pins",
"num_output_pins",
"num_input_audio_formats",
"num_output_audio_formats"
]
!immutable [ "uuid", "type" ]
unique "instance"
}
uuid "7c:9d:3f:a4:75:ea:d5:44:94:2d:96:79:91:a3:38:09"
type "effect"
no_pm "true"
num_input_pins 1
num_output_pins 1
}
Topology Controls Architecture#
The Sound Dose widget exposes four specialized byte controls defined in sound_dose_controls_playback.conf:
Bytes Control 1 (Setup): Configures
sens_dbfs_dbspl(\(-10.00\) to \(+130.00\,\text{dB}\)). Usually loaded at boot viasetup_sens_100db.conf.Bytes Control 2 (Volume): Reports user volume slider changes (\(-100.00\) to \(+40.00\,\text{dB}\)).
Bytes Control 3 (Gain): Dynamic attenuation control (\(-100.00\) to \(0.00\,\text{dB}\)). Used by host daemons to enforce safe listening levels.
Bytes Control 4 (Payload): Telemetry channel carrying the active
struct sof_sound_doserecord.
Figure 132 Figure 173: End-to-End Headphone Protection Audio Graph: From Host Media Stream and Sound Dose Widget to Headphone Output#
Developer Calibration & Diagnostic Runbook#
When bringing up Sound Dose on a new hardware platform or validating compliance with IEC 62368-1:
Acoustic Sensitivity Calibration: Connect the target reference headphones to a calibrated artificial ear fixture (e.g. an IEC 60318-4 ear simulator or Head and Torso Simulator (HATS)). Play a 1 kHz sinusoidal test tone at \(0\,\text{dBFS}\) with the system volume set to 100%. Record the measured acoustic output in \(\text{dBSPL}\) (for example, \(102.5\,\text{dBSPL}\)). Configure this baseline sensitivity in the topology or via ALSA controls:
# Set sensitivity to 102.5 dB (10250 centi-dB) amixer -c 0 cset name='Headphone Sound Dose setup bytes' 0x72,0x28,0x00,0x00
Telemetry Verification: Monitor the 1-second asynchronous IPC4 notification stream using DSP logger utilities (see DSP Telemetry, Logging & Traces):
# Stream real-time DSP trace logs sof-logger -t -f 1 | grep -i "sound_dose"
Verify that
Time,dBFS, andMELincrement predictably every 1 second:comp_info: sound_dose: Time 42 dBFS -1800 MEL 8450
Dynamic Limiter Validation: Inject an attenuation command via
amixerwhile monitoring audio playback:# Force dynamic attenuation of -10 dB (-1000 centi-dB) amixer -c 0 cset name='Headphone Sound Dose gain bytes' 0x18,0xfc,0x00,0x00
Listen for clean, artifact-free attenuation without clicks or pops, verifying that the slew rate ramps smoothly at 0.05 dB per frame.
Upstream Source Code References#
Component Core & Generic Processing:
src/audio/sound_dose/sound_dose.c: Module adapter lifecycle (
init,prepare,process,reset,free), gain ramping, and frame scheduling.src/audio/sound_dose/sound_dose-generic.c: Real-time fixed-point sample processing, Direct Form I filtering, 64-bit energy accumulation, and logarithmic conversion.
src/audio/sound_dose/sound_dose.h: Component private structures, filter constants, fixed-point shifts, and math coefficients.
src/include/user/sound_dose.h: ABI definitions, control parameter IDs, and telemetry structures.
IPC4 Notification & Control Interface:
src/audio/sound_dose/sound_dose-ipc4.c: Unsolicited IPC4 notification constructor and large config handlers.
src/include/user/audio_feature.h: Standard audio feature container definitions.
Pre-Computed Filter Coefficients:
src/audio/sound_dose/sound_dose_iir_48k.h: Pre-calculated IEC 61672-1 Class 1 A-weighting coefficients for 48 kHz.
src/audio/sound_dose/sound_dose_iir_44k.h: Pre-calculated IEC 61672-1 Class 1 A-weighting coefficients for 44.1 kHz.
ALSA Topology 2 Configurations:
tools/topology/topology2/include/components/sound_dose.conf: Topology 2 sound dose widget declaration.
tools/topology/topology2/include/bench/sound_dose_controls_playback.conf: Benchmark topology control definitions for setup, volume, gain, and data payload.