autoeq-optim 0.5.58

AutoEQ objectives, constraints, and optimizer backends
Documentation
use super::super::{loudness, roughness, sharpness};
use super::epa::epa_channel_energy_weight;
use super::epa_config::EpaConfig;
use super::misc::denormalize_spl;
use super::misc::interpolate_log_frequency;
use super::types::EpaChannelRole;
use super::types::EpaScore;

/// Combine level-relative channel spectra into one BS.1770-style EPA score.
///
/// Inputs are normalized room-EQ SPL curves. Each channel is first lifted to
/// `config.listening_level_phon`, then channel energies are summed with
/// BS.1770-style role weights. The aggregate curve is evaluated at its own
/// 1 kHz level so the diagnostic preserves the +3 dB energy effect of two
/// equal transfer-response channels instead of re-normalizing it away. This is
/// not a programme loudness prediction without calibrated stimulus audio.
pub fn compute_epa_multichannel_normalized(
    freqs: &[f64],
    channel_spl_rel: &[(&[f64], EpaChannelRole)],
    config: &EpaConfig,
) -> Option<EpaScore> {
    if freqs.is_empty() || channel_spl_rel.is_empty() {
        return None;
    }

    if !channel_spl_rel.iter().any(|(spl_rel, role)| {
        spl_rel.len() == freqs.len() && epa_channel_energy_weight(*role) > 0.0
    }) {
        return None;
    }

    let aggregate_spl: Vec<f64> = (0..freqs.len())
        .map(|idx| {
            let mut energy_sum = 0.0;
            for &(spl_rel, role) in channel_spl_rel {
                if spl_rel.len() != freqs.len() {
                    continue;
                }
                let weight = epa_channel_energy_weight(role);
                if weight <= 0.0 {
                    continue;
                }
                energy_sum +=
                    weight * 10.0_f64.powf((spl_rel[idx] + config.listening_level_phon) / 10.0);
            }
            if energy_sum > 0.0 {
                10.0 * energy_sum.log10()
            } else {
                -100.0
            }
        })
        .collect();

    let aggregate_level_1khz = interpolate_log_frequency(freqs, &aggregate_spl, 1000.0)
        .unwrap_or(config.listening_level_phon);
    let mut aggregate_config = config.clone();
    aggregate_config.listening_level_phon = aggregate_level_1khz;
    Some(compute_epa(freqs, &aggregate_spl, &aggregate_config))
}

/// Compute EPA score from a frequency response.
///
/// The diagnostic path shifts the response so its interpolated 1 kHz level
/// equals `config.listening_level_phon`. Level-relative curves should use
/// [`compute_epa_normalized`] for a consistent reference offset. This shift
/// does not supply the calibrated programme spectrum needed for a validated
/// loudness, roughness, or preference prediction.
pub fn compute_epa(freqs: &[f64], spl_db: &[f64], config: &EpaConfig) -> EpaScore {
    // 1. Compute specific loudness across Bark bands
    let specific = loudness::specific_loudness(freqs, spl_db, config.listening_level_phon);
    let total_loud = loudness::total_loudness(&specific);

    // 2. Compute sharpness (high-frequency emphasis metric)
    let sharp = sharpness::sharpness(&specific);

    // 3. Compute the legacy spectral-peak-interaction diagnostic
    let rough = roughness::roughness_from_spectrum(freqs, spl_db);

    // 4. Compute loudness balance (uniformity of specific loudness)
    let mean_specific = total_loud / 24.0;
    let variance = specific
        .iter()
        .map(|&n| (n - mean_specific).powi(2))
        .sum::<f64>()
        / 24.0;
    let balance = 1.0 / (1.0 + variance.sqrt()); // 1.0 = perfectly uniform

    // 5. Map to EPA dimensions (0-10 scale)

    // Evaluation: penalize sharpness deviation from target + reward flatness
    let sharpness_error = (sharp - config.target_sharpness).abs();
    let evaluation = (10.0 - 3.0 * sharpness_error - 2.0 * (1.0 - balance)).clamp(0.0, 10.0);

    // Potency: based on total loudness normalized to typical listening levels
    let potency = (total_loud / 10.0).clamp(0.0, 10.0); // ~100 sone -> 10

    // Activity: roughness drives this (lower roughness = calmer sound)
    let activity = (rough * 5.0).clamp(0.0, 10.0);

    // 6. Composite preference: high E, moderate P, low A
    let preference = config.evaluation_weight * evaluation + config.potency_weight * potency
        - config.activity_weight * activity;

    EpaScore {
        evaluation,
        potency,
        activity,
        preference,
        sharpness_acum: sharp,
        roughness: rough,
        total_loudness_sone: total_loud,
        loudness_balance: balance,
    }
}

/// Like [`compute_epa`] but for level-relative (mean-subtracted) input curves.
///
/// The input is denormalized by adding `config.listening_level_phon` before
/// evaluation. See [`denormalize_spl`] for the calibration rationale.
pub fn compute_epa_normalized(freqs: &[f64], spl_rel: &[f64], config: &EpaConfig) -> EpaScore {
    let spl_abs = denormalize_spl(spl_rel, config.listening_level_phon);
    compute_epa(freqs, &spl_abs, config)
}