rasterwave 0.6.0

High-performance streaming SSTV, radiofax and RTTY encoders/decoders
Documentation
use crate::{Error, Result};

/// Number of stop bits that close each RTTY character.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum StopBits {
    /// One stop bit.
    One,
    /// One and a half stop bits, the amateur 45.45 baud convention.
    OnePointFive,
    /// Two stop bits.
    Two,
}

impl StopBits {
    /// Stop-bit duration in bit periods.
    #[must_use]
    pub const fn bits(self) -> f64 {
        match self {
            Self::One => 1.0,
            Self::OnePointFive => 1.5,
            Self::Two => 2.0,
        }
    }
}

/// Character set used to interpret the figures shift of ITA2 / Baudot codes.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
#[non_exhaustive]
pub enum CharacterSet {
    /// US-TTY figures (`$`, `'`, `!`, `"`, `#`, `&`, `;`), the common amateur variant.
    #[default]
    UsTty,
    /// ITU-T ITA2 figures (`'`, `+`, `=`).
    Ita2,
}

/// Signalling profile: symbol rate, tone shift and stop-bit length.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct RttyProfile {
    /// Symbol rate in baud.
    pub baud: f64,
    /// Distance between mark and space tones in hertz.
    pub shift_hz: f64,
    /// Stop-bit length.
    pub stop_bits: StopBits,
}

impl RttyProfile {
    /// Amateur standard: 45.45 baud, 170 Hz shift, 1.5 stop bits.
    pub const RTTY_45_170: Self = Self::new(45.45, 170.0, StopBits::OnePointFive);
    /// 50 baud, 170 Hz shift, 1.5 stop bits.
    pub const RTTY_50_170: Self = Self::new(50.0, 170.0, StopBits::OnePointFive);
    /// 75 baud, 170 Hz shift, 1.5 stop bits.
    pub const RTTY_75_170: Self = Self::new(75.0, 170.0, StopBits::OnePointFive);
    /// 50 baud, 425 Hz shift, 1.5 stop bits.
    pub const RTTY_50_425: Self = Self::new(50.0, 425.0, StopBits::OnePointFive);
    /// 50 baud, 850 Hz shift, 1.5 stop bits.
    pub const RTTY_50_850: Self = Self::new(50.0, 850.0, StopBits::OnePointFive);

    /// Creates a profile without validation; use [`RttyProfile::validate`] before use.
    #[must_use]
    pub const fn new(baud: f64, shift_hz: f64, stop_bits: StopBits) -> Self {
        Self {
            baud,
            shift_hz,
            stop_bits,
        }
    }

    /// Checks that the profile is representable by the modem.
    pub fn validate(&self) -> Result<()> {
        if !self.baud.is_finite() || !(20.0..=300.0).contains(&self.baud) {
            return Err(Error::InvalidConfiguration(
                "RTTY baud must be between 20 and 300",
            ));
        }
        if !self.shift_hz.is_finite() || !(20.0..=1_200.0).contains(&self.shift_hz) {
            return Err(Error::InvalidConfiguration(
                "RTTY shift must be between 20 and 1200 Hz",
            ));
        }
        Ok(())
    }

    /// Checks that `tones` are separated by this profile's shift.
    pub fn check_tones(&self, tones: &RttyTones) -> Result<()> {
        if (tones.shift_hz() - self.shift_hz).abs() > 1.0 {
            return Err(Error::InvalidConfiguration(
                "RTTY tones must be separated by the profile shift",
            ));
        }
        Ok(())
    }

    /// Bit period in seconds.
    #[must_use]
    pub fn bit_seconds(&self) -> f64 {
        1.0 / self.baud
    }

    /// Duration of one framed character (start, five data bits and stop bits) in seconds.
    #[must_use]
    pub fn character_seconds(&self) -> f64 {
        (6.0 + self.stop_bits.bits()) / self.baud
    }
}

impl Default for RttyProfile {
    fn default() -> Self {
        Self::RTTY_45_170
    }
}

/// Audio tone frequencies as they must appear in the PCM stream.
///
/// The caller owns sideband handling: on lower sideband the mark tone is the
/// lower audio frequency, on upper sideband it is the higher one, so the RF
/// mark stays above the RF space as the amateur convention requires.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct RttyTones {
    /// Mark (binary one, idle) tone in hertz.
    pub mark_hz: f64,
    /// Space (binary zero) tone in hertz.
    pub space_hz: f64,
}

impl RttyTones {
    /// Creates a tone pair.
    #[must_use]
    pub const fn new(mark_hz: f64, space_hz: f64) -> Self {
        Self { mark_hz, space_hz }
    }

    /// Builds a pair from a centre frequency and shift, placing mark above or below the centre.
    #[must_use]
    pub fn from_center(center_hz: f64, shift_hz: f64, mark_above_center: bool) -> Self {
        let half = shift_hz / 2.0;
        if mark_above_center {
            Self::new(center_hz + half, center_hz - half)
        } else {
            Self::new(center_hz - half, center_hz + half)
        }
    }

    /// Centre frequency between mark and space.
    #[must_use]
    pub fn center_hz(&self) -> f64 {
        (self.mark_hz + self.space_hz) / 2.0
    }

    /// Absolute tone separation.
    #[must_use]
    pub fn shift_hz(&self) -> f64 {
        (self.mark_hz - self.space_hz).abs()
    }

    /// Returns the pair with mark and space exchanged.
    #[must_use]
    pub fn reversed(&self) -> Self {
        Self::new(self.space_hz, self.mark_hz)
    }

    /// Checks that both tones are representable at `sample_rate` and distinct.
    pub fn validate(&self, sample_rate: u32) -> Result<()> {
        let nyquist = f64::from(sample_rate) / 2.0;
        for tone in [self.mark_hz, self.space_hz] {
            if !tone.is_finite() || tone < 100.0 || tone > nyquist * 0.9 {
                return Err(Error::InvalidConfiguration(
                    "RTTY tones must be above 100 Hz and below 90% of Nyquist",
                ));
            }
        }
        if self.shift_hz() < 20.0 {
            return Err(Error::InvalidConfiguration(
                "RTTY mark and space tones must be at least 20 Hz apart",
            ));
        }
        Ok(())
    }
}

impl Default for RttyTones {
    /// The traditional 2125 / 2295 Hz pair for lower-sideband AFSK.
    fn default() -> Self {
        Self::new(2_125.0, 2_295.0)
    }
}

pub(crate) fn validate_sample_rate(sample_rate: u32) -> Result<()> {
    if (8_000..=384_000).contains(&sample_rate) {
        Ok(())
    } else {
        Err(Error::InvalidSampleRate(sample_rate))
    }
}