autoeq-optim 0.5.58

AutoEQ objectives, constraints, and optimizer backends
Documentation
use super::db::db_from_energy_ratio;
use super::db::db_from_ratio;
use super::misc::interpolate_log_frequency;
use super::misc::masking_weight;
use super::temporal_masking_config::TemporalMaskingConfig;
use super::types::TemporalIrMaskingMetrics;
use super::types::TemporalMaskingMode;
use super::types::TemporalMaskingProfile;

/// Compute a legacy experimental temporal diagnostic from detected room modes.
///
/// This helper remains available for offline/report analysis but is excluded
/// from the active spectral-flatness-only EPA optimizer.
///
/// The penalty estimates how much audible modal ringing remains after the
/// candidate EQ correction. Cuts at severe, prominent modal peaks reduce the
/// residual term; boosts at those modes increase it. This deliberately stays
/// frequency-domain so it can run inside every optimizer evaluation.
pub fn temporal_masking_penalty(
    freqs: &[f64],
    peq_spl: &[f64],
    modes: &[TemporalMaskingMode],
    config: &TemporalMaskingConfig,
) -> f64 {
    if !config.enabled || config.weight <= 0.0 || modes.is_empty() {
        return 0.0;
    }

    let profile_scale = match config.profile {
        TemporalMaskingProfile::Transient => 1.35,
        TemporalMaskingProfile::Mixed => 1.0,
        TemporalMaskingProfile::Sustained => 0.65,
    };

    let mut sum = 0.0;
    let mut count = 0.0;
    for mode in modes {
        let severity = mode.temporal_severity_db.max(0.0);
        let prominence = mode.prominence_db.max(0.0);
        if severity <= 0.0 || prominence <= 0.0 {
            continue;
        }

        let eq_at_mode = interpolate_log_frequency(freqs, peq_spl, mode.frequency).unwrap_or(0.0);
        let residual_prominence = (prominence + eq_at_mode).max(0.0);
        let residual_ratio = (residual_prominence / prominence.max(1e-6)).clamp(0.0, 4.0);
        let boost_penalty = eq_at_mode.max(0.0) / prominence.max(1.0);
        let q_scale = (mode.q.max(1.0) / 10.0).sqrt().clamp(0.5, 2.5);

        sum += q_scale * severity.powi(2) * (residual_ratio.powi(2) + boost_penalty.powi(2));
        count += 1.0;
    }

    if count == 0.0 {
        0.0
    } else {
        config.weight * profile_scale * (sum / count)
    }
}

/// Analyze true FIR impulse-response pre/post ringing with temporal masking.
///
/// The main impulse peak is treated as a transient masker. Energy before that
/// peak is pre-ringing; energy after it is post-ringing. Samples close to the
/// peak are partially masked by configurable pre/post masking windows, while
/// distant ringing is treated as fully audible.
pub fn temporal_ir_masking_metrics(
    ir: &[f64],
    sample_rate: f64,
    config: &TemporalMaskingConfig,
) -> Option<TemporalIrMaskingMetrics> {
    if !config.ir_enabled || config.ir_weight <= 0.0 || sample_rate <= 0.0 || ir.is_empty() {
        return None;
    }

    let (main_index, main_amp) = ir
        .iter()
        .enumerate()
        .map(|(i, &v)| (i, v.abs()))
        .max_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))?;
    if main_amp <= 1e-12 {
        return None;
    }

    let main_energy = main_amp * main_amp;
    let mut pre_peak = 0.0_f64;
    let mut post_peak = 0.0_f64;
    let mut pre_energy = 0.0_f64;
    let mut post_energy = 0.0_f64;

    for (idx, &sample) in ir.iter().enumerate() {
        if idx == main_index {
            continue;
        }
        let amp = sample.abs();
        let energy = sample * sample;
        if idx < main_index {
            let time_ms = (main_index - idx) as f64 * 1000.0 / sample_rate;
            let weight = masking_weight(time_ms, config.pre_mask_ms);
            pre_peak = pre_peak.max(amp);
            pre_energy += energy * weight;
        } else {
            let time_ms = (idx - main_index) as f64 * 1000.0 / sample_rate;
            let weight = masking_weight(time_ms, config.post_mask_ms);
            post_peak = post_peak.max(amp);
            post_energy += energy * weight;
        }
    }

    let pre_audible_db = db_from_energy_ratio(pre_energy / main_energy);
    let post_audible_db = db_from_energy_ratio(post_energy / main_energy);
    let threshold = config.ir_audibility_threshold_db;
    let pre_excess = (pre_audible_db - threshold).max(0.0);
    let post_excess = (post_audible_db - threshold).max(0.0);
    let profile_scale = match config.profile {
        TemporalMaskingProfile::Transient => 1.35,
        TemporalMaskingProfile::Mixed => 1.0,
        TemporalMaskingProfile::Sustained => 0.65,
    };
    let penalty = config.ir_weight
        * profile_scale
        * (config.pre_ringing_weight * pre_excess.powi(2)
            + config.post_ringing_weight * post_excess.powi(2))
        / 100.0;

    Some(TemporalIrMaskingMetrics {
        main_index,
        main_time_ms: main_index as f64 * 1000.0 / sample_rate,
        pre_ringing_peak_db: db_from_ratio(pre_peak / main_amp),
        post_ringing_peak_db: db_from_ratio(post_peak / main_amp),
        pre_ringing_audible_db: pre_audible_db,
        post_ringing_audible_db: post_audible_db,
        penalty,
    })
}