use std::io::Write;
use std::path::{Path, PathBuf};
use std::time::Duration;
const WORKER_MARKER: &str = "MINUTES_AUDIO_DECODE_WORKER_V1";
const WORKER_ADDRESS_SPACE_BYTES: u64 = 3 * 1024 * 1024 * 1024;
#[cfg(target_os = "macos")]
fn install_child_address_space_ceiling() -> Result<(), String> {
let baseline = process_virtual_size()?;
let limit = baseline
.checked_add(WORKER_ADDRESS_SPACE_BYTES)
.ok_or_else(|| "decode worker address-space ceiling overflowed".to_string())?;
let rlimit = libc::rlimit {
rlim_cur: limit,
rlim_max: limit,
};
if unsafe { libc::setrlimit(libc::RLIMIT_AS, &rlimit) } != 0 {
return Err("decode worker could not install its address-space ceiling".into());
}
Ok(())
}
#[cfg(target_os = "macos")]
fn process_virtual_size() -> Result<u64, String> {
use mach2::kern_return::KERN_SUCCESS;
use mach2::task::task_info;
use mach2::task_info::{
task_basic_info_64, task_info_t, TASK_BASIC_INFO_64, TASK_BASIC_INFO_64_COUNT,
};
use mach2::traps::mach_task_self;
let mut info = task_basic_info_64::default();
let mut count = TASK_BASIC_INFO_64_COUNT;
let status = unsafe {
task_info(
mach_task_self(),
TASK_BASIC_INFO_64,
(&mut info as *mut task_basic_info_64).cast::<libc::c_int>() as task_info_t,
&mut count,
)
};
if status != KERN_SUCCESS || count != TASK_BASIC_INFO_64_COUNT {
return Err("decode worker could not measure its address space".into());
}
Ok(info.virtual_size)
}
#[cfg(all(unix, not(target_os = "macos")))]
fn verify_parent_bound_address_space() -> Result<(), String> {
let mut limit = libc::rlimit {
rlim_cur: 0,
rlim_max: 0,
};
if unsafe { libc::getrlimit(libc::RLIMIT_AS, &mut limit) } != 0 {
return Err("decode worker could not read its address-space ceiling".into());
}
#[allow(clippy::useless_conversion)]
let current = u64::try_from(limit.rlim_cur).unwrap_or(u64::MAX);
#[allow(clippy::useless_conversion)]
let maximum = u64::try_from(limit.rlim_max).unwrap_or(u64::MAX);
if current != WORKER_ADDRESS_SPACE_BYTES || maximum != WORKER_ADDRESS_SPACE_BYTES {
return Err(
"decode worker refuses to parse input: its address-space ceiling values do not equal \
the configured worker budget"
.into(),
);
}
Ok(())
}
const EXIT_UNDECODABLE: i32 = 65;
fn retain_safe_environment(command: &mut crate::bounded_child::BoundedCommand) {
command.env_clear();
for name in ["LANG", "LC_ALL", "LC_CTYPE"] {
if let Some(value) = std::env::var_os(name) {
command.env(name, value);
}
}
}
const WORKER_CAPABLE_EXECUTABLES: [&str; 2] = ["minutes", "minutes-app"];
fn executable_handles_worker_protocol(path: &Path) -> bool {
path.file_stem()
.and_then(|stem| stem.to_str())
.is_some_and(|stem| WORKER_CAPABLE_EXECUTABLES.contains(&stem))
}
fn resolve_worker_executable() -> Result<crate::bounded_child::BoundExecutable, String> {
let current = std::env::current_exe()
.map_err(|_| "compressed audio decode worker host was unavailable".to_string())?;
if executable_handles_worker_protocol(¤t) {
if let Ok(executable) = crate::bounded_child::BoundExecutable::current() {
return Ok(executable);
}
}
let helper_name = format!("minutes{}", std::env::consts::EXE_SUFFIX);
#[allow(unused_mut)]
let mut candidates = vec![current.parent().map(|parent| parent.join(&helper_name))];
#[cfg(test)]
candidates.push(
current
.parent()
.and_then(|parent| parent.parent())
.map(|grandparent| grandparent.join(&helper_name)),
);
let adjacent = candidates
.into_iter()
.flatten()
.find(|candidate| candidate.is_file() && candidate != ¤t);
let mut bind_failure = None;
if let Some(helper) = adjacent {
match crate::bounded_child::BoundExecutable::bind(&helper) {
Ok(executable) => return Ok(executable),
Err(error) => bind_failure = Some(error),
}
}
if !executable_handles_worker_protocol(¤t) {
return Err(match bind_failure {
Some(error) => format!(
"compressed audio decode worker is unavailable because the Minutes binary \
beside this process could not be bound: {error}"
),
None => "compressed audio decode worker is unavailable because no Minutes binary \
was found next to this process"
.to_string(),
});
}
crate::bounded_child::BoundExecutable::current()
.map_err(|_| "compressed audio decode worker executable could not be resolved".to_string())
}
pub fn bounded_decode_fallback_enabled(config: &crate::config::Config) -> bool {
config.transcription.compressed_decode_fallback
}
pub fn bounded_decode_fallback_available(config: &crate::config::Config) -> bool {
bounded_decode_fallback_enabled(config) && resolve_worker_executable().is_ok()
}
#[derive(Clone, Copy)]
enum WorkerMode {
Decode,
ProbeDuration,
}
fn build_decode_command(
path: &Path,
mode: WorkerMode,
) -> Result<crate::bounded_child::BoundedCommand, String> {
let executable = resolve_worker_executable()?;
let mut command = crate::bounded_child::BoundedCommand::from_bound_executable(executable)
.map_err(|_| "compressed audio decode worker authority could not be bound".to_string())?;
retain_safe_environment(&mut command);
command.env(WORKER_MARKER, "1");
if matches!(mode, WorkerMode::ProbeDuration) {
command.arg(PROBE_DURATION_ARG);
}
command
.arg("--")
.arg(path)
.single_process()
.close_extra_descriptors();
#[cfg(not(target_os = "macos"))]
command.address_space_limit(WORKER_ADDRESS_SPACE_BYTES);
Ok(command)
}
pub(crate) fn decode_to_private_pcm(
path: &Path,
destination: &mut crate::pipeline::PrivateAudioTempFile,
max_output_bytes: u64,
wall_clock: Duration,
) -> Result<(), String> {
let mut command = build_decode_command(path, WorkerMode::Decode)?;
let output = crate::pipeline::output_with_authorized_audio_stdin_to_private_file_with_budget(
&mut command,
None,
destination,
max_output_bytes,
wall_clock,
)
.map_err(|error| {
if crate::bounded_child::is_spawn_failure(&error) {
format!("compressed audio decode worker could not be started: {error}")
} else {
format!("compressed audio decode worker failed: {error}")
}
})?;
if output.status.success() {
return Ok(());
}
let stderr = String::from_utf8_lossy(&output.stderr);
let detail = stderr.lines().last().unwrap_or("unknown error").to_string();
if output.status.code() == Some(EXIT_UNDECODABLE) {
Err(format!("the audio could not be decoded: {detail}"))
} else {
Err(format!(
"compressed audio decode worker failed closed: {detail}"
))
}
}
pub fn maybe_run_audio_decode_worker() -> Option<i32> {
let marker = std::env::var_os(WORKER_MARKER)?;
std::env::remove_var(WORKER_MARKER);
if marker != "1" {
eprintln!(
"{WORKER_MARKER} was set to an unrecognized value; refusing to run as a decode worker"
);
return Some(EXIT_UNDECODABLE);
}
#[cfg(target_os = "macos")]
if let Err(error) = install_child_address_space_ceiling() {
eprintln!("{error}");
return Some(71);
}
#[cfg(all(unix, not(target_os = "macos")))]
if let Err(error) = verify_parent_bound_address_space() {
eprintln!("{error}");
return Some(71);
}
let probe_only = std::env::args_os().any(|argument| argument == PROBE_DURATION_ARG);
let path = std::env::args_os()
.skip_while(|argument| argument != "--")
.nth(1)
.map(PathBuf::from);
let Some(path) = path else {
eprintln!("compressed audio decode worker requires exactly one input path");
return Some(EXIT_UNDECODABLE);
};
Some(if probe_only {
run_probe(&path)
} else {
run_worker(&path)
})
}
const PROBE_DURATION_ARG: &str = "--probe-duration";
pub(crate) fn probe_compressed_duration(
path: &Path,
wall_clock: Duration,
) -> Option<std::time::Duration> {
let label = crate::pipeline::private_audio_diagnostic_label(path);
let mut command = match build_decode_command(path, WorkerMode::ProbeDuration) {
Ok(command) => command,
Err(error) => {
tracing::warn!(
path = %label,
%error,
"compressed duration probe could not be built; content-type routing falls back to config"
);
return None;
}
};
let run = match crate::bounded_child::run(
&mut command,
None,
crate::bounded_child::StdoutTarget::Capture { max_bytes: 128 },
crate::bounded_child::ChildBudget {
wall_clock,
stderr_tail: 4 * 1024,
},
) {
Ok(run) => run,
Err(error) => {
tracing::warn!(
path = %label,
%error,
"compressed duration probe could not be launched; content-type routing falls back to config"
);
return None;
}
};
if run.timed_out || !run.output.status.success() {
tracing::warn!(
path = %label,
timed_out = run.timed_out,
exit = ?run.output.status.code(),
detail = %String::from_utf8_lossy(&run.output.stderr)
.lines()
.last()
.unwrap_or("no detail")
.chars()
.take(200)
.collect::<String>(),
"compressed duration probe failed; content-type routing falls back to config"
);
return None;
}
let reported = String::from_utf8_lossy(&run.output.stdout)
.trim()
.to_string();
let Ok(seconds) = reported.parse::<f64>() else {
tracing::warn!(
path = %label,
"compressed duration probe returned no parseable duration; content-type routing falls back to config"
);
return None;
};
if !(seconds.is_finite() && seconds > 0.0) {
tracing::warn!(
path = %label,
seconds,
"compressed duration probe reported an unusable duration; content-type routing falls back to config"
);
return None;
}
Some(std::time::Duration::from_secs_f64(seconds))
}
fn probe_duration_seconds(path: &Path) -> Result<f64, String> {
use symphonia::core::codecs::CODEC_TYPE_NULL;
use symphonia::core::formats::FormatOptions;
use symphonia::core::io::MediaSourceStream;
use symphonia::core::meta::MetadataOptions;
use symphonia::core::probe::Hint;
let file = std::fs::File::open(path).map_err(|error| format!("input unavailable: {error}"))?;
let stream = MediaSourceStream::new(Box::new(file), Default::default());
let mut hint = Hint::new();
if let Some(extension) = path.extension().and_then(|value| value.to_str()) {
hint.with_extension(extension);
}
let probed = symphonia::default::get_probe()
.format(
&hint,
stream,
&FormatOptions::default(),
&MetadataOptions::default(),
)
.map_err(|error| format!("probe failed: {error}"))?;
let track = probed
.format
.tracks()
.iter()
.find(|track| track.codec_params.codec != CODEC_TYPE_NULL)
.ok_or_else(|| "no audio track found".to_string())?;
let rate = track
.codec_params
.sample_rate
.ok_or_else(|| "container declared no sample rate".to_string())?;
let frames = track
.codec_params
.n_frames
.ok_or_else(|| "container declared no frame count".to_string())?;
if rate == 0 {
return Err("container declared a zero sample rate".into());
}
if let Some(time_base) = track.codec_params.time_base {
let time = time_base.calc_time(frames);
return Ok(time.seconds as f64 + time.frac);
}
Ok(frames as f64 / f64::from(rate))
}
fn run_probe(path: &Path) -> i32 {
match probe_duration_seconds(path) {
Ok(seconds) => {
println!("{seconds}");
0
}
Err(error) => {
eprintln!("{error}");
EXIT_UNDECODABLE
}
}
}
fn run_worker(path: &Path) -> i32 {
match decode_compressed_to_s16le(path) {
Ok(pcm) => {
let mut stdout = std::io::stdout().lock();
if stdout.write_all(&pcm).is_err() || stdout.flush().is_err() {
return 74;
}
0
}
Err(error) => {
eprintln!("{error}");
EXIT_UNDECODABLE
}
}
}
fn decode_compressed_to_s16le(path: &Path) -> Result<Vec<u8>, String> {
use symphonia::core::audio::SampleBuffer;
use symphonia::core::codecs::{DecoderOptions, CODEC_TYPE_NULL};
use symphonia::core::formats::FormatOptions;
use symphonia::core::io::MediaSourceStream;
use symphonia::core::meta::MetadataOptions;
use symphonia::core::probe::Hint;
let file = std::fs::File::open(path).map_err(|error| format!("input unavailable: {error}"))?;
let stream = MediaSourceStream::new(Box::new(file), Default::default());
let mut hint = Hint::new();
if let Some(extension) = path.extension().and_then(|value| value.to_str()) {
hint.with_extension(extension);
}
let probed = symphonia::default::get_probe()
.format(
&hint,
stream,
&FormatOptions::default(),
&MetadataOptions::default(),
)
.map_err(|error| format!("probe failed: {error}"))?;
let mut format = probed.format;
let track = format
.tracks()
.iter()
.find(|track| track.codec_params.codec != CODEC_TYPE_NULL)
.ok_or_else(|| "no audio track found".to_string())?;
let track_id = track.id;
let source_rate = track.codec_params.sample_rate.unwrap_or(44_100);
let channels = track
.codec_params
.channels
.map(|value| value.count())
.unwrap_or(1)
.max(1);
let mut decoder = symphonia::default::get_codecs()
.make(&track.codec_params, &DecoderOptions::default())
.map_err(|error| format!("decoder unavailable: {error}"))?;
let budget = crate::audio_budget::AudioWorkBudget::new();
budget
.validate_stream(source_rate, channels)
.map_err(|error| error.to_string())?;
let mut resampler: Option<crate::audio_budget::StreamingMonoResampler> = None;
let mut decoded_any = false;
loop {
let packet = match format.next_packet() {
Ok(packet) => packet,
Err(symphonia::core::errors::Error::ResetRequired) => {
return Err("stream reset mid-file; this container needs ffmpeg".into())
}
Err(_) => break,
};
budget
.check_deadline()
.map_err(|error| format!("decode exceeded its resource budget: {error}"))?;
if packet.track_id() != track_id {
continue;
}
let decoded = match decoder.decode(&packet) {
Ok(decoded) => decoded,
Err(symphonia::core::errors::Error::ResetRequired) => {
return Err("decoder reset mid-stream; this container needs ffmpeg".into())
}
Err(_) => continue,
};
let spec = *decoded.spec();
let resampler = match resampler.as_mut() {
Some(resampler) => resampler,
None => {
budget
.validate_stream(spec.rate, spec.channels.count().max(1))
.map_err(|error| error.to_string())?;
resampler.insert(
crate::audio_budget::StreamingMonoResampler::new(
spec.rate,
crate::audio_budget::CANONICAL_SAMPLE_RATE,
budget,
crate::audio_budget::MAX_CANONICAL_SAMPLES,
)
.map_err(|error| error.to_string())?,
)
}
};
let mut buffer = SampleBuffer::<f32>::new(decoded.capacity() as u64, spec);
buffer.copy_interleaved_ref(decoded);
let frame_channels = spec.channels.count().max(1);
for frame in buffer.samples().chunks(frame_channels) {
if frame.len() < frame_channels {
continue;
}
let mono = frame.iter().copied().sum::<f32>() / frame_channels as f32;
if !mono.is_finite() {
return Err("decoded audio contains a non-finite sample".into());
}
resampler
.push_mono_sample(mono)
.map_err(|error| format!("decode exceeded its resource budget: {error}"))?;
decoded_any = true;
}
}
if !decoded_any {
return Err("no decodable audio was found".into());
}
let samples = resampler
.ok_or_else(|| "no decodable audio was found".to_string())?
.finish()
.map_err(|error| format!("decode exceeded its resource budget: {error}"))?;
if samples.is_empty() {
return Err("no decodable audio was found".into());
}
let mut pcm = Vec::with_capacity(samples.len() * std::mem::size_of::<i16>());
for sample in samples {
let clamped = (sample.clamp(-1.0, 1.0) * i16::MAX as f32) as i16;
pcm.extend_from_slice(&clamped.to_le_bytes());
}
Ok(pcm)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn worker_marker_is_absent_in_an_ordinary_process() {
std::env::remove_var(WORKER_MARKER);
assert!(maybe_run_audio_decode_worker().is_none());
}
#[test]
fn the_fallback_is_on_by_default_and_can_be_refused() {
let mut config = crate::config::Config::default();
assert!(
bounded_decode_fallback_enabled(&config),
"compressed-import fallback must default to on"
);
config.transcription.compressed_decode_fallback = false;
assert!(!bounded_decode_fallback_enabled(&config));
}
#[test]
fn an_existing_config_without_the_field_keeps_the_fallback() {
let existing: crate::config::TranscriptionConfig =
toml::from_str("engine = \"whisper\"\n").unwrap();
assert!(existing.compressed_decode_fallback);
}
#[cfg(not(target_os = "macos"))]
#[test]
fn the_production_decode_command_carries_the_address_space_ceiling() {
let nonexistent_input = std::env::temp_dir()
.join("minutes-nonexistent-audio")
.join("input.m4a");
let command = build_decode_command(&nonexistent_input, WorkerMode::Decode)
.expect("the decode command must be constructible in the test tree");
assert_eq!(
command.configured_address_space_limit(),
Some(WORKER_ADDRESS_SPACE_BYTES),
"the decode child must be launched under an address-space ceiling"
);
}
#[cfg(target_os = "macos")]
#[test]
fn the_macos_decode_command_defers_its_ceiling_to_the_child() {
let command = build_decode_command(Path::new("/nonexistent/input.m4a"), WorkerMode::Decode)
.expect("the decode command must be constructible in the test tree");
assert_eq!(command.configured_address_space_limit(), None);
}
#[cfg(target_os = "macos")]
#[test]
fn the_macos_child_ceiling_refuses_an_over_budget_mapping() {
const CHILD_ENV: &str = "MINUTES_AUDIO_DECODE_CEILING_TEST_CHILD";
if std::env::var_os(CHILD_ENV).is_some() {
install_child_address_space_ceiling()
.expect("the decode child ceiling must install on macOS");
let requested = usize::try_from(WORKER_ADDRESS_SPACE_BYTES)
.unwrap()
.checked_add(16 * 1024)
.unwrap();
let mapping = unsafe {
libc::mmap(
std::ptr::null_mut(),
requested,
libc::PROT_NONE,
libc::MAP_PRIVATE | libc::MAP_ANON,
-1,
0,
)
};
if mapping != libc::MAP_FAILED {
unsafe {
libc::munmap(mapping, requested);
}
panic!("Darwin permitted a mapping larger than the decode child's growth budget");
}
return;
}
let mut command = crate::engine_process::command(std::env::current_exe().unwrap());
command
.arg("--exact")
.arg(
"audio_decode_worker::tests::the_macos_child_ceiling_refuses_an_over_budget_mapping",
)
.arg("--nocapture")
.env(CHILD_ENV, "1");
let output = command.output().unwrap();
assert!(
output.status.success(),
"macOS ceiling child failed:\nstdout:\n{}\nstderr:\n{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr),
);
}
#[cfg(not(target_os = "macos"))]
#[test]
fn the_probe_command_carries_the_same_ceiling_as_the_decode_command() {
let nonexistent_input = std::env::temp_dir()
.join("minutes-nonexistent-audio")
.join("input.m4a");
let decode = build_decode_command(&nonexistent_input, WorkerMode::Decode)
.expect("decode command must be constructible in the test tree");
let probe = build_decode_command(&nonexistent_input, WorkerMode::ProbeDuration)
.expect("probe command must be constructible in the test tree");
assert_eq!(
probe.configured_address_space_limit(),
Some(WORKER_ADDRESS_SPACE_BYTES)
);
assert_eq!(
probe.configured_address_space_limit(),
decode.configured_address_space_limit(),
"both children parse hostile containers and must be bounded identically"
);
}
#[test]
fn a_mid_stream_reset_fails_instead_of_truncating() {
const CHAINED: &[u8] = include_bytes!("../resources/decode-fixture-chained.ogg");
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("chained.ogg");
std::fs::write(&path, CHAINED).unwrap();
let first_stream = probe_duration_seconds(&path)
.expect("the chained fixture's first logical stream must be probeable");
assert!(
(2.5..=3.5).contains(&first_stream),
"the fixture's first stream must be the ~3 s one this test reasons about, got \
{first_stream}; if it was regenerated, re-read the provenance commands above"
);
match decode_compressed_to_s16le(&path) {
Ok(pcm) => panic!(
"a chained stream must not be reported as a complete decode: got {} samples, \
{:.2} s at 16 kHz, from a 5 s file",
pcm.len() / 2,
(pcm.len() / 2) as f64 / 16_000.0
),
Err(error) => assert!(
error.contains("reset"),
"expected the reset to be named so the user knows why: {error}"
),
}
}
#[test]
fn undecodable_input_fails_closed_rather_than_returning_silence() {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("not-audio.m4a");
std::fs::write(&path, b"this is not a media container").unwrap();
let error = decode_compressed_to_s16le(&path).unwrap_err();
assert!(
error.contains("probe failed") || error.contains("no audio track found"),
"unexpected failure for a non-container input: {error}"
);
}
#[test]
fn missing_input_is_reported_rather_than_panicking() {
let directory = tempfile::tempdir().unwrap();
let error = decode_compressed_to_s16le(&directory.path().join("absent.mp3")).unwrap_err();
assert!(error.contains("input unavailable"));
}
#[test]
fn a_non_minutes_host_refuses_to_self_exec() {
assert!(!executable_handles_worker_protocol(Path::new(
"/tmp/minutes_core-0123456789abcdef"
)));
assert!(!executable_handles_worker_protocol(Path::new(
"/usr/bin/env"
)));
assert!(executable_handles_worker_protocol(Path::new(
"/usr/local/bin/minutes"
)));
assert!(executable_handles_worker_protocol(Path::new(
"/Applications/Minutes.app/Contents/MacOS/minutes-app"
)));
}
fn write_test_wav(path: &Path, sample_rate: u32, frames: usize) {
let spec = hound::WavSpec {
channels: 1,
sample_rate,
bits_per_sample: 16,
sample_format: hound::SampleFormat::Int,
};
let mut writer = hound::WavWriter::create(path, spec).unwrap();
for index in 0..frames {
let phase = index as f32 / sample_rate as f32 * 440.0 * std::f32::consts::TAU;
writer
.write_sample((phase.sin() * 16_000.0) as i16)
.unwrap();
}
writer.finalize().unwrap();
}
#[test]
fn decode_resamples_to_canonical_sixteen_khz_mono_pcm() {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("tone.wav");
write_test_wav(&path, 44_100, 44_100);
let pcm = decode_compressed_to_s16le(&path).unwrap();
assert_eq!(pcm.len() % 2, 0, "s16le output must be whole samples");
let samples = pcm.len() / 2;
assert!(
(15_500..=16_500).contains(&samples),
"expected ~16000 samples, got {samples}"
);
assert!(
pcm.chunks_exact(2)
.any(|pair| i16::from_le_bytes([pair[0], pair[1]]).abs() > 1_000),
"decoded tone must carry real signal"
);
}
#[test]
fn decode_preserves_already_canonical_audio_length() {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("canonical.wav");
write_test_wav(&path, 16_000, 16_000);
let pcm = decode_compressed_to_s16le(&path).unwrap();
assert_eq!(pcm.len() / 2, 16_000);
}
#[test]
fn bounded_worker_child_round_trips_pcm_into_a_private_file() {
resolve_worker_executable()
.expect("a worker-capable executable must resolve for the end-to-end decode test");
let directory = tempfile::tempdir().unwrap();
let source = directory.path().join("tone.wav");
write_test_wav(&source, 44_100, 44_100);
let mut destination =
crate::pipeline::PrivateAudioTempFile::new("minutes-decode-test-", ".s16le").unwrap();
decode_to_private_pcm(
&source,
&mut destination,
crate::audio_budget::AudioWorkBudget::max_pcm_s16le_bytes(),
Duration::from_secs(120),
)
.unwrap();
let mut reader = destination.try_clone_reader().unwrap();
let mut pcm = Vec::new();
std::io::Read::read_to_end(&mut reader, &mut pcm).unwrap();
let samples = pcm.len() / 2;
assert!(
(15_500..=16_500).contains(&samples),
"expected ~16000 samples through the child, got {samples}"
);
}
const M4A_FIXTURE: &[u8] = include_bytes!("../resources/decode-fixture-tone.m4a");
const WEBM_FIXTURE: &[u8] = include_bytes!("../resources/decode-fixture-tone.webm");
#[test]
fn webm_duration_is_read_in_seconds_not_container_ticks() {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("meet-recording.webm");
std::fs::write(&path, WEBM_FIXTURE).unwrap();
let seconds = probe_duration_seconds(&path).expect("webm fixture must probe");
assert!(
(7.5..=8.5).contains(&seconds),
"8 s webm must probe as about 8 s, got {seconds}"
);
}
#[cfg(all(unix, not(target_os = "macos")))]
#[test]
fn the_production_probe_child_runs_under_an_address_space_ceiling() {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("memo.m4a");
std::fs::write(&path, M4A_FIXTURE).unwrap();
let executable = resolve_worker_executable()
.expect("a worker-capable executable must resolve for the end-to-end probe test");
let mut unbounded = crate::bounded_child::BoundedCommand::from_bound_executable(executable)
.expect("the worker authority must bind");
retain_safe_environment(&mut unbounded);
unbounded.env(WORKER_MARKER, "1");
unbounded.arg(PROBE_DURATION_ARG).arg("--").arg(&path);
let refused = crate::bounded_child::run(
&mut unbounded,
None,
crate::bounded_child::StdoutTarget::Capture { max_bytes: 128 },
crate::bounded_child::ChildBudget {
wall_clock: Duration::from_secs(30),
stderr_tail: 4 * 1024,
},
)
.expect("an unbounded probe child must at least launch");
let diagnostic = String::from_utf8_lossy(&refused.output.stderr).into_owned();
assert_eq!(
refused.output.status.code(),
Some(71),
"an unbounded probe child must exit with the containment refusal code; got \
{:?} with stderr {diagnostic:?}. If this is not 71, the `minutes` binary beside \
this harness predates the worker's self-check and this test cannot observe the \
ceiling: rebuild it with `cargo build -p minutes-cli --no-default-features`",
refused.output.status.code()
);
assert!(
diagnostic.contains("address-space ceiling"),
"the refusal must name the ceiling so it cannot be confused with another \
fail-closed exit: {diagnostic:?}"
);
let seconds = probe_compressed_duration(&path, Duration::from_secs(30))
.expect("the production probe must report the fixture duration");
assert!(
(0.75..=1.25).contains(&seconds.as_secs_f64()),
"1 s m4a must probe as about 1 s, got {seconds:?}"
);
}
#[cfg(all(unix, not(target_os = "macos")))]
#[test]
fn a_ceiling_that_is_not_the_worker_budget_is_refused() {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("memo.m4a");
std::fs::write(&path, M4A_FIXTURE).unwrap();
let executable = resolve_worker_executable()
.expect("a worker-capable executable must resolve for the ceiling-value test");
let mut foreign = crate::bounded_child::BoundedCommand::from_bound_executable(executable)
.expect("the worker authority must bind");
retain_safe_environment(&mut foreign);
foreign.env(WORKER_MARKER, "1");
foreign.arg(PROBE_DURATION_ARG).arg("--").arg(&path);
foreign.address_space_limit(2 * 1024 * 1024 * 1024);
let run = crate::bounded_child::run(
&mut foreign,
None,
crate::bounded_child::StdoutTarget::Capture { max_bytes: 128 },
crate::bounded_child::ChildBudget {
wall_clock: Duration::from_secs(30),
stderr_tail: 4 * 1024,
},
)
.expect("a child under a foreign ceiling must still launch");
let diagnostic = String::from_utf8_lossy(&run.output.stderr).into_owned();
assert_eq!(
run.output.status.code(),
Some(71),
"a ceiling that is not the worker budget must be refused; got {:?} with stderr \
{diagnostic:?}",
run.output.status.code()
);
assert!(
diagnostic.contains("address-space ceiling"),
"{diagnostic:?}"
);
}
#[cfg(target_os = "linux")]
#[test]
fn a_soft_ceiling_the_child_could_raise_is_refused() {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("memo.m4a");
std::fs::write(&path, M4A_FIXTURE).unwrap();
let current = std::env::current_exe().unwrap();
let helper = current
.parent()
.and_then(|parent| parent.parent())
.map(|grandparent| grandparent.join("minutes"))
.filter(|candidate| candidate.is_file())
.expect(
"this test needs a worker-capable binary beside the harness; build one with \
`cargo build -p minutes-cli --no-default-features`",
);
let budget_kib = (WORKER_ADDRESS_SPACE_BYTES / 1024).to_string();
let script = format!(
"ulimit -H -v unlimited 2>/dev/null; ulimit -S -v {budget_kib} || exit 70; \
exec \"$1\" {PROBE_DURATION_ARG} -- \"$2\""
);
let output = std::process::Command::new("/bin/sh")
.arg("-c")
.arg(&script)
.arg("minutes-soft-ceiling-probe")
.arg(&helper)
.arg(&path)
.env_clear()
.env(WORKER_MARKER, "1")
.output()
.expect("the shell wrapper must launch");
let diagnostic = String::from_utf8_lossy(&output.stderr).into_owned();
assert_ne!(
output.status.code(),
Some(70),
"the shell could not set a soft-only ceiling, so this test proves nothing: \
{diagnostic:?}"
);
assert_eq!(
output.status.code(),
Some(71),
"a soft ceiling the child could raise must be refused; got {:?} with stderr \
{diagnostic:?}",
output.status.code()
);
assert!(
diagnostic.contains("address-space ceiling"),
"{diagnostic:?}"
);
}
#[test]
fn m4a_duration_is_unchanged_by_the_time_base_reading() {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("memo.m4a");
std::fs::write(&path, M4A_FIXTURE).unwrap();
let seconds = probe_duration_seconds(&path).expect("m4a fixture must probe");
assert!(
(0.75..=1.25).contains(&seconds),
"1 s m4a must probe as about 1 s, got {seconds}"
);
}
#[test]
fn compressed_m4a_decodes_without_ffmpeg_at_decode_time() {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("memo.m4a");
std::fs::write(&path, M4A_FIXTURE).unwrap();
let pcm = decode_compressed_to_s16le(&path).unwrap();
let samples = pcm.len() / 2;
assert!(
(14_000..=18_000).contains(&samples),
"expected roughly one second of 16 kHz audio, got {samples}"
);
assert!(
pcm.chunks_exact(2)
.any(|pair| i16::from_le_bytes([pair[0], pair[1]]).abs() > 1_000),
"decoded memo must carry real signal"
);
}
#[test]
fn compressed_import_survives_an_unavailable_ffmpeg() {
let directory = tempfile::tempdir().unwrap();
let path = directory.path().join("memo.m4a");
std::fs::write(&path, M4A_FIXTURE).unwrap();
let guard = crate::test_home_env_lock();
let previous = std::env::var_os("MINUTES_FFMPEG");
std::env::set_var("MINUTES_FFMPEG", directory.path().join("absent-ffmpeg"));
let decoded =
crate::transcribe::decode_compressed_for_test(&path, &crate::config::Config::default());
match previous {
Some(value) => std::env::set_var("MINUTES_FFMPEG", value),
None => std::env::remove_var("MINUTES_FFMPEG"),
}
drop(guard);
let samples = decoded.expect("a compressed import must decode without ffmpeg");
assert!(
(14_000..=18_000).contains(&samples.len()),
"expected roughly one second at 16 kHz, got {}",
samples.len()
);
}
}