hdrshot-gui 2.5.0

HDR image tool: desktop app for converting HDR screenshots and images
//! The shutter sound of a screenshot: a short, soft double click made in
//! code, so no sound file has to ship with the app. Windows only.

// Only screenshots, which need Windows, play it.
#![cfg_attr(not(windows), allow(dead_code))]

use std::sync::atomic::{AtomicBool, Ordering};

/// Whether the shutter sounds, as the setting says; read by the thread
/// that takes the screenshot.
static SHUTTER: AtomicBool = AtomicBool::new(false);

/// Samples per second of the sound.
const RATE: u32 = 22_050;

/// Turns the shutter sound on or off.
pub(crate) fn set_shutter(on: bool) {
    SHUTTER.store(on, Ordering::Relaxed);
}

/// Plays the shutter sound, if on, without waiting for it to end.
pub(crate) fn shutter() {
    if SHUTTER.load(Ordering::Relaxed) {
        #[cfg(windows)]
        imp::play_shutter();
    }
}

/// The shutter sound as a WAV file: 16-bit mono PCM, two quiet clicks,
/// like a camera's mirror and shutter, about a tenth of a second long.
pub(crate) fn shutter_wav() -> Vec<u8> {
    let length = RATE as usize / 10;
    // A fixed seed, so the sound is the same every time.
    let mut seed = 0x2545_f491_u32;
    let mut noise = move || {
        seed ^= seed << 13;
        seed ^= seed >> 17;
        seed ^= seed << 5;
        seed as f32 / u32::MAX as f32 * 2.0 - 1.0
    };
    let click = |t: f32, noise: f32| {
        if t < 0.0 {
            return 0.0;
        }
        // Mostly noise, for a click rather than a beep, over a low knock,
        // both dying away within a few milliseconds.
        let knock = (t * 1_400.0 * std::f32::consts::TAU).sin() * (-t / 0.006).exp();
        0.7 * noise * (-t / 0.002).exp() + 0.3 * knock
    };
    let samples = (0..length).map(|i| {
        let t = i as f32 / RATE as f32;
        let n = noise();
        let value = click(t, n) + 0.6 * click(t - 0.045, n);
        // Soft: well below full scale.
        (value * 0.3 * f32::from(i16::MAX)) as i16
    });
    wav(RATE, samples)
}

/// A WAV file of 16-bit mono `samples` at `rate` samples per second.
fn wav(rate: u32, samples: impl ExactSizeIterator<Item = i16>) -> Vec<u8> {
    let data = (samples.len() * 2) as u32;
    let mut out = Vec::with_capacity(44 + data as usize);
    out.extend_from_slice(b"RIFF");
    out.extend_from_slice(&(36 + data).to_le_bytes());
    out.extend_from_slice(b"WAVEfmt ");
    out.extend_from_slice(&16u32.to_le_bytes());
    // PCM, one channel.
    out.extend_from_slice(&1u16.to_le_bytes());
    out.extend_from_slice(&1u16.to_le_bytes());
    out.extend_from_slice(&rate.to_le_bytes());
    // Bytes per second, bytes per sample and bits per sample.
    out.extend_from_slice(&(rate * 2).to_le_bytes());
    out.extend_from_slice(&2u16.to_le_bytes());
    out.extend_from_slice(&16u16.to_le_bytes());
    out.extend_from_slice(b"data");
    out.extend_from_slice(&data.to_le_bytes());
    for sample in samples {
        out.extend_from_slice(&sample.to_le_bytes());
    }
    out
}

#[cfg(windows)]
mod imp {
    use std::sync::OnceLock;

    use windows::Win32::Media::Audio::{PlaySoundW, SND_ASYNC, SND_MEMORY, SND_NODEFAULT};
    use windows::core::PCWSTR;

    pub fn play_shutter() {
        // Kept for as long as the app runs: an asynchronous sound plays
        // from this memory after the call returns. In 16-bit units, so it
        // is aligned as the call's pointer type wants.
        static WAV: OnceLock<Vec<u16>> = OnceLock::new();
        let wav = WAV.get_or_init(|| {
            super::shutter_wav()
                .as_chunks::<2>()
                .0
                .iter()
                .map(|pair| u16::from_ne_bytes(*pair))
                .collect()
        });
        // SAFETY: with SND_MEMORY the pointer is to a whole WAV file in
        // memory that lives until the app quits.
        unsafe {
            let _ = PlaySoundW(
                PCWSTR(wav.as_ptr()),
                None,
                SND_MEMORY | SND_ASYNC | SND_NODEFAULT,
            );
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn shutter_is_a_short_wav() {
        let wav = shutter_wav();
        let u16_at = |i: usize| u16::from_le_bytes([wav[i], wav[i + 1]]);
        let u32_at = |i: usize| u32::from_le_bytes([wav[i], wav[i + 1], wav[i + 2], wav[i + 3]]);
        assert_eq!(&wav[0..4], b"RIFF");
        assert_eq!(u32_at(4) as usize, wav.len() - 8);
        assert_eq!(&wav[8..16], b"WAVEfmt ");
        assert_eq!(u32_at(16), 16);
        assert_eq!((u16_at(20), u16_at(22)), (1, 1));
        assert_eq!(u32_at(24), RATE);
        assert_eq!(u32_at(28), RATE * 2);
        assert_eq!((u16_at(32), u16_at(34)), (2, 16));
        assert_eq!(&wav[36..40], b"data");
        assert_eq!(u32_at(40) as usize, wav.len() - 44);
        // A tenth of a second.
        assert_eq!(wav.len() - 44, RATE as usize / 10 * 2);
        assert_eq!(wav.len() % 2, 0);
    }

    #[test]
    fn shutter_is_soft_and_dies_away() {
        let wav = shutter_wav();
        let samples: Vec<i16> = wav[44..]
            .as_chunks::<2>()
            .0
            .iter()
            .map(|pair| i16::from_le_bytes(*pair))
            .collect();
        let peak = samples.iter().map(|s| s.unsigned_abs()).max().unwrap();
        assert!(peak > 1000, "audible, peak {peak}");
        assert!(peak < i16::MAX as u16 / 2, "soft, peak {peak}");
        // Silent by the end, so it doesn't stop with a click of its own.
        let tail = samples[samples.len() - 100..]
            .iter()
            .map(|s| s.unsigned_abs());
        assert!(tail.max().unwrap() < 50);
        assert_eq!(shutter_wav(), wav);
    }
}