Skip to main content

qualia_audio/aqa/mos/
nisqa.rs

1//! NISQA — non-intrusive speech-quality learned MOS predictor. **NeedsWeights.**
2//!
3//! NISQA (Mittag et al., 2021) is a deep model (CNN + self-attention) trained to
4//! predict speech MOS and its sub-dimensions (noisiness, coloration,
5//! discontinuity, loudness) from a single degraded clip, no clean reference. As
6//! with DNSMOS, the score IS the trained network; there is no principled hand
7//! coded formula that yields it.
8//!
9//! This function therefore **fails closed**: without weights it returns
10//! [`AudioError::BackendUnavailable`] and never fabricates a MOS. Fabricating a
11//! learned MOS is forbidden by project rule.
12
13use crate::types::AudioError;
14
15/// Predict a NISQA speech-quality MOS for `signal`.
16///
17/// - `signal`: mono degraded speech (no reference needed).
18/// - `weights`: the trained NISQA model weights. `None` (or, currently, any value)
19///   means the learned backend is unavailable.
20///
21/// # Fails closed
22///
23/// Returns [`AudioError::BackendUnavailable`] when `weights` is `None`, and also
24/// while the inference backend is unwired for `Some(_)`. It never returns a
25/// synthesised MOS.
26pub fn nisqa(signal: &[f32], weights: Option<&[u8]>) -> Result<f32, AudioError> {
27    if signal.is_empty() {
28        return Err(AudioError::MalformedAudio);
29    }
30
31    match weights {
32        // No model → no MOS. Fail closed; NEVER fabricate a number.
33        None => Err(AudioError::BackendUnavailable),
34        // Weights present but learned inference is not yet wired: still fail closed.
35        Some(_bytes) => Err(AudioError::BackendUnavailable),
36    }
37}
38
39#[cfg(test)]
40mod tests {
41    use super::*;
42
43    #[test]
44    fn no_weights_fails_closed_never_returns_mos() {
45        let sig = vec![0.05f32, -0.1, 0.2, -0.15];
46        let out = nisqa(&sig, None);
47        assert_eq!(
48            out,
49            Err(AudioError::BackendUnavailable),
50            "NISQA with no weights must fail closed, not return a MOS"
51        );
52        assert!(out.is_err());
53    }
54
55    #[test]
56    fn weights_present_still_fails_closed_until_backend_wired() {
57        let sig = vec![0.1f32, 0.2, 0.3];
58        let dummy = [0u8; 16];
59        assert_eq!(
60            nisqa(&sig, Some(&dummy)),
61            Err(AudioError::BackendUnavailable),
62            "unwired backend must fail closed, not guess a MOS"
63        );
64    }
65
66    #[test]
67    fn empty_signal_is_malformed() {
68        assert_eq!(nisqa(&[], None), Err(AudioError::MalformedAudio));
69    }
70}