use std::fs::File;
use std::io::Write as _;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering::Relaxed};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use anyhow::{Context, Result, bail};
use crate::lang;
pub const RATE: u32 = crate::voice::RATE;
const FRAME: usize = RATE as usize / 50;
const WINDOW: usize = RATE as usize / 100;
const LEVELS: usize = 100;
const LOUDEST: u32 = 31;
const BITRATE: i32 = 32_000;
const KEEP: Duration = Duration::from_secs(3600);
pub struct Recorder {
shared: Arc<Shared>,
thread: Option<std::thread::JoinHandle<Result<Take>>>,
path: PathBuf,
}
#[derive(Default)]
struct Shared {
stop: AtomicBool,
opened: AtomicBool,
captured: AtomicU64,
failed: Mutex<Option<String>>,
}
#[derive(Debug)]
pub struct Take {
path: PathBuf,
pub duration: i32,
pub waveform: String,
}
impl Take {
pub fn into_path(mut self) -> PathBuf {
std::mem::take(&mut self.path)
}
}
impl Drop for Take {
fn drop(&mut self) {
if !self.path.as_os_str().is_empty() {
let _ = std::fs::remove_file(&self.path);
}
}
}
fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
mutex.lock().unwrap_or_else(PoisonError::into_inner)
}
impl Recorder {
pub fn start(outbox: &Path) -> Result<Recorder> {
let path = new_path(outbox);
crate::clipboard::private_folder(outbox).context(lang::t("the file can't be made"))?;
let file = crate::clipboard::new_file(&path).context(lang::t("the file can't be made"))?;
let shared = Arc::new(Shared::default());
let (ours, theirs) = (Arc::clone(&shared), Arc::clone(&shared));
let temp = path.clone();
let spawned = std::thread::Builder::new()
.name("record".into())
.spawn(move || {
let result = record(&ours, file, temp.clone());
if let Err(e) = &result {
*lock(&theirs.failed) = Some(format!("{e:#}"));
let _ = std::fs::remove_file(&temp);
}
result
});
match spawned.context(lang::t("there's no thread to record on")) {
Ok(thread) => Ok(Recorder {
shared,
thread: Some(thread),
path,
}),
Err(e) => {
let _ = std::fs::remove_file(&path);
Err(e)
}
}
}
#[cfg(test)]
pub fn idle() -> Recorder {
Recorder {
shared: Arc::default(),
thread: Some(std::thread::spawn(|| bail!("nothing was recorded"))),
path: PathBuf::new(),
}
}
pub fn duration(&self) -> Duration {
Duration::from_secs_f64(self.shared.captured.load(Relaxed) as f64 / f64::from(RATE))
}
pub fn failed(&self) -> Option<String> {
lock(&self.shared.failed).clone()
}
pub fn stop(mut self) -> Result<Take> {
self.shared.stop.store(true, Relaxed);
if !self.shared.opened.load(Relaxed) {
bail!(lang::t("nothing was recorded"));
}
let thread = self.thread.take().expect("a recorder stops once");
let result = thread
.join()
.map_err(|_| anyhow::anyhow!(lang::t("the recording couldn't be made")))?;
let take = result?;
if take.duration == 0 {
bail!(lang::t("nothing was recorded"));
}
self.path = PathBuf::new();
Ok(take)
}
}
impl Drop for Recorder {
fn drop(&mut self) {
self.shared.stop.store(true, Relaxed);
if let Some(thread) = self.thread.take()
&& self.shared.opened.load(Relaxed)
{
let _ = thread.join();
}
if !self.path.as_os_str().is_empty() {
let _ = std::fs::remove_file(&self.path);
}
}
}
fn record(shared: &Shared, file: File, path: PathBuf) -> Result<Take> {
let mut source = source::open()?;
shared.opened.store(true, Relaxed);
if shared.stop.load(Relaxed) {
drop(source);
bail!(lang::t("nothing was recorded"));
}
let mut encoder = ::opus::Encoder::new(RATE, ::opus::Channels::Mono, ::opus::Application::Voip)
.context(lang::t("the microphone can't be used"))?;
let _ = encoder.set_bitrate(::opus::Bitrate::Bits(BITRATE));
let preskip = encoder.get_lookahead().unwrap_or(0).max(0) as u64;
let mut ogg = Ogg::new(file);
ogg.head(preskip as u16)?;
let mut pcm = vec![0i16; FRAME];
let mut peaks: Vec<u16> = Vec::new();
let mut peak = 0u16;
let mut window = 0usize;
let mut samples = 0u64;
let mut pending: Option<(Vec<u8>, u64)> = None;
while !shared.stop.load(Relaxed) {
let mut patience = Patience::new(samples > 0, &shared.stop);
if !source.read(&mut pcm, &mut patience)? {
break;
}
for &s in &pcm {
peak = peak.max(s.unsigned_abs());
window += 1;
if window == WINDOW {
peaks.push(peak);
peak = 0;
window = 0;
}
}
let packet = encoder.encode_vec(&pcm, 4000)?;
samples += pcm.len() as u64;
shared.captured.store(samples, Relaxed);
if let Some((last, end)) = pending.replace((packet, samples)) {
ogg.packet(&last, end, false)?;
}
}
if let Some((last, end)) = pending.take() {
ogg.packet(&last, end, true)?;
}
let seconds = (samples - preskip.min(samples)) / u64::from(RATE);
Ok(Take {
path,
duration: i32::try_from(seconds).unwrap_or(i32::MAX),
waveform: waveform(&peaks),
})
}
fn waveform(peaks: &[u16]) -> String {
if peaks.is_empty() {
return String::new();
}
let loud = u32::from(peaks.iter().copied().max().unwrap_or(0).max(1));
let n = peaks.len();
let levels: Vec<u8> = (0..LEVELS)
.map(|c| {
let from = c * n / LEVELS;
let to = ((c + 1) * n / LEVELS).clamp(from + 1, n);
let peak = u32::from(peaks[from..to].iter().copied().max().unwrap_or(0));
((peak * LOUDEST + loud / 2) / loud) as u8
})
.collect();
use base64::Engine;
base64::engine::general_purpose::STANDARD.encode(pack(&levels))
}
fn pack(levels: &[u8]) -> Vec<u8> {
let mut bytes = vec![0; (levels.len() * 5).div_ceil(8)];
for (i, &level) in levels.iter().enumerate() {
let (byte, shift) = (i * 5 / 8, i * 5 % 8);
let bits = u16::from(level.min(31)) << shift;
bytes[byte] |= bits as u8;
if let Some(next) = bytes.get_mut(byte + 1) {
*next |= (bits >> 8) as u8;
}
}
bytes
}
const PREFIX: &str = "tuigram-voice-";
fn new_path(outbox: &Path) -> PathBuf {
let nanos = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |d| d.as_nanos());
outbox.join(format!("{PREFIX}{}-{nanos}.ogg", std::process::id()))
}
pub fn is_recording(path: &Path, outbox: &Path) -> bool {
let named = path
.file_name()
.and_then(|n| n.to_str())
.is_some_and(|name| {
name.strip_prefix(PREFIX)
.and_then(|n| n.strip_suffix(".ogg"))
.and_then(|n| n.split_once('-'))
.is_some_and(|(pid, nanos)| {
[pid, nanos]
.iter()
.all(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()))
})
});
named
&& path.parent().is_some_and(|dir| {
dir == outbox
|| matches!(
(std::fs::canonicalize(dir), std::fs::canonicalize(outbox)),
(Ok(dir), Ok(outbox)) if dir == outbox
)
})
}
pub fn clean_stale(outbox: &Path, now: SystemTime) {
let Ok(entries) = std::fs::read_dir(outbox) else {
return;
};
for entry in entries.flatten() {
if !is_recording(&entry.path(), outbox) {
continue;
}
let stale = entry
.metadata()
.ok()
.filter(std::fs::Metadata::is_file)
.and_then(|m| m.modified().ok())
.is_some_and(|t| now.duration_since(t).is_ok_and(|age| age > KEEP));
if stale {
let _ = std::fs::remove_file(entry.path());
}
}
}
struct Ogg {
out: File,
serial: u32,
seq: u32,
}
impl Ogg {
fn new(out: File) -> Self {
let nanos = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |d| d.as_nanos());
Self {
out,
serial: nanos as u32,
seq: 0,
}
}
fn head(&mut self, preskip: u16) -> Result<()> {
let mut head = Vec::with_capacity(19);
head.extend_from_slice(b"OpusHead");
head.push(1); head.push(1); head.extend_from_slice(&preskip.to_le_bytes());
head.extend_from_slice(&RATE.to_le_bytes());
head.extend_from_slice(&0i16.to_le_bytes()); head.push(0); self.page(2, 0, &[&head])?; let vendor = b"tuigram";
let mut tags = Vec::with_capacity(16 + vendor.len());
tags.extend_from_slice(b"OpusTags");
tags.extend_from_slice(&(vendor.len() as u32).to_le_bytes());
tags.extend_from_slice(vendor);
tags.extend_from_slice(&0u32.to_le_bytes()); self.page(0, 0, &[&tags])?;
Ok(())
}
fn packet(&mut self, packet: &[u8], granule: u64, last: bool) -> Result<()> {
self.page(u8::from(last) << 2, granule, &[packet])
}
fn page(&mut self, flags: u8, granule: u64, packets: &[&[u8]]) -> Result<()> {
let mut lacing = Vec::new();
for packet in packets {
let mut left = packet.len();
loop {
let part = left.min(255);
lacing.push(part as u8);
left -= part;
if part < 255 {
break;
}
}
}
let mut page = Vec::with_capacity(27 + lacing.len() + 4000);
page.extend_from_slice(b"OggS");
page.push(0); page.push(flags);
page.extend_from_slice(&granule.to_le_bytes());
page.extend_from_slice(&self.serial.to_le_bytes());
page.extend_from_slice(&self.seq.to_le_bytes());
self.seq += 1;
page.extend_from_slice(&0u32.to_le_bytes()); page.push(lacing.len() as u8);
page.extend_from_slice(&lacing);
for packet in packets {
page.extend_from_slice(packet);
}
let sum = crc(&page);
page[22..26].copy_from_slice(&sum.to_le_bytes());
self.out
.write_all(&page)
.context(lang::t("the file can't be written"))
}
}
fn crc(bytes: &[u8]) -> u32 {
const fn table() -> [u32; 256] {
let mut table = [0u32; 256];
let mut i = 0;
while i < 256 {
let mut r = (i as u32) << 24;
let mut b = 0;
while b < 8 {
r = if r & 0x8000_0000 != 0 {
(r << 1) ^ 0x04c1_1db7
} else {
r << 1
};
b += 1;
}
table[i] = r;
i += 1;
}
table
}
const TABLE: [u32; 256] = table();
let mut sum = 0u32;
for &byte in bytes {
sum = (sum << 8) ^ TABLE[((sum >> 24) as u8 ^ byte) as usize];
}
sum
}
const STARTING: Duration = Duration::from_secs(15);
const STALLED: Duration = Duration::from_secs(3);
struct Patience<'a> {
since: Instant,
wait: Duration,
stop: &'a AtomicBool,
}
impl<'a> Patience<'a> {
fn new(heard_before: bool, stop: &'a AtomicBool) -> Self {
Self {
since: Instant::now(),
wait: if heard_before { STALLED } else { STARTING },
stop,
}
}
#[cfg_attr(
not(any(target_os = "linux", target_os = "macos", target_os = "windows")),
allow(dead_code)
)]
fn heard(&mut self) {
self.since = Instant::now();
}
#[cfg_attr(
not(any(target_os = "linux", target_os = "macos", target_os = "windows")),
allow(dead_code)
)]
fn wait(&self) -> Result<bool> {
if self.stop.load(Relaxed) {
return Ok(false);
}
if self.since.elapsed() > self.wait {
bail!(lang::t("the microphone stopped"));
}
std::thread::sleep(Duration::from_millis(5));
Ok(true)
}
}
trait Source {
fn read(&mut self, buf: &mut [i16], patience: &mut Patience) -> Result<bool>;
}
#[cfg(target_os = "linux")]
mod source {
use std::ffi::{CStr, c_char, c_int, c_long, c_uint, c_ulong, c_void};
use std::ptr::null_mut;
use std::sync::OnceLock;
use anyhow::{Result, bail};
use super::{Patience, RATE, Source};
use crate::lang;
type Pcm = c_void;
const CAPTURE: c_int = 1;
const NONBLOCK: c_int = 1;
#[cfg(target_endian = "little")]
const S16: c_int = 2;
#[cfg(target_endian = "big")]
const S16: c_int = 3;
const RW_INTERLEAVED: c_int = 3;
const LATENCY: c_uint = 100_000;
type ErrorHandler =
unsafe extern "C" fn(*const c_char, c_int, *const c_char, c_int, *const c_char);
unsafe extern "C" fn quiet(
_: *const c_char,
_: c_int,
_: *const c_char,
_: c_int,
_: *const c_char,
) {
}
type SetHandler = unsafe extern "C" fn(Option<ErrorHandler>) -> c_int;
type Open = unsafe extern "C" fn(*mut *mut Pcm, *const c_char, c_int, c_int) -> c_int;
type SetParams =
unsafe extern "C" fn(*mut Pcm, c_int, c_int, c_uint, c_uint, c_int, c_uint) -> c_int;
type Read = unsafe extern "C" fn(*mut Pcm, *mut c_void, c_ulong) -> c_long;
type Recover = unsafe extern "C" fn(*mut Pcm, c_int, c_int) -> c_int;
type Close = unsafe extern "C" fn(*mut Pcm) -> c_int;
type StrError = unsafe extern "C" fn(c_int) -> *const c_char;
struct Alsa {
open: Open,
set_params: SetParams,
readi: Read,
recover: Recover,
close: Close,
strerror: StrError,
}
fn alsa() -> Result<&'static Alsa> {
static ALSA: OnceLock<Option<Alsa>> = OnceLock::new();
match ALSA.get_or_init(load) {
Some(alsa) => Ok(alsa),
None => bail!(lang::t(
"there's no sound here (ALSA's libasound.so.2 isn't installed)"
)),
}
}
fn load() -> Option<Alsa> {
unsafe {
let lib = libc::dlopen(
c"libasound.so.2".as_ptr(),
libc::RTLD_NOW | libc::RTLD_LOCAL,
);
if lib.is_null() {
return None;
}
macro_rules! function {
($name:literal as $signature:ty) => {{
let f = libc::dlsym(lib, $name.as_ptr());
if f.is_null() {
return None;
}
std::mem::transmute::<*mut c_void, $signature>(f)
}};
}
let set_handler = function!(c"snd_lib_error_set_handler" as SetHandler);
set_handler(Some(quiet));
Some(Alsa {
open: function!(c"snd_pcm_open" as Open),
set_params: function!(c"snd_pcm_set_params" as SetParams),
readi: function!(c"snd_pcm_readi" as Read),
recover: function!(c"snd_pcm_recover" as Recover),
close: function!(c"snd_pcm_close" as Close),
strerror: function!(c"snd_strerror" as StrError),
})
}
}
pub struct Mic {
alsa: &'static Alsa,
pcm: *mut Pcm,
}
pub fn open() -> Result<Box<dyn Source>> {
let alsa = alsa()?;
let pcm = crate::sound::quietly(|| open_with(alsa))?;
Ok(Box::new(Mic { alsa, pcm }))
}
fn open_with(alsa: &Alsa) -> Result<*mut Pcm> {
let mut pcm = null_mut();
let e = unsafe { (alsa.open)(&mut pcm, c"default".as_ptr(), CAPTURE, NONBLOCK) };
if e < 0 {
bail!(
"{}: {}",
lang::t("the microphone can't be opened"),
message(alsa, e)
);
}
let e = unsafe { (alsa.set_params)(pcm, S16, RW_INTERLEAVED, 1, RATE, 1, LATENCY) };
if e < 0 {
unsafe { (alsa.close)(pcm) };
bail!(
"{}: {}",
lang::t("the microphone can't be used"),
message(alsa, e)
);
}
Ok(pcm)
}
fn message(alsa: &Alsa, e: c_int) -> String {
let text = unsafe { (alsa.strerror)(e) };
if text.is_null() {
return format!("{} {e}", lang::t("error"));
}
unsafe { CStr::from_ptr(text) }
.to_string_lossy()
.into_owned()
}
impl Source for Mic {
fn read(&mut self, buf: &mut [i16], patience: &mut Patience) -> Result<bool> {
let mut filled = 0;
while filled < buf.len() {
let n = unsafe {
(self.alsa.readi)(
self.pcm,
buf[filled..].as_mut_ptr().cast(),
(buf.len() - filled) as c_ulong,
)
};
if n == 0 || n == -c_long::from(libc::EAGAIN) {
if !patience.wait()? {
return Ok(false);
}
continue;
}
if n < 0 {
let e = unsafe { (self.alsa.recover)(self.pcm, n as c_int, 1) };
if e < 0 {
bail!(
"{}: {}",
lang::t("the microphone stopped"),
message(self.alsa, e)
);
}
continue;
}
filled += n as usize;
patience.heard();
}
Ok(true)
}
}
impl Drop for Mic {
fn drop(&mut self) {
unsafe { (self.alsa.close)(self.pcm) };
}
}
}
#[cfg(any(target_os = "macos", target_os = "windows"))]
mod source {
use std::collections::VecDeque;
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use anyhow::{Context, Result, anyhow, bail};
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
use cpal::{FromSample, SampleFormat, SizedSample, StreamConfig};
use super::{Patience, RATE, Resampler, Source};
use crate::lang;
#[derive(Default)]
struct Heard {
samples: VecDeque<f32>,
failed: Option<String>,
}
pub struct Mic {
_stream: cpal::Stream,
heard: Arc<Mutex<Heard>>,
resampler: Resampler,
scratch: Vec<i16>,
}
fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
mutex.lock().unwrap_or_else(PoisonError::into_inner)
}
pub fn open() -> Result<Box<dyn Source>> {
let device = cpal::default_host()
.default_input_device()
.context(lang::t("no microphone found"))?;
let supported = device
.default_input_config()
.map_err(|e| anyhow!("{}: {e}", lang::t("the microphone can't be used")))?;
let format = supported.sample_format();
let config: StreamConfig = supported.into();
let heard = Arc::new(Mutex::new(Heard::default()));
let stream = match format {
SampleFormat::F32 => stream::<f32>(&device, &config, &heard)?,
SampleFormat::I16 => stream::<i16>(&device, &config, &heard)?,
SampleFormat::U16 => stream::<u16>(&device, &config, &heard)?,
SampleFormat::I32 => stream::<i32>(&device, &config, &heard)?,
other => bail!(lang::f(
"the microphone gives {format} samples, which tuigram can't take",
&[("format", &other)],
)),
};
stream
.play()
.map_err(|e| anyhow!("{}: {e}", lang::t("the microphone didn't start")))?;
Ok(Box::new(Mic {
_stream: stream,
heard,
resampler: Resampler::new(config.sample_rate, RATE),
scratch: Vec::new(),
}))
}
fn stream<T: SizedSample>(
device: &cpal::Device,
config: &StreamConfig,
heard: &Arc<Mutex<Heard>>,
) -> Result<cpal::Stream>
where
f32: FromSample<T>,
{
let channels = usize::from(config.channels).max(1);
let fill = Arc::clone(heard);
let failed = Arc::clone(heard);
device
.build_input_stream(
*config,
move |data: &[T], _: &cpal::InputCallbackInfo| {
let mut heard = lock(&fill);
for frame in data.chunks(channels) {
let sum: f32 = frame.iter().map(|s| s.to_sample::<f32>()).sum();
heard.samples.push_back(sum / channels as f32);
}
},
move |e| lock(&failed).failed = Some(e.to_string()),
None,
)
.map_err(|e| anyhow!("{}: {e}", lang::t("the microphone can't be used")))
}
impl Source for Mic {
fn read(&mut self, buf: &mut [i16], patience: &mut Patience) -> Result<bool> {
let mut filled = 0;
while filled < buf.len() {
{
let mut heard = lock(&self.heard);
if let Some(e) = &heard.failed {
bail!("{}: {e}", lang::t("the microphone stopped"));
}
let mut input = Vec::new();
while let Some(s) = heard.samples.pop_front() {
input.push(s);
}
drop(heard);
self.resampler.run(&input, &mut self.scratch);
}
let take = self.scratch.len().min(buf.len() - filled);
buf[filled..filled + take].copy_from_slice(&self.scratch[..take]);
self.scratch.drain(..take);
filled += take;
if take > 0 {
patience.heard();
}
if filled < buf.len() && !patience.wait()? {
return Ok(false);
}
}
Ok(true)
}
}
}
#[cfg(not(any(target_os = "macos", target_os = "windows", target_os = "linux")))]
mod source {
use anyhow::{Result, bail};
use super::Source;
pub fn open() -> Result<Box<dyn Source>> {
bail!(crate::lang::t("tuigram can't record on this system yet"))
}
}
#[cfg(any(test, any(target_os = "macos", target_os = "windows")))]
pub struct Resampler {
step: f64,
at: f64,
last: f32,
}
#[cfg(any(test, any(target_os = "macos", target_os = "windows")))]
impl Resampler {
pub fn new(from: u32, to: u32) -> Self {
Self {
step: f64::from(from) / f64::from(to.max(1)),
at: 0.0,
last: 0.0,
}
}
pub fn run(&mut self, input: &[f32], out: &mut Vec<i16>) {
let Some(&end) = input.last() else {
return;
};
let sample = |i: isize| match i {
-1 => self.last,
i => input[i as usize],
};
let len = input.len() as f64;
while self.at < len - 1.0 {
let i = self.at.floor();
let (a, b) = (sample(i as isize), sample(i as isize + 1));
let s = a + (b - a) * (self.at - i) as f32;
out.push((s * 32768.0).clamp(-32768.0, 32767.0) as i16);
self.at += self.step;
}
self.at -= len;
self.last = end;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn esc_and_v_never_wait_for_a_microphone_still_opening() {
let opening = || Recorder {
shared: Arc::default(),
thread: Some(std::thread::spawn(|| {
std::thread::sleep(Duration::from_secs(2));
bail!("opened too late")
})),
path: PathBuf::new(),
};
let at = std::time::Instant::now();
drop(opening());
assert!(at.elapsed() < Duration::from_secs(1), "Esc waited");
let at = std::time::Instant::now();
assert!(opening().stop().is_err(), "nothing was recorded");
assert!(at.elapsed() < Duration::from_secs(1), "V waited");
}
#[test]
fn ogg_crc_matches_the_known_value() {
assert_eq!(crc(b"123456789"), 0x89a1_897f);
}
#[test]
fn a_written_page_carries_its_checksum() {
let path = std::env::temp_dir().join(format!(
"tuigram-record-test-{}-page.ogg",
std::process::id()
));
let file = File::create(&path).unwrap();
let mut ogg = Ogg::new(file);
ogg.packet(b"a packet", 960, true).unwrap();
drop(ogg);
let page = std::fs::read(&path).unwrap();
std::fs::remove_file(&path).unwrap();
assert!(page.starts_with(b"OggS\0\x04"), "the last page says so");
let stored = u32::from_le_bytes(page[22..26].try_into().unwrap());
let mut zeroed = page.clone();
zeroed[22..26].fill(0);
assert_eq!(crc(&zeroed), stored, "the page's checksum is its own");
assert_eq!(u64::from_le_bytes(page[6..14].try_into().unwrap()), 960);
assert_eq!(page[26], 1, "one packet");
assert_eq!(page[27], 8, "of 8 bytes");
}
#[test]
fn waveform_levels_pack_as_voice_rs_reads_them() {
let levels: Vec<u8> = (0..100usize).map(|i| ((i * 7) % 32) as u8).collect();
let packed = pack(&levels);
let unpacked: Vec<u8> = (0..packed.len() * 8 / 5)
.map(|i| {
let (byte, shift) = (i * 5 / 8, i * 5 % 8);
let next = packed.get(byte + 1).copied().unwrap_or(0);
let pair = u16::from(packed[byte]) | u16::from(next) << 8;
(pair >> shift & 0x1f) as u8
})
.collect();
assert_eq!(unpacked[..100], levels[..]);
}
#[test]
fn a_waveform_scales_to_the_loudest_peak() {
let mut peaks = vec![0u16; 100];
peaks[50] = 1000;
let levels_b64 = waveform(&peaks);
use base64::Engine;
let bytes = base64::engine::general_purpose::STANDARD
.decode(&levels_b64)
.unwrap();
assert_eq!(bytes.len(), 63, "100 levels of 5 bits");
let loud = (0..bytes.len() * 8 / 5)
.map(|i| {
let (byte, shift) = (i * 5 / 8, i * 5 % 8);
let next = bytes.get(byte + 1).copied().unwrap_or(0);
((u16::from(bytes[byte]) | u16::from(next) << 8) >> shift & 0x1f) as u8
})
.max()
.unwrap();
assert_eq!(loud, 31);
assert!(waveform(&[]).is_empty(), "nothing heard, no waveform");
}
#[test]
fn a_recording_written_is_one_voice_rs_reads() {
let mut encoder =
::opus::Encoder::new(RATE, ::opus::Channels::Mono, ::opus::Application::Voip).unwrap();
let preskip = encoder.get_lookahead().unwrap_or(0).max(0) as u64;
let path =
std::env::temp_dir().join(format!("tuigram-record-test-{}.ogg", std::process::id()));
let file = File::create(&path).unwrap();
let mut ogg = Ogg::new(file);
ogg.head(preskip as u16).unwrap();
let mut samples = 0u64;
let mut pending: Option<(Vec<u8>, u64)> = None;
for frame in 0..50 {
let pcm: Vec<i16> = (0..FRAME)
.map(|i| {
let t = (frame * FRAME + i) as f64 / f64::from(RATE);
(f64::sin(t * 440.0 * std::f64::consts::TAU) * 8000.0) as i16
})
.collect();
let packet = encoder.encode_vec(&pcm, 4000).unwrap();
samples += FRAME as u64;
if let Some((last, end)) = pending.replace((packet, samples)) {
ogg.packet(&last, end, false).unwrap();
}
}
let (last, end) = pending.take().unwrap();
ogg.packet(&last, end, true).unwrap();
drop(ogg);
let file = File::open(&path).unwrap();
let mut sound = crate::voice::OggOpus::new(std::io::BufReader::new(file)).unwrap();
let mut heard = Vec::new();
let mut out = Vec::new();
while sound.next(&mut out).unwrap() {
heard.extend_from_slice(&out);
}
std::fs::remove_file(&path).unwrap();
let expect = 50 * FRAME - preskip as usize;
assert_eq!(heard.len(), expect);
assert!(heard.iter().any(|&s| s.unsigned_abs() > 4000));
}
#[test]
fn resampling_keeps_the_length_in_time() {
let mut resampler = Resampler::new(44_100, 48_000);
let mut out = Vec::new();
let second: Vec<f32> = (0..44_100)
.map(|i| f32::sin(i as f32 / 44_100.0 * 440.0 * std::f32::consts::TAU))
.collect();
for chunk in second.chunks(441) {
resampler.run(chunk, &mut out);
}
assert!(
(47_990..=48_000).contains(&out.len()),
"a second stays a second: {}",
out.len()
);
}
#[test]
fn a_device_has_longer_to_start_than_to_go_quiet_and_a_stop_ends_the_wait() {
let stop = AtomicBool::new(false);
let quiet_for = STALLED + Duration::from_secs(1);
let mut starting = Patience::new(false, &stop);
starting.since -= quiet_for;
assert!(starting.wait().unwrap(), "still starting: read again");
let mut going = Patience::new(true, &stop);
going.since -= quiet_for;
assert!(going.wait().is_err(), "it gave sound, then none");
going.heard();
assert!(going.wait().unwrap(), "it gave some again");
stop.store(true, Relaxed);
starting.since -= STARTING;
assert!(!starting.wait().unwrap(), "stopped: no error, no waiting");
}
#[test]
fn stale_recordings_are_removed_but_fresh_ones_kept() {
let dir =
std::env::temp_dir().join(format!("tuigram-record-test-{}-stale", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let old = dir.join("tuigram-voice-1-2.ogg");
let other = dir.join("other.ogg");
let lookalike = dir.join("tuigram-voice-notes.ogg");
for file in [&old, &other, &lookalike] {
std::fs::write(file, b"x").unwrap();
}
let now = SystemTime::now();
for file in [&old, &lookalike] {
File::options()
.write(true)
.open(file)
.unwrap()
.set_modified(now - KEEP - Duration::from_secs(60))
.unwrap();
}
clean_stale(&dir, now);
assert!(!old.exists(), "an hour-old recording is removed");
assert!(other.exists(), "other files are left alone");
assert!(
lookalike.exists(),
"named otherwise than tuigram names them"
);
let fresh = dir.join("tuigram-voice-3-4.ogg");
std::fs::write(&fresh, b"x").unwrap();
clean_stale(&dir, now);
assert!(fresh.exists(), "a fresh one may be a live tuigram's");
std::fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn a_recording_is_a_file_only_you_can_read_in_the_outbox() {
let outbox =
std::env::temp_dir().join(format!("tuigram-record-test-{}-outbox", std::process::id()));
let path = new_path(&outbox);
assert!(is_recording(&path, &outbox), "{path:?}");
assert!(
!is_recording(&path, &std::env::temp_dir()),
"only in the outbox"
);
assert!(!is_recording(&outbox.join("pasted-1.png"), &outbox));
crate::clipboard::private_folder(&outbox).unwrap();
drop(crate::clipboard::new_file(&path).unwrap());
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mode = |p: &Path| std::fs::metadata(p).unwrap().permissions().mode() & 0o777;
assert_eq!(mode(&outbox), 0o700);
assert_eq!(mode(&path), 0o600);
}
assert!(
crate::clipboard::new_file(&path).is_err(),
"never one that's there already"
);
std::fs::remove_dir_all(&outbox).unwrap();
}
#[test]
fn a_take_deletes_its_file_unless_taken() {
let path = new_path(&std::env::temp_dir());
std::fs::write(&path, b"x").unwrap();
{
let take = Take {
path: path.clone(),
duration: 1,
waveform: String::new(),
};
assert_eq!(take.path, path);
}
assert!(!path.exists(), "dropped, the file is gone");
std::fs::write(&path, b"x").unwrap();
let take = Take {
path: path.clone(),
duration: 1,
waveform: String::new(),
};
let kept = take.into_path();
assert!(kept.exists(), "taken, the file stays");
std::fs::remove_file(&kept).unwrap();
}
}