use crate::{
CapacityError, StorageLimits,
converter::{
FrameReblocker, InputNormalizer, OutputConverter, decode_samples_sanitized,
encode_samples_quantized, resolve_mixer_working_format, validate_channel_mapping,
},
mixer::{CspaMixer, InputDiagnosticSnapshot, MixStepOutcome, MixerInputPacket},
ordering::Failure,
planner::{CaptureRequest, is_unit_gain},
reads::{Cancellation, PartialReason, ReadError, ReadResult, Slice},
schema::{
AggregateManagerBudgets, BackendId, ByteOrder, CaptureTarget, DEFAULT_IDLE_GRACE_NS,
DitherMode, Format, Header, InputConversionPolicy, MAX_IDLE_BURST_CREDIT_NS,
MembershipDescriptor, MixedBlockMetadata, OutputConverterConfig, ParticipationState,
PlanError, PlatformOs, ProcessIdentity, Reason, SampleType, Stamp,
},
storage::{CopyStats, Pool},
stream_runtime::{
CallerWait, DeadlineSet, MAX_SESSION_SUBSCRIPTIONS, ReadySignal, SessionNotifier,
SessionSubscription,
},
traits::AudioStreamBackend,
};
use std::cell::Cell;
use std::collections::{BTreeMap, BTreeSet};
use std::sync::{
Arc, Mutex,
atomic::{AtomicUsize, Ordering::SeqCst},
};
use std::time::Instant;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum AdmissionError {
Invalid(CapacityError),
Full,
}
#[derive(Debug)]
struct Budget {
max_sessions: usize,
byte_ceiling: usize,
sessions: AtomicUsize,
bytes: AtomicUsize,
}
#[derive(Clone, Debug)]
pub struct StorageBudget(Arc<Budget>);
impl StorageBudget {
pub fn new(max_sessions: usize, byte_ceiling: usize) -> Result<Self, AdmissionError> {
if max_sessions == 0 || byte_ceiling == 0 {
return Err(AdmissionError::Invalid(CapacityError::Zero));
}
Ok(Self(Arc::new(Budget {
max_sessions,
byte_ceiling,
sessions: AtomicUsize::new(0),
bytes: AtomicUsize::new(0),
})))
}
#[allow(deprecated, reason = "fetch_update supports the minimum Rust version")]
pub fn reserve(
&self,
limits: StorageLimits,
metadata_bytes: usize,
) -> Result<StorageReservation, AdmissionError> {
let bytes = limits
.total_bytes()
.checked_add(metadata_bytes)
.ok_or(AdmissionError::Invalid(CapacityError::Overflow))?;
if bytes > self.0.byte_ceiling {
return Err(AdmissionError::Invalid(CapacityError::ExceedsByteCeiling));
}
self.0
.sessions
.fetch_update(SeqCst, SeqCst, |used| {
used.checked_add(1)
.filter(|next| *next <= self.0.max_sessions)
})
.map_err(|_| AdmissionError::Full)?;
if self
.0
.bytes
.fetch_update(SeqCst, SeqCst, |used| {
used.checked_add(bytes)
.filter(|next| *next <= self.0.byte_ceiling)
})
.is_err()
{
self.0.sessions.fetch_sub(1, SeqCst);
return Err(AdmissionError::Full);
}
Ok(StorageReservation(Arc::new(Reservation {
budget: self.0.clone(),
pcm_bytes: limits.total_bytes(),
bytes,
counts_session: true,
})))
}
#[allow(deprecated, reason = "fetch_update supports the minimum Rust version")]
pub fn reserve_auxiliary_bytes(
&self,
limits: StorageLimits,
metadata_bytes: usize,
) -> Result<StorageReservation, AdmissionError> {
let bytes = limits
.total_bytes()
.checked_add(metadata_bytes)
.ok_or(AdmissionError::Invalid(CapacityError::Overflow))?;
if bytes > self.0.byte_ceiling {
return Err(AdmissionError::Invalid(CapacityError::ExceedsByteCeiling));
}
self.0
.bytes
.fetch_update(SeqCst, SeqCst, |used| {
used.checked_add(bytes)
.filter(|next| *next <= self.0.byte_ceiling)
})
.map_err(|_| AdmissionError::Full)?;
Ok(StorageReservation(Arc::new(Reservation {
budget: self.0.clone(),
pcm_bytes: limits.total_bytes(),
bytes,
counts_session: false,
})))
}
pub fn resident_sessions(&self) -> usize {
self.0.sessions.load(SeqCst)
}
pub fn reserved_bytes(&self) -> usize {
self.0.bytes.load(SeqCst)
}
}
#[derive(Debug)]
struct Reservation {
budget: Arc<Budget>,
pcm_bytes: usize,
bytes: usize,
counts_session: bool,
}
impl Drop for Reservation {
fn drop(&mut self) {
self.budget.bytes.fetch_sub(self.bytes, SeqCst);
if self.counts_session {
self.budget.sessions.fetch_sub(1, SeqCst);
}
}
}
#[derive(Debug)]
pub struct StorageReservation(Arc<Reservation>);
impl StorageReservation {
pub fn retain(&self) -> Self {
Self(self.0.clone())
}
pub fn pcm_bytes(&self) -> usize {
self.0.pcm_bytes
}
pub fn total_bytes(&self) -> usize {
self.0.bytes
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Visibility {
Complete,
Limited,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ManagerError {
InvalidConfiguration,
InvalidState,
InvalidObservation,
UnknownVisibility,
Ambiguous,
CandidateCapacity,
EventCapacity,
Capacity,
Deadline,
CleanupTimeout,
Permission,
Unsupported,
OpenFailed,
Exhausted,
WorkingFormatChanged,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum BoundaryKind {
SessionChanged,
ConfigurationChanged,
DeviceChanged,
FormatChanged,
Gap,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SessionBoundary {
pub session: u64,
pub segment: u64,
pub kind: BoundaryKind,
pub format: Arc<Format>,
pub device_id: Option<Arc<str>>,
pub identity: Option<ProcessIdentity>,
}
impl From<PlanError> for ManagerError {
fn from(error: PlanError) -> Self {
match error {
PlanError::InvalidTarget
| PlanError::ReversedStrategyRange
| PlanError::InvalidBackend => Self::InvalidConfiguration,
PlanError::UnsupportedScope
| PlanError::PreciseTimingUnqualified
| PlanError::UnsupportedCapturePlan => Self::Unsupported,
PlanError::PermissionDenied => Self::Permission,
PlanError::BackendUnavailable | PlanError::NoSuchProcess | PlanError::PidReused => {
Self::OpenFailed
}
PlanError::Capacity(_) => Self::Capacity,
}
}
}
pub struct NativeTreeMixTopology {
max_links: usize,
source_to_targets: BTreeMap<Arc<str>, BTreeSet<usize>>,
target_to_sources: BTreeMap<usize, BTreeSet<Arc<str>>>,
}
impl NativeTreeMixTopology {
pub fn new(max_links: usize) -> Result<Self, PlanError> {
if !(1..=256).contains(&max_links) {
return Err(PlanError::Capacity(CapacityError::ExceedsByteCeiling));
}
Ok(Self {
max_links,
source_to_targets: BTreeMap::new(),
target_to_sources: BTreeMap::new(),
})
}
pub fn active_link_count(&self) -> usize {
self.source_to_targets.len()
}
pub fn active_sources(&self) -> Vec<Arc<str>> {
self.source_to_targets.keys().cloned().collect()
}
pub fn attach_source(
&mut self,
target_index: usize,
source_id: impl Into<Arc<str>>,
) -> Result<bool, ManagerError> {
let source_id: Arc<str> = source_id.into();
if let Some(owners) = self.source_to_targets.get_mut(&source_id) {
owners.insert(target_index);
self.target_to_sources
.entry(target_index)
.or_default()
.insert(source_id);
return Ok(false);
}
if self.source_to_targets.len() >= self.max_links {
return Err(ManagerError::Capacity);
}
let mut owners = BTreeSet::new();
owners.insert(target_index);
self.source_to_targets.insert(source_id.clone(), owners);
self.target_to_sources
.entry(target_index)
.or_default()
.insert(source_id);
Ok(true)
}
pub fn retire_target(&mut self, target_index: usize) -> Vec<Arc<str>> {
let mut unlinked = Vec::new();
let Some(sources) = self.target_to_sources.remove(&target_index) else {
return unlinked;
};
for src in sources {
let remove_link = if let Some(owners) = self.source_to_targets.get_mut(&src) {
owners.remove(&target_index);
owners.is_empty()
} else {
false
};
if remove_link {
self.source_to_targets.remove(&src);
unlinked.push(src);
}
}
unlinked
}
pub fn reconfigure_targets(&mut self, mapping: &[Option<usize>]) -> Vec<Arc<str>> {
let mut new_target_to_sources: BTreeMap<usize, BTreeSet<Arc<str>>> = BTreeMap::new();
let mut new_source_to_targets: BTreeMap<Arc<str>, BTreeSet<usize>> = BTreeMap::new();
for (new_idx, mapped_old) in mapping.iter().enumerate() {
if let Some(old_idx) = *mapped_old
&& let Some(sources) = self.target_to_sources.get(&old_idx)
{
new_target_to_sources.insert(new_idx, sources.clone());
for src in sources {
new_source_to_targets
.entry(src.clone())
.or_default()
.insert(new_idx);
}
}
}
let mut unlinked = Vec::new();
for src in self.source_to_targets.keys() {
if !new_source_to_targets.contains_key(src) {
unlinked.push(src.clone());
}
}
self.target_to_sources = new_target_to_sources;
self.source_to_targets = new_source_to_targets;
unlinked
}
pub fn prune_missing_sources(
&mut self,
mut is_live: impl FnMut(&str) -> bool,
) -> Vec<Arc<str>> {
let mut stale = Vec::new();
for src in self.source_to_targets.keys() {
if !is_live(src.as_ref()) {
stale.push(src.clone());
}
}
for src in &stale {
if let Some(owners) = self.source_to_targets.remove(src) {
for t_idx in owners {
if let Some(set) = self.target_to_sources.get_mut(&t_idx) {
set.remove(src);
}
}
}
}
stale
}
}
#[derive(Debug)]
struct PendingOpenGuard {
pending: Arc<AtomicUsize>,
}
impl Drop for PendingOpenGuard {
fn drop(&mut self) {
self.pending.fetch_sub(1, SeqCst);
}
}
#[derive(Debug)]
pub struct PendingOpenTicket {
_guard: PendingOpenGuard,
}
#[derive(Clone)]
pub struct InputStatusHandle {
target_index: usize,
target_id: Arc<str>,
backend: BackendId,
native_format: Arc<Format>,
mixer_format: Arc<Format>,
is_resampled: bool,
identity_bypass: bool,
shared: Arc<Mutex<Vec<InputDiagnosticSnapshot>>>,
}
impl InputStatusHandle {
pub fn target_index(&self) -> usize {
self.target_index
}
pub fn target_id(&self) -> &Arc<str> {
&self.target_id
}
pub fn backend(&self) -> BackendId {
self.backend
}
pub fn format(&self) -> &Arc<Format> {
&self.native_format
}
pub fn native_format(&self) -> &Arc<Format> {
&self.native_format
}
pub fn mixer_format(&self) -> &Arc<Format> {
&self.mixer_format
}
pub fn is_resampled(&self) -> bool {
self.is_resampled
}
pub fn is_identity_bypass(&self) -> bool {
self.identity_bypass
}
pub fn snapshot(&self) -> Option<InputDiagnosticSnapshot> {
self.shared
.lock()
.unwrap_or_else(|e| e.into_inner())
.get(self.target_index)
.cloned()
}
}
struct InputPipelineSlot {
normalizer: InputNormalizer,
reblocker: FrameReblocker,
norm_scratch: Vec<f32>,
primary_scratch: Vec<f32>,
shifted_scratch: Vec<f32>,
out_block_scratch: Vec<f32>,
last_block: Vec<f32>,
has_last_block: bool,
sustained_deficit_since_ns: Option<u64>,
}
impl InputPipelineSlot {
fn new(
input_format: Format,
working_format: Format,
block_frames: usize,
max_input_frames_per_call: usize,
) -> Result<Self, Reason> {
let normalizer = InputNormalizer::new(
input_format,
working_format.clone(),
max_input_frames_per_call,
)?;
let out_ch = usize::from(working_format.channels());
let max_norm_out = normalizer.max_output_frames(max_input_frames_per_call);
let reblock_cap = max_norm_out + block_frames * 8;
let reblocker = FrameReblocker::new(out_ch, block_frames, reblock_cap)?;
let block_samples = block_frames * out_ch;
Ok(Self {
normalizer,
reblocker,
norm_scratch: Vec::with_capacity(max_norm_out * out_ch),
primary_scratch: vec![0.0_f32; block_samples],
shifted_scratch: vec![0.0_f32; block_samples],
out_block_scratch: vec![0.0_f32; block_samples],
last_block: vec![0.0_f32; block_samples],
has_last_block: false,
sustained_deficit_since_ns: None,
})
}
}
#[inline]
pub fn default_block_frames_for_rate(rate_hz: u32, max_frames_per_block: usize) -> usize {
let cap = max_frames_per_block.max(64);
((rate_hz / 100) as usize).clamp(64, cap)
}
pub trait ReadClock {
fn now_ns(&mut self) -> u64;
}
#[derive(Clone, Copy, Debug)]
pub struct MonotonicReadClock {
epoch: Instant,
}
impl Default for MonotonicReadClock {
fn default() -> Self {
Self::new()
}
}
impl MonotonicReadClock {
#[inline]
pub fn new() -> Self {
Self {
epoch: Instant::now(),
}
}
}
impl ReadClock for MonotonicReadClock {
#[inline]
fn now_ns(&mut self) -> u64 {
self.epoch.elapsed().as_nanos().min(u128::from(u64::MAX)) as u64
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum IdleClockState {
Unanchored,
ColdStart { origin_num: u128 },
Active { horizon_num: u128 },
Idle { next_due_num: u128 },
}
#[derive(Clone, Copy, Debug)]
pub struct IdleOutputClock {
rate_hz: u32,
quantum_frames: usize,
idle_grace_ns: u64,
max_burst_credit_ns: u64,
state: IdleClockState,
}
impl IdleOutputClock {
pub fn new(rate_hz: u32, quantum_frames: usize) -> Result<Self, Reason> {
Self::with_grace(rate_hz, quantum_frames, DEFAULT_IDLE_GRACE_NS)
}
pub fn with_grace(
rate_hz: u32,
quantum_frames: usize,
idle_grace_ns: u64,
) -> Result<Self, Reason> {
if rate_hz == 0 || quantum_frames == 0 {
return Err(Reason::InvalidFormat);
}
Ok(Self {
rate_hz,
quantum_frames,
idle_grace_ns,
max_burst_credit_ns: MAX_IDLE_BURST_CREDIT_NS,
state: IdleClockState::Unanchored,
})
}
#[inline]
pub fn rate_hz(&self) -> u32 {
self.rate_hz
}
#[inline]
pub fn quantum_frames(&self) -> usize {
self.quantum_frames
}
#[inline]
pub fn idle_grace_ns(&self) -> u64 {
self.idle_grace_ns
}
#[inline]
pub fn reset(&mut self) {
self.state = IdleClockState::Unanchored;
}
pub fn set_rate(&mut self, rate_hz: u32, quantum_frames: usize) -> Result<(), Reason> {
if rate_hz == 0 || quantum_frames == 0 {
return Err(Reason::InvalidFormat);
}
self.rate_hz = rate_hz;
self.quantum_frames = quantum_frames;
self.state = IdleClockState::Unanchored;
Ok(())
}
#[inline]
fn frames_to_num(&self, frames: usize, frame_rate_hz: u32) -> u128 {
if frame_rate_hz == self.rate_hz || frame_rate_hz == 0 {
(frames as u128) * 1_000_000_000u128
} else {
(frames as u128) * 1_000_000_000u128 * u128::from(self.rate_hz)
/ u128::from(frame_rate_hz)
}
}
#[inline]
pub fn record_real_frames(&mut self, now_ns: u64, frames: usize, frame_rate_hz: u32) {
if frames == 0 {
return;
}
let rate = u128::from(self.rate_hz);
let now_num = u128::from(now_ns) * rate;
let dur_num = self.frames_to_num(frames, frame_rate_hz);
let max_credit_num = u128::from(self.max_burst_credit_ns) * rate;
let next_horizon = match self.state {
IdleClockState::Active { horizon_num } => {
let floor = now_num.saturating_sub(dur_num);
(horizon_num.max(floor) + dur_num).min(now_num + max_credit_num)
}
IdleClockState::Unanchored
| IdleClockState::ColdStart { .. }
| IdleClockState::Idle { .. } => now_num + dur_num.min(max_credit_num),
};
self.state = IdleClockState::Active {
horizon_num: next_horizon,
};
}
#[inline]
pub fn note_input_activity(&mut self, now_ns: u64, frames: usize, frame_rate_hz: u32) {
if frames == 0 {
return;
}
let rate = u128::from(self.rate_hz);
let now_num = u128::from(now_ns) * rate;
let max_credit_num = u128::from(self.max_burst_credit_ns) * rate;
let dur_num = self
.frames_to_num(frames, frame_rate_hz)
.min(max_credit_num);
let target_horizon = now_num + dur_num;
let next_horizon = match self.state {
IdleClockState::Active { horizon_num } => horizon_num.max(target_horizon),
IdleClockState::Unanchored
| IdleClockState::ColdStart { .. }
| IdleClockState::Idle { .. } => target_horizon,
};
self.state = IdleClockState::Active {
horizon_num: next_horizon,
};
}
#[inline]
fn current_due_num(&mut self, now_ns: u64) -> u128 {
let rate = u128::from(self.rate_hz);
let now_num = u128::from(now_ns) * rate;
let grace_num = u128::from(self.idle_grace_ns) * rate;
if matches!(self.state, IdleClockState::Unanchored) {
self.state = IdleClockState::ColdStart {
origin_num: now_num,
};
}
match self.state {
IdleClockState::Unanchored => unreachable!(),
IdleClockState::ColdStart { origin_num } => origin_num + grace_num,
IdleClockState::Active { horizon_num } => horizon_num + grace_num,
IdleClockState::Idle { next_due_num } => next_due_num,
}
}
#[inline]
pub fn is_due(&mut self, now_ns: u64) -> bool {
let rate = u128::from(self.rate_hz);
let due_num = self.current_due_num(now_ns);
u128::from(now_ns) * rate >= due_num
}
#[inline]
pub fn next_deadline_ns(&mut self, now_ns: u64) -> u64 {
let rate = u128::from(self.rate_hz);
let next_num = self.current_due_num(now_ns);
next_num.div_ceil(rate).min(u128::from(u64::MAX)) as u64
}
pub fn poll_silence_quantum(
&mut self,
now_ns: u64,
blocking: bool,
) -> Result<usize, PartialReason> {
let rate = u128::from(self.rate_hz);
let now_num = u128::from(now_ns) * rate;
let due_num = self.current_due_num(now_ns);
if now_num < due_num {
return Err(if blocking {
PartialReason::Timeout
} else {
PartialReason::WouldBlock
});
}
let quantum_num = (self.quantum_frames as u128) * 1_000_000_000u128;
let anchor = if now_num.saturating_sub(due_num) > quantum_num {
now_num
} else {
due_num
};
self.state = IdleClockState::Idle {
next_due_num: anchor + quantum_num,
};
Ok(self.quantum_frames)
}
}
#[derive(Clone, Debug)]
pub struct OutputStageConfig {
pub input_format: Arc<Format>,
pub output_converter: Option<OutputConverterConfig>,
pub gain: f32,
pub clamp_f32: bool,
pub silence_on_idle: bool,
pub idle_grace_ns: u64,
pub output_queue_slots: usize,
pub quantum_frames: usize,
pub max_frames_per_block: usize,
}
pub struct OutputStage {
input_format: Arc<Format>,
output_format: Arc<Format>,
converter: Option<OutputConverter>,
gain: f32,
clamp_f32: bool,
silence_on_idle: bool,
idle_clock: IdleOutputClock,
max_frames_per_block: usize,
sample_counter: u64,
last_contributing_mask: u64,
out_pool: Pool,
out_bytes_scratch: Vec<u8>,
stage_f32_scratch: Vec<f32>,
pending_out_slice: Option<(Slice, MixedBlockMetadata)>,
pending_out_bytes: Option<(usize, usize, MixedBlockMetadata)>,
sequence: u64,
}
impl OutputStage {
pub fn new(cfg: OutputStageConfig, budget: &StorageBudget) -> Result<Self, ManagerError> {
if cfg.quantum_frames == 0
|| cfg.max_frames_per_block == 0
|| cfg.quantum_frames > cfg.max_frames_per_block
|| cfg.output_queue_slots == 0
|| !cfg.gain.is_finite()
|| cfg.gain < 0.0
{
return Err(ManagerError::InvalidConfiguration);
}
let converter = match &cfg.output_converter {
Some(conv_cfg) => Some(
OutputConverter::new(
(*cfg.input_format).clone(),
conv_cfg.clone(),
cfg.max_frames_per_block,
)
.map_err(|_| ManagerError::Unsupported)?,
),
None => None,
};
let output_format = Arc::new(
cfg.output_converter
.as_ref()
.map_or_else(|| (*cfg.input_format).clone(), |c| c.target_format.clone()),
);
let max_out_frames = converter.as_ref().map_or(cfg.max_frames_per_block, |conv| {
conv.max_output_frames(cfg.max_frames_per_block)
});
let out_quantum_frames = if converter.is_some() {
default_block_frames_for_rate(output_format.rate(), max_out_frames)
} else {
cfg.quantum_frames
};
let idle_clock = IdleOutputClock::with_grace(
output_format.rate(),
out_quantum_frames,
cfg.idle_grace_ns,
)
.map_err(|_| ManagerError::InvalidConfiguration)?;
let out_stride = output_format.bytes_per_frame();
let out_pool_frames = max_out_frames.max(cfg.max_frames_per_block);
let out_ceiling = cfg
.output_queue_slots
.checked_mul(out_pool_frames)
.and_then(|f| f.checked_mul(out_stride))
.ok_or(ManagerError::Capacity)?;
let out_limits = StorageLimits::new(
cfg.output_queue_slots,
out_pool_frames,
out_stride,
out_ceiling,
)
.map_err(|_| ManagerError::Capacity)?;
let out_res = budget
.reserve_auxiliary_bytes(out_limits, 0)
.map_err(|_| ManagerError::Capacity)?;
let out_pool =
Pool::new_reserved(out_limits, out_pool_frames, output_format.clone(), out_res)
.map_err(|_| ManagerError::Capacity)?;
let in_ch = usize::from(cfg.input_format.channels());
let out_ch = usize::from(output_format.channels());
let needs_stage_f32 = !is_unit_gain(cfg.gain) || cfg.clamp_f32 || cfg.silence_on_idle;
let stage_f32_cap = if needs_stage_f32 {
(cfg.max_frames_per_block * in_ch).max(out_quantum_frames * out_ch)
} else {
0
};
Ok(Self {
input_format: cfg.input_format,
output_format,
converter,
gain: cfg.gain,
clamp_f32: cfg.clamp_f32,
silence_on_idle: cfg.silence_on_idle,
idle_clock,
max_frames_per_block: cfg.max_frames_per_block,
sample_counter: 0,
last_contributing_mask: 0,
out_pool,
out_bytes_scratch: Vec::with_capacity(out_pool_frames * out_stride),
stage_f32_scratch: Vec::with_capacity(stage_f32_cap),
pending_out_slice: None,
pending_out_bytes: None,
sequence: 0,
})
}
#[inline]
pub fn input_format(&self) -> &Arc<Format> {
&self.input_format
}
#[inline]
pub fn output_format(&self) -> &Arc<Format> {
&self.output_format
}
#[inline]
pub fn silence_on_idle(&self) -> bool {
self.silence_on_idle
}
#[inline]
pub fn idle_clock(&self) -> &IdleOutputClock {
&self.idle_clock
}
#[inline]
pub fn idle_clock_mut(&mut self) -> &mut IdleOutputClock {
&mut self.idle_clock
}
#[inline]
pub fn clear_pending_output(&mut self) {
self.pending_out_slice = None;
self.pending_out_bytes = None;
}
#[inline]
pub fn has_pending_output(&self) -> bool {
self.pending_out_slice.is_some() || self.pending_out_bytes.is_some()
}
#[inline]
pub fn has_pending_real_output(&self) -> bool {
self.pending_out_slice
.as_ref()
.is_some_and(|(_, m)| !m.synthesized_silence)
|| self
.pending_out_bytes
.as_ref()
.is_some_and(|(_, _, m)| !m.synthesized_silence)
}
#[inline]
pub fn has_pending_silence_output(&self) -> bool {
self.pending_out_slice
.as_ref()
.is_some_and(|(_, m)| m.synthesized_silence)
|| self
.pending_out_bytes
.as_ref()
.is_some_and(|(_, _, m)| m.synthesized_silence)
}
#[inline]
pub fn evict_pending_silence(&mut self) {
if self
.pending_out_slice
.as_ref()
.is_some_and(|(_, m)| m.synthesized_silence)
{
self.pending_out_slice = None;
}
if self
.pending_out_bytes
.as_ref()
.is_some_and(|(_, _, m)| m.synthesized_silence)
{
self.pending_out_bytes = None;
}
}
#[inline]
pub fn out_bytes(&self) -> &[u8] {
&self.out_bytes_scratch
}
#[inline]
pub fn next_silence_deadline_ns(&mut self, now_ns: u64) -> Option<u64> {
self.silence_on_idle
.then(|| self.idle_clock.next_deadline_ns(now_ns))
}
pub fn reset_for_input_format(&mut self, new_input_format: Arc<Format>) -> Result<(), Reason> {
let next_in_quantum =
default_block_frames_for_rate(new_input_format.rate(), self.max_frames_per_block);
let out_quantum = if let Some(conv) = self.converter.as_mut() {
conv.reset_for_input_format((*new_input_format).clone())?;
let max_out = conv.max_output_frames(self.max_frames_per_block);
default_block_frames_for_rate(self.output_format.rate(), max_out)
} else {
if new_input_format.bytes_per_frame() != self.output_format.bytes_per_frame() {
return Err(Reason::FormatChanged);
}
self.output_format = new_input_format.clone();
next_in_quantum
};
self.idle_clock
.set_rate(self.output_format.rate(), out_quantum)?;
let needed_f32 = (self.max_frames_per_block * usize::from(new_input_format.channels()))
.max(out_quantum * usize::from(self.output_format.channels()));
if (!is_unit_gain(self.gain) || self.clamp_f32 || self.silence_on_idle)
&& self.stage_f32_scratch.capacity() < needed_f32
{
self.stage_f32_scratch
.reserve(needed_f32 - self.stage_f32_scratch.len());
}
self.input_format = new_input_format;
Ok(())
}
pub fn process_f32_samples(
&mut self,
in_samples: &[f32],
meta: &mut MixedBlockMetadata,
now_ns: u64,
) -> Result<usize, ReadError> {
let in_ch = usize::from(self.input_format.channels());
if !in_samples.len().is_multiple_of(in_ch) {
return Err(ReadError::InvalidDestination);
}
let in_frames = in_samples.len() / in_ch;
if in_frames > 0 {
self.evict_pending_silence();
self.idle_clock
.record_real_frames(now_ns, in_frames, self.input_format.rate());
self.last_contributing_mask = meta.contributing_mask;
}
self.stage_f32_internal(in_samples, meta)
}
pub fn process_f32_flushed_tail(
&mut self,
in_samples: &[f32],
meta: &mut MixedBlockMetadata,
) -> Result<usize, ReadError> {
let in_ch = usize::from(self.input_format.channels());
if !in_samples.len().is_multiple_of(in_ch) {
return Err(ReadError::InvalidDestination);
}
if !in_samples.is_empty() {
self.evict_pending_silence();
self.last_contributing_mask = meta.contributing_mask;
}
self.stage_f32_internal(in_samples, meta)
}
pub fn process_raw_bytes(
&mut self,
in_bytes: &[u8],
meta: &mut MixedBlockMetadata,
now_ns: u64,
) -> Result<usize, ReadError> {
let in_frames = self
.input_format
.frames_in(in_bytes.len())
.map_err(|_| ReadError::InvalidDestination)?;
if in_frames == 0 {
self.out_bytes_scratch.clear();
return Ok(0);
}
if in_frames > self.max_frames_per_block {
return Err(ReadError::InvalidDestination);
}
self.evict_pending_silence();
self.idle_clock
.record_real_frames(now_ns, in_frames, self.input_format.rate());
self.last_contributing_mask = meta.contributing_mask;
let out_frames = if is_unit_gain(self.gain) && !self.clamp_f32 {
if let Some(conv) = self.converter.as_mut() {
let prev = conv.stats();
let produced = conv
.convert_into(in_bytes, &mut self.out_bytes_scratch)
.map_err(|_| ReadError::InvalidDestination)?;
let next = conv.stats();
meta.clipped_samples = meta
.clipped_samples
.saturating_add(next.clipped_samples.saturating_sub(prev.clipped_samples));
meta.nonfinite_samples = meta.nonfinite_samples.saturating_add(
next.nonfinite_samples
.saturating_sub(prev.nonfinite_samples),
);
produced
} else {
self.out_bytes_scratch.clear();
self.out_bytes_scratch.extend_from_slice(in_bytes);
in_frames
}
} else {
let mut nonfinite = 0u64;
self.stage_f32_scratch.clear();
decode_samples_sanitized(
in_bytes,
self.input_format.sample(),
self.input_format.order(),
&mut self.stage_f32_scratch,
&mut nonfinite,
)
.map_err(|_| ReadError::InvalidDestination)?;
if nonfinite > 0 {
meta.nonfinite_samples = meta.nonfinite_samples.saturating_add(nonfinite);
meta.nonfinite_inputs |= 1;
}
let gain = self.gain;
let clamp_f32 = self.clamp_f32;
let mut clipped = 0u64;
for s in &mut self.stage_f32_scratch {
let scaled = *s * gain;
if scaled.abs() > 1.0 {
clipped += 1;
}
*s = if clamp_f32 {
scaled.clamp(-1.0, 1.0)
} else {
scaled
};
}
meta.clipped_samples = meta.clipped_samples.saturating_add(clipped);
if let Some(conv) = self.converter.as_mut() {
let prev = conv.stats();
let produced = conv
.convert_f32_into(&self.stage_f32_scratch, &mut self.out_bytes_scratch)
.map_err(|_| ReadError::InvalidDestination)?;
let next = conv.stats();
meta.clipped_samples = meta
.clipped_samples
.saturating_add(next.clipped_samples.saturating_sub(prev.clipped_samples));
produced
} else {
self.out_bytes_scratch.clear();
let mut enc_clipped = 0u64;
encode_samples_quantized(
&self.stage_f32_scratch,
self.output_format.sample(),
self.output_format.order(),
DitherMode::None,
0,
&mut self.sample_counter,
&mut enc_clipped,
&mut self.out_bytes_scratch,
);
in_frames
}
};
Ok(out_frames)
}
pub fn flush_converter_tail(
&mut self,
membership_version: u64,
failed_inputs: u64,
) -> Result<Option<(usize, MixedBlockMetadata)>, ReadError> {
if !self
.converter
.as_ref()
.is_some_and(OutputConverter::has_unflushed_tail)
{
return Ok(None);
}
self.evict_pending_silence();
let Some(conv) = self.converter.as_mut() else {
return Ok(None);
};
let prev = conv.stats();
let produced = conv
.flush_tail_into(&mut self.out_bytes_scratch)
.map_err(|_| ReadError::InvalidDestination)?;
if produced == 0 {
return Ok(None);
}
let next = conv.stats();
let clipped = next.clipped_samples.saturating_sub(prev.clipped_samples);
if self.clamp_f32 && self.output_format.sample() == SampleType::F32 {
match self.output_format.order() {
ByteOrder::Little => {
for chunk in self.out_bytes_scratch.as_chunks_mut::<4>().0 {
let v = f32::from_le_bytes(*chunk).clamp(-1.0, 1.0);
*chunk = v.to_le_bytes();
}
}
ByteOrder::Big => {
for chunk in self.out_bytes_scratch.as_chunks_mut::<4>().0 {
let v = f32::from_be_bytes(*chunk).clamp(-1.0, 1.0);
*chunk = v.to_be_bytes();
}
}
}
}
let meta = MixedBlockMetadata {
membership_version,
contributing_mask: self.last_contributing_mask.max(1),
failed_inputs,
synthesized_silence: false,
clipped_samples: clipped,
..Default::default()
};
Ok(Some((produced, meta)))
}
fn stage_f32_internal(
&mut self,
in_samples: &[f32],
meta: &mut MixedBlockMetadata,
) -> Result<usize, ReadError> {
let in_ch = usize::from(self.input_format.channels());
if !in_samples.len().is_multiple_of(in_ch) {
return Err(ReadError::InvalidDestination);
}
let in_frames = in_samples.len() / in_ch;
if in_frames == 0 {
self.out_bytes_scratch.clear();
return Ok(0);
}
if in_frames > self.max_frames_per_block {
return Err(ReadError::InvalidDestination);
}
if !is_unit_gain(self.gain) || self.clamp_f32 {
self.stage_f32_scratch.clear();
let gain = self.gain;
let clamp_f32 = self.clamp_f32;
let mut clipped = 0u64;
for &raw in in_samples {
let clean = if raw.is_finite() {
raw
} else {
meta.nonfinite_samples = meta.nonfinite_samples.saturating_add(1);
0.0
};
let scaled = clean * gain;
if scaled.abs() > 1.0 {
clipped += 1;
}
self.stage_f32_scratch.push(if clamp_f32 {
scaled.clamp(-1.0, 1.0)
} else {
scaled
});
}
meta.clipped_samples = meta.clipped_samples.saturating_add(clipped);
if let Some(conv) = self.converter.as_mut() {
let prev = conv.stats();
let produced = conv
.convert_f32_into(&self.stage_f32_scratch, &mut self.out_bytes_scratch)
.map_err(|_| ReadError::InvalidDestination)?;
let next = conv.stats();
meta.clipped_samples = meta
.clipped_samples
.saturating_add(next.clipped_samples.saturating_sub(prev.clipped_samples));
return Ok(produced);
}
self.out_bytes_scratch.clear();
match self.output_format.order() {
ByteOrder::Little => {
for &sample in &self.stage_f32_scratch {
self.out_bytes_scratch
.extend_from_slice(&sample.to_le_bytes());
}
}
ByteOrder::Big => {
for &sample in &self.stage_f32_scratch {
self.out_bytes_scratch
.extend_from_slice(&sample.to_be_bytes());
}
}
}
return Ok(in_frames);
}
if let Some(conv) = self.converter.as_mut() {
let prev = conv.stats();
let produced = conv
.convert_f32_into(in_samples, &mut self.out_bytes_scratch)
.map_err(|_| ReadError::InvalidDestination)?;
let next = conv.stats();
meta.clipped_samples = meta
.clipped_samples
.saturating_add(next.clipped_samples.saturating_sub(prev.clipped_samples));
meta.nonfinite_samples = meta.nonfinite_samples.saturating_add(
next.nonfinite_samples
.saturating_sub(prev.nonfinite_samples),
);
Ok(produced)
} else {
self.out_bytes_scratch.clear();
match self.output_format.order() {
ByteOrder::Little => {
for &sample in in_samples {
self.out_bytes_scratch
.extend_from_slice(&sample.to_le_bytes());
}
}
ByteOrder::Big => {
for &sample in in_samples {
self.out_bytes_scratch
.extend_from_slice(&sample.to_be_bytes());
}
}
}
Ok(in_frames)
}
}
pub fn poll_idle_silence(
&mut self,
now_ns: u64,
blocking: bool,
membership_version: u64,
failed_inputs: u64,
) -> Result<Result<(usize, MixedBlockMetadata), PartialReason>, ReadError> {
if !self.silence_on_idle {
return Ok(Err(if blocking {
PartialReason::Timeout
} else {
PartialReason::WouldBlock
}));
}
let out_q_frames = match self.idle_clock.poll_silence_quantum(now_ns, blocking) {
Ok(f) => f,
Err(reason) => return Ok(Err(reason)),
};
if let Some((tail_frames, tail_meta)) =
self.flush_converter_tail(membership_version, failed_inputs)?
{
return Ok(Ok((tail_frames, tail_meta)));
}
let meta = MixedBlockMetadata {
membership_version,
failed_inputs,
synthesized_silence: true,
..Default::default()
};
if let Some(conv) = self.converter.as_ref()
&& conv.dither() == DitherMode::Tpdf
&& self.output_format.sample() != SampleType::F32
{
let out_ch = usize::from(self.output_format.channels());
let silence_samples = out_q_frames * out_ch;
self.stage_f32_scratch.clear();
self.stage_f32_scratch.resize(silence_samples, 0.0);
self.out_bytes_scratch.clear();
let mut enc_clipped = 0u64;
encode_samples_quantized(
&self.stage_f32_scratch,
self.output_format.sample(),
self.output_format.order(),
DitherMode::Tpdf,
conv.seed(),
&mut self.sample_counter,
&mut enc_clipped,
&mut self.out_bytes_scratch,
);
Ok(Ok((out_q_frames, meta)))
} else {
let out_bytes_len = out_q_frames * self.output_format.bytes_per_frame();
self.out_bytes_scratch.clear();
self.out_bytes_scratch.resize(out_bytes_len, 0);
Ok(Ok((out_q_frames, meta)))
}
}
pub fn try_pop_pending_owned(
&mut self,
requested_frames: usize,
) -> Result<Option<(ReadResult, MixedBlockMetadata)>, ReadError> {
let req_frames = requested_frames.max(1);
if let Some((mut pending_slice, meta)) = self.pending_out_slice.take() {
let emit_frames = pending_slice.frames.min(req_frames);
let emit_slice = Slice {
block: pending_slice.block.clone(),
first: pending_slice.first,
frames: emit_frames,
};
if emit_frames < pending_slice.frames {
pending_slice.first += emit_frames;
pending_slice.frames -= emit_frames;
self.pending_out_slice = Some((pending_slice, meta));
}
let emit_bytes = emit_slice.bytes().len() as u64;
return Ok(Some((
ReadResult {
frames: emit_frames,
chunks: vec![emit_slice],
first_packet: None,
last_packet: None,
reason: PartialReason::Complete,
control: None,
copies: CopyStats {
bytes: emit_bytes,
destinations: 1,
..Default::default()
},
},
meta,
)));
}
if let Some((byte_off, rem_frames, meta)) = self.pending_out_bytes.take() {
let stride = self.out_pool.format().bytes_per_frame();
let emit_frames = rem_frames.min(req_frames);
let emit_bytes = emit_frames * stride;
self.sequence = self.sequence.saturating_add(1);
let hdr = Header {
sequence: self.sequence,
segment: meta.membership_version,
generation: 1,
frames: emit_frames,
sample_position: None,
timestamp: None,
};
let block = self
.out_pool
.offer(
&self.out_bytes_scratch[byte_off..byte_off + emit_bytes],
hdr,
)
.map_err(|_| ReadError::InvalidDestination)?;
if emit_frames < rem_frames {
self.pending_out_bytes =
Some((byte_off + emit_bytes, rem_frames - emit_frames, meta));
}
let slice = Slice {
block,
first: 0,
frames: emit_frames,
};
return Ok(Some((
ReadResult {
frames: emit_frames,
chunks: vec![slice],
first_packet: None,
last_packet: None,
reason: PartialReason::Complete,
control: None,
copies: CopyStats {
bytes: emit_bytes as u64,
destinations: 1,
..Default::default()
},
},
meta,
)));
}
Ok(None)
}
pub fn try_pop_pending_into(
&mut self,
dst: &mut [u8],
requested_frames: usize,
) -> Result<Option<(ReadResult, MixedBlockMetadata)>, ReadError> {
let req_frames = requested_frames.max(1);
let out_stride = self.output_format.bytes_per_frame();
if dst.len() < req_frames.saturating_mul(out_stride) {
return Err(ReadError::InvalidDestination);
}
if let Some((byte_off, rem_frames, meta)) = self.pending_out_bytes.take() {
let emit_frames = rem_frames.min(req_frames);
let emit_bytes = emit_frames * out_stride;
dst[..emit_bytes]
.copy_from_slice(&self.out_bytes_scratch[byte_off..byte_off + emit_bytes]);
if emit_frames < rem_frames {
self.pending_out_bytes =
Some((byte_off + emit_bytes, rem_frames - emit_frames, meta));
}
return Ok(Some((
ReadResult {
frames: emit_frames,
chunks: Vec::new(),
first_packet: None,
last_packet: None,
reason: PartialReason::Complete,
control: None,
copies: CopyStats {
bytes: emit_bytes as u64,
destinations: 1,
..Default::default()
},
},
meta,
)));
}
if let Some((mut pending_slice, meta)) = self.pending_out_slice.take() {
let emit_frames = pending_slice.frames.min(req_frames);
let emit_bytes = emit_frames * out_stride;
let src_bytes = pending_slice.bytes();
dst[..emit_bytes].copy_from_slice(&src_bytes[..emit_bytes]);
if emit_frames < pending_slice.frames {
pending_slice.first += emit_frames;
pending_slice.frames -= emit_frames;
self.pending_out_slice = Some((pending_slice, meta));
}
return Ok(Some((
ReadResult {
frames: emit_frames,
chunks: Vec::new(),
first_packet: None,
last_packet: None,
reason: PartialReason::Complete,
control: None,
copies: CopyStats {
bytes: emit_bytes as u64,
destinations: 1,
..Default::default()
},
},
meta,
)));
}
Ok(None)
}
pub fn finish_owned(
&mut self,
out_frames: usize,
requested_frames: usize,
meta: MixedBlockMetadata,
) -> Result<(ReadResult, MixedBlockMetadata), ReadError> {
let req_frames = requested_frames.max(1);
self.sequence = self.sequence.saturating_add(1);
let hdr = Header {
sequence: self.sequence,
segment: meta.membership_version,
generation: 1,
frames: out_frames,
sample_position: None,
timestamp: None,
};
let block = self
.out_pool
.offer(&self.out_bytes_scratch, hdr)
.map_err(|_| ReadError::InvalidDestination)?;
let emit_frames = out_frames.min(req_frames);
if emit_frames < out_frames {
self.pending_out_slice = Some((
Slice {
block: block.clone(),
first: emit_frames,
frames: out_frames - emit_frames,
},
meta,
));
}
let slice = Slice {
block,
first: 0,
frames: emit_frames,
};
let emit_bytes = slice.bytes().len() as u64;
Ok((
ReadResult {
frames: emit_frames,
chunks: vec![slice],
first_packet: None,
last_packet: None,
reason: PartialReason::Complete,
control: None,
copies: CopyStats {
bytes: emit_bytes,
destinations: 1,
..Default::default()
},
},
meta,
))
}
pub fn finish_into(
&mut self,
dst: &mut [u8],
out_frames: usize,
requested_frames: usize,
meta: MixedBlockMetadata,
) -> Result<(ReadResult, MixedBlockMetadata), ReadError> {
let req_frames = requested_frames.max(1);
let out_stride = self.output_format.bytes_per_frame();
if dst.len() < req_frames.saturating_mul(out_stride) {
return Err(ReadError::InvalidDestination);
}
self.sequence = self.sequence.saturating_add(1);
let emit_frames = out_frames.min(req_frames);
let emit_bytes = emit_frames * out_stride;
dst[..emit_bytes].copy_from_slice(&self.out_bytes_scratch[..emit_bytes]);
if emit_frames < out_frames {
self.pending_out_bytes = Some((emit_bytes, out_frames - emit_frames, meta));
}
Ok((
ReadResult {
frames: emit_frames,
chunks: Vec::new(),
first_packet: None,
last_packet: None,
reason: PartialReason::Complete,
control: None,
copies: CopyStats {
bytes: emit_bytes as u64,
destinations: 1,
..Default::default()
},
},
meta,
))
}
}
#[inline]
fn empty_read_result(reason: PartialReason) -> ReadResult {
ReadResult {
frames: 0,
chunks: Vec::new(),
first_packet: None,
last_packet: None,
reason,
control: None,
copies: Default::default(),
}
}
enum StageEmitOp {
Deliver(usize, MixedBlockMetadata),
PopPending,
}
pub struct PassThroughStage {
stage: OutputStage,
notifier: Arc<SessionNotifier>,
subscription: Option<SessionSubscription>,
clock: MonotonicReadClock,
max_frames_per_block: usize,
raw_in_scratch: Vec<u8>,
}
impl PassThroughStage {
pub fn new(
request: &CaptureRequest,
input_format: Arc<Format>,
max_frames_per_block: usize,
budget: &StorageBudget,
) -> Result<Self, ManagerError> {
let gain = request.targets.first().map_or(1.0, |t| t.gain);
let quantum_frames =
default_block_frames_for_rate(input_format.rate(), max_frames_per_block);
let stage = OutputStage::new(
OutputStageConfig {
input_format: input_format.clone(),
output_converter: request.output_converter.clone(),
gain,
clamp_f32: request.mixer_config.clamp_f32,
silence_on_idle: request.mixer_config.silence_on_idle,
idle_grace_ns: request.mixer_config.idle_grace_ns,
output_queue_slots: request.mixer_config.output_queue_slots,
quantum_frames,
max_frames_per_block,
},
budget,
)?;
let notifier = Arc::new(SessionNotifier::new(2).map_err(|_| ManagerError::Capacity)?);
let in_stride = input_format.bytes_per_frame();
Ok(Self {
stage,
notifier,
subscription: None,
clock: MonotonicReadClock::new(),
max_frames_per_block,
raw_in_scratch: vec![0u8; max_frames_per_block * in_stride],
})
}
#[inline]
pub fn output_format(&self) -> &Arc<Format> {
self.stage.output_format()
}
#[inline]
pub fn session_notifier(&self) -> &Arc<SessionNotifier> {
&self.notifier
}
#[inline]
pub fn clear_pending_output(&mut self) {
self.stage.clear_pending_output();
}
#[inline]
pub fn detach_stream(&mut self) {
self.subscription = None;
}
pub fn bind_stream_ready(&mut self, ready: &Arc<ReadySignal>) -> Result<(), ManagerError> {
self.subscription = None;
let sub = self
.notifier
.subscribe(ready)
.map_err(|_| ManagerError::Capacity)?;
self.subscription = Some(sub);
Ok(())
}
pub fn reset_for_stream(
&mut self,
new_input_format: Arc<Format>,
ready: &Arc<ReadySignal>,
) -> Result<(), ManagerError> {
self.subscription = None;
self.stage
.reset_for_input_format(new_input_format.clone())
.map_err(|_| ManagerError::Unsupported)?;
let needed_bytes = self.max_frames_per_block * new_input_format.bytes_per_frame();
if self.raw_in_scratch.len() < needed_bytes {
self.raw_in_scratch.resize(needed_bytes, 0);
}
self.bind_stream_ready(ready)
}
pub fn read_owned<S: AudioStreamBackend>(
&mut self,
stream: Option<&mut S>,
requested_frames: usize,
wait: CallerWait,
cancel: &Cancellation,
segment_id: u64,
relaunch_deadline_ns: Option<u64>,
) -> Result<(ReadResult, MixedBlockMetadata), ReadError> {
let mut clock = self.clock;
let res = self.read_owned_with_clock(
stream,
requested_frames,
wait,
cancel,
&mut clock,
segment_id,
relaunch_deadline_ns,
);
self.clock = clock;
res
}
#[allow(clippy::too_many_arguments)]
pub fn read_owned_with_clock<S: AudioStreamBackend, C: ReadClock>(
&mut self,
stream: Option<&mut S>,
requested_frames: usize,
wait: CallerWait,
cancel: &Cancellation,
clock: &mut C,
segment_id: u64,
relaunch_deadline_ns: Option<u64>,
) -> Result<(ReadResult, MixedBlockMetadata), ReadError> {
let req_frames = requested_frames.max(1);
if self.stage.has_pending_real_output()
&& let Some(popped) = self.stage.try_pop_pending_owned(req_frames)?
{
return Ok(popped);
}
self.schedule_core(
stream,
req_frames,
wait,
cancel,
clock,
segment_id,
relaunch_deadline_ns,
|stage, op| match op {
StageEmitOp::Deliver(out_frames, meta) => {
stage.finish_owned(out_frames, req_frames, meta).map(Some)
}
StageEmitOp::PopPending => stage.try_pop_pending_owned(req_frames),
},
)
}
#[allow(clippy::too_many_arguments)]
pub fn read_into<S: AudioStreamBackend>(
&mut self,
stream: Option<&mut S>,
dst: &mut [u8],
requested_frames: usize,
wait: CallerWait,
cancel: &Cancellation,
segment_id: u64,
relaunch_deadline_ns: Option<u64>,
) -> Result<(ReadResult, MixedBlockMetadata), ReadError> {
let mut clock = self.clock;
let res = self.read_into_with_clock(
stream,
dst,
requested_frames,
wait,
cancel,
&mut clock,
segment_id,
relaunch_deadline_ns,
);
self.clock = clock;
res
}
#[allow(clippy::too_many_arguments)]
pub fn read_into_with_clock<S: AudioStreamBackend, C: ReadClock>(
&mut self,
stream: Option<&mut S>,
dst: &mut [u8],
requested_frames: usize,
wait: CallerWait,
cancel: &Cancellation,
clock: &mut C,
segment_id: u64,
relaunch_deadline_ns: Option<u64>,
) -> Result<(ReadResult, MixedBlockMetadata), ReadError> {
let req_frames = requested_frames.max(1);
let out_stride = self.stage.output_format().bytes_per_frame();
if dst.len() < req_frames.saturating_mul(out_stride) {
return Err(ReadError::InvalidDestination);
}
if self.stage.has_pending_real_output()
&& let Some(popped) = self.stage.try_pop_pending_into(dst, req_frames)?
{
return Ok(popped);
}
self.schedule_core(
stream,
req_frames,
wait,
cancel,
clock,
segment_id,
relaunch_deadline_ns,
|stage, op| match op {
StageEmitOp::Deliver(out_frames, meta) => stage
.finish_into(dst, out_frames, req_frames, meta)
.map(Some),
StageEmitOp::PopPending => stage.try_pop_pending_into(dst, req_frames),
},
)
}
#[allow(clippy::too_many_arguments)]
fn schedule_core<S: AudioStreamBackend, C: ReadClock>(
&mut self,
mut stream: Option<&mut S>,
req_frames: usize,
wait: CallerWait,
cancel: &Cancellation,
clock: &mut C,
segment_id: u64,
relaunch_deadline_ns: Option<u64>,
mut finish_op: impl FnMut(
&mut OutputStage,
StageEmitOp,
)
-> Result<Option<(ReadResult, MixedBlockMetadata)>, ReadError>,
) -> Result<(ReadResult, MixedBlockMetadata), ReadError> {
let blocking = wait.is_blocking();
let start_ns = clock.now_ns();
let caller_ns = match wait {
CallerWait::Zero => Some(start_ns),
CallerWait::Bounded(dur) => {
let dur_ns = dur.as_nanos().min(u128::from(u64::MAX)) as u64;
Some(start_ns.saturating_add(dur_ns))
}
CallerWait::Unbounded => None,
};
let notifier = Arc::clone(&self.notifier);
let deadlines_cell = Cell::new(DeadlineSet {
caller_ns,
relaunch_ns: relaunch_deadline_ns,
..DeadlineSet::default()
});
let mut first_poll_ns = Some(start_ns);
notifier.poll_until(
cancel,
|| first_poll_ns.take().unwrap_or_else(|| clock.now_ns()),
|now_ns| deadlines_cell.get().wait_from(now_ns, blocking),
|now_ns| {
let idle_meta = MixedBlockMetadata {
membership_version: segment_id,
..Default::default()
};
if cancel.is_cancelled() {
return Some(Ok((empty_read_result(PartialReason::Cancelled), idle_meta)));
}
let mut saw_stream_eof = stream.is_none();
if let Some(active) = stream.as_deref_mut() {
let in_fmt = self.stage.input_format();
let in_rate = u64::from(in_fmt.rate().max(1));
let out_rate = u64::from(self.stage.output_format().rate().max(1));
let in_bpf = in_fmt.bytes_per_frame();
let pull_frames = (((req_frames as u64).saturating_mul(in_rate))
.div_ceil(out_rate) as usize)
.clamp(1, self.max_frames_per_block);
let dst_bytes = pull_frames * in_bpf;
if self.raw_in_scratch.len() < dst_bytes {
self.raw_in_scratch.resize(dst_bytes, 0);
}
loop {
let mut accum_in_bytes = 0usize;
let mut first_pkt = None;
let mut last_pkt = None;
while accum_in_bytes < dst_bytes {
let rem_frames = (dst_bytes - accum_in_bytes) / in_bpf;
match active.read_into_with_cancel(
&mut self.raw_in_scratch[accum_in_bytes..dst_bytes],
rem_frames,
std::time::Duration::ZERO,
cancel.clone(),
) {
Ok(raw_res) if raw_res.frames > 0 => {
if first_pkt.is_none() {
first_pkt = raw_res.first_packet;
}
if raw_res.last_packet.is_some() {
last_pkt = raw_res.last_packet;
}
accum_in_bytes += raw_res.frames * in_bpf;
if raw_res.reason == PartialReason::Eof {
saw_stream_eof = true;
break;
}
}
Ok(mut raw_res) if raw_res.reason == PartialReason::Boundary => {
if accum_in_bytes == 0 {
self.stage.evict_pending_silence();
if let Some(ref mut ctrl) = raw_res.control {
ctrl.format = self.stage.output_format().clone();
}
return Some(Ok((raw_res, idle_meta)));
}
break;
}
Ok(raw_res) if raw_res.reason == PartialReason::Eof => {
saw_stream_eof = true;
break;
}
Ok(raw_res)
if matches!(raw_res.reason, PartialReason::Failure(_)) =>
{
if accum_in_bytes == 0 {
self.stage.evict_pending_silence();
return Some(Ok((raw_res, idle_meta)));
}
break;
}
Ok(_) => break,
Err(err) => return Some(Err(err)),
}
}
if accum_in_bytes == 0 {
break;
}
let mut meta = MixedBlockMetadata {
membership_version: segment_id,
contributing_mask: 1,
skew_estimate_ns: Some(0),
skew_uncertainty_ns: Some(0),
..Default::default()
};
match self.stage.process_raw_bytes(
&self.raw_in_scratch[..accum_in_bytes],
&mut meta,
now_ns,
) {
Ok(out_frames) if out_frames > 0 => {
return Some(
match finish_op(
&mut self.stage,
StageEmitOp::Deliver(out_frames, meta),
) {
Ok(Some((mut res, final_meta))) => {
res.first_packet = first_pkt;
res.last_packet = last_pkt;
Ok((res, final_meta))
}
Ok(None) => Err(ReadError::InvalidDestination),
Err(err) => Err(err),
},
);
}
Ok(_) => {
if saw_stream_eof {
break;
}
}
Err(err) => return Some(Err(err)),
}
}
}
if saw_stream_eof && relaunch_deadline_ns.is_none_or(|dl| now_ns >= dl) {
self.stage.evict_pending_silence();
match self.stage.flush_converter_tail(segment_id, 0) {
Ok(Some((tail_frames, tail_meta))) => {
return Some(
match finish_op(
&mut self.stage,
StageEmitOp::Deliver(tail_frames, tail_meta),
) {
Ok(Some(res)) => Ok(res),
Ok(None) => Err(ReadError::InvalidDestination),
Err(err) => Err(err),
},
);
}
Ok(None) => {
return Some(Ok((empty_read_result(PartialReason::Eof), idle_meta)));
}
Err(err) => return Some(Err(err)),
}
}
if self.stage.has_pending_silence_output() {
match finish_op(&mut self.stage, StageEmitOp::PopPending) {
Ok(Some(popped)) => return Some(Ok(popped)),
Ok(None) => {}
Err(err) => return Some(Err(err)),
}
}
if self.stage.silence_on_idle() {
match self
.stage
.poll_idle_silence(now_ns, blocking, segment_id, 0)
{
Ok(Ok((out_frames, meta))) => {
return Some(
match finish_op(
&mut self.stage,
StageEmitOp::Deliver(out_frames, meta),
) {
Ok(Some(res)) => Ok(res),
Ok(None) => Err(ReadError::InvalidDestination),
Err(err) => Err(err),
},
);
}
Ok(Err(reason)) => {
if !blocking {
return Some(Ok((empty_read_result(reason), idle_meta)));
}
}
Err(err) => return Some(Err(err)),
}
}
if !blocking {
return Some(Ok((
empty_read_result(PartialReason::WouldBlock),
idle_meta,
)));
}
if caller_ns.is_some_and(|dl| now_ns >= dl) {
return Some(Ok((empty_read_result(PartialReason::Timeout), idle_meta)));
}
let silence_ns = self.stage.next_silence_deadline_ns(now_ns);
deadlines_cell.set(DeadlineSet {
caller_ns,
alignment_ns: None,
relaunch_ns: relaunch_deadline_ns,
silence_ns,
});
None
},
)
}
#[inline]
pub fn now_ns(&mut self) -> u64 {
self.clock.now_ns()
}
}
pub struct MultiInputManager {
request: CaptureRequest,
working_format: Arc<Format>,
output_format: Arc<Format>,
block_frames: usize,
max_frames_per_block: usize,
storage_budget: StorageBudget,
pending_opens: Arc<AtomicUsize>,
notifier: Arc<SessionNotifier>,
clock: MonotonicReadClock,
topology: NativeTreeMixTopology,
pipelines: Vec<Option<InputPipelineSlot>>,
relaunch_deadlines_ns: Vec<Option<u64>>,
mixer: CspaMixer,
output_stage: OutputStage,
diagnostics: Arc<Mutex<Vec<InputDiagnosticSnapshot>>>,
input_handles: Vec<InputStatusHandle>,
mix_scratch: Vec<f32>,
last_metadata: Option<MixedBlockMetadata>,
}
impl MultiInputManager {
pub fn new(
request: CaptureRequest,
native_format: Arc<Format>,
max_frames_per_block: usize,
) -> Result<Self, ManagerError> {
let default_backend = request.backends.primary_for_os(PlatformOs::current());
let per_input: Vec<(BackendId, Arc<Format>)> = request
.targets
.iter()
.map(|t| (t.backend.unwrap_or(default_backend), native_format.clone()))
.collect();
Self::new_with_block_frames(
request,
per_input,
max_frames_per_block,
max_frames_per_block,
None,
)
}
pub fn new_heterogeneous(
request: CaptureRequest,
per_input: Vec<(BackendId, Arc<Format>)>,
block_frames: usize,
max_input_frames_per_call: usize,
) -> Result<Self, ManagerError> {
Self::new_with_block_frames(
request,
per_input,
block_frames,
max_input_frames_per_call,
None,
)
}
pub fn new_heterogeneous_with_budget(
request: CaptureRequest,
per_input: Vec<(BackendId, Arc<Format>)>,
block_frames: usize,
max_input_frames_per_call: usize,
existing_budget: StorageBudget,
) -> Result<Self, ManagerError> {
Self::new_with_block_frames(
request,
per_input,
block_frames,
max_input_frames_per_call,
Some(existing_budget),
)
}
fn new_with_block_frames(
request: CaptureRequest,
per_input: Vec<(BackendId, Arc<Format>)>,
block_frames: usize,
max_frames_per_block: usize,
existing_budget: Option<StorageBudget>,
) -> Result<Self, ManagerError> {
request
.budgets
.validate()
.map_err(|_| ManagerError::Capacity)?;
if request.targets.is_empty()
|| per_input.len() != request.targets.len()
|| block_frames == 0
|| max_frames_per_block == 0
|| block_frames > max_frames_per_block
{
return Err(ManagerError::InvalidConfiguration);
}
if request.targets.len() > request.budgets.max_targets
|| request.targets.len() > request.budgets.max_active_streams
{
return Err(ManagerError::Capacity);
}
let raw_formats: Vec<Format> = per_input.iter().map(|(_, f)| (**f).clone()).collect();
let all_identical_f32 = raw_formats
.iter()
.all(|f| f == &raw_formats[0] && f.sample() == SampleType::F32);
let working_format = if all_identical_f32 {
Arc::new(raw_formats[0].clone())
} else {
let (wf, _) = resolve_mixer_working_format(
&raw_formats,
request.output_converter.as_ref(),
request.input_conversion,
)
.map_err(ManagerError::from)?;
Arc::new(wf)
};
let storage_budget = match existing_budget {
Some(budget) => budget,
None => StorageBudget::new(
request.budgets.max_active_streams,
request.budgets.max_total_pcm_memory,
)
.map_err(|_| ManagerError::Capacity)?,
};
let max_subs = request
.budgets
.max_active_streams
.saturating_mul(2)
.clamp(1, MAX_SESSION_SUBSCRIPTIONS);
let notifier =
Arc::new(SessionNotifier::new(max_subs).map_err(|_| ManagerError::Capacity)?);
let topology = NativeTreeMixTopology::new(request.budgets.max_native_graph_links)
.map_err(|_| ManagerError::Capacity)?;
let mixer = CspaMixer::new_with_max_targets(
working_format.clone(),
&request.targets,
request.mixer_config,
max_frames_per_block,
request.budgets.max_targets,
)
.map_err(ManagerError::from)?;
let output_stage = OutputStage::new(
OutputStageConfig {
input_format: working_format.clone(),
output_converter: request.output_converter.clone(),
gain: 1.0,
clamp_f32: false,
silence_on_idle: request.mixer_config.silence_on_idle,
idle_grace_ns: request.mixer_config.idle_grace_ns,
output_queue_slots: request.mixer_config.output_queue_slots,
quantum_frames: block_frames,
max_frames_per_block,
},
&storage_budget,
)?;
let output_format = output_stage.output_format().clone();
let mut pipelines = Vec::with_capacity(request.budgets.max_targets);
let relaunch_deadlines_ns = vec![None; request.targets.len()];
let mut diag_snapshots = Vec::with_capacity(request.budgets.max_targets);
mixer.write_input_diagnostics(&mut diag_snapshots);
let diagnostics = Arc::new(Mutex::new(diag_snapshots));
let mut input_handles = Vec::with_capacity(request.targets.len());
for (idx, (t, (backend, in_fmt))) in request.targets.iter().zip(per_input).enumerate() {
let pipe_opt = if matches!(in_fmt.layout(), crate::schema::Layout::Known(_)) {
Some(
InputPipelineSlot::new(
(*in_fmt).clone(),
(*working_format).clone(),
block_frames,
max_frames_per_block,
)
.map_err(|_| ManagerError::Unsupported)?,
)
} else {
None
};
let is_resampled = in_fmt.rate() != working_format.rate();
let identity_bypass = pipe_opt.as_ref().map_or(in_fmt == working_format, |p| {
p.normalizer.is_identity_bypass()
});
pipelines.push(pipe_opt);
input_handles.push(InputStatusHandle {
target_index: idx,
target_id: t.id.clone(),
backend,
native_format: in_fmt,
mixer_format: working_format.clone(),
is_resampled,
identity_bypass,
shared: diagnostics.clone(),
});
}
let ch = usize::from(working_format.channels());
Ok(Self {
request,
working_format,
output_format,
block_frames,
max_frames_per_block,
storage_budget,
pending_opens: Arc::new(AtomicUsize::new(0)),
notifier,
clock: MonotonicReadClock::new(),
topology,
pipelines,
relaunch_deadlines_ns,
mixer,
output_stage,
diagnostics,
input_handles,
mix_scratch: vec![0.0_f32; max_frames_per_block * ch],
last_metadata: None,
})
}
#[inline]
pub fn working_format(&self) -> &Arc<Format> {
&self.working_format
}
#[inline]
pub fn output_format(&self) -> &Arc<Format> {
&self.output_format
}
#[inline]
pub fn block_frames(&self) -> usize {
self.block_frames
}
#[inline]
pub fn storage_budget(&self) -> &StorageBudget {
&self.storage_budget
}
#[inline]
pub fn budgets(&self) -> &AggregateManagerBudgets {
&self.request.budgets
}
#[inline]
pub fn targets(&self) -> &[CaptureTarget] {
&self.request.targets
}
#[inline]
pub fn session_notifier(&self) -> &Arc<SessionNotifier> {
&self.notifier
}
#[inline]
pub fn now_ns(&mut self) -> u64 {
self.clock.now_ns()
}
#[inline]
pub fn last_block_metadata(&self) -> Option<MixedBlockMetadata> {
self.last_metadata
}
#[inline]
pub fn clear_pending_output(&mut self) {
self.output_stage.clear_pending_output();
}
#[inline]
pub fn has_pending_output(&self) -> bool {
self.output_stage.has_pending_output()
}
#[inline]
pub fn relaunch_deadline_ns(&self, input_index: usize) -> Option<u64> {
self.relaunch_deadlines_ns
.get(input_index)
.copied()
.flatten()
}
pub fn set_relaunch_deadline_ns(
&mut self,
input_index: usize,
deadline_ns: Option<u64>,
) -> Result<(), Reason> {
let slot = self
.relaunch_deadlines_ns
.get_mut(input_index)
.ok_or(Reason::InvalidFormat)?;
*slot = deadline_ns;
let _ = self.notifier.notify();
Ok(())
}
#[inline]
pub fn earliest_relaunch_deadline_ns(&self) -> Option<u64> {
self.relaunch_deadlines_ns.iter().copied().flatten().min()
}
pub fn reconfigure_targets(
&mut self,
new_targets: Vec<CaptureTarget>,
) -> Result<Vec<Option<usize>>, ManagerError> {
let default_backend = self.request.backends.primary_for_os(PlatformOs::current());
let per_input: Vec<(BackendId, Arc<Format>)> = new_targets
.iter()
.map(|t| {
(
t.backend.unwrap_or(default_backend),
self.working_format.clone(),
)
})
.collect();
self.reconfigure_targets_with_formats(new_targets, per_input)
}
pub fn reconfigure_targets_with_formats(
&mut self,
new_targets: Vec<CaptureTarget>,
per_input: Vec<(BackendId, Arc<Format>)>,
) -> Result<Vec<Option<usize>>, ManagerError> {
if new_targets.is_empty() || per_input.len() != new_targets.len() {
return Err(ManagerError::InvalidConfiguration);
}
if new_targets.len() > self.request.budgets.max_targets
|| new_targets.len() > self.request.budgets.max_active_streams
{
return Err(ManagerError::Capacity);
}
if self.request.input_conversion == InputConversionPolicy::StrictNoResample
&& per_input
.iter()
.any(|(_, fmt)| fmt.rate() != self.working_format.rate())
{
return Err(ManagerError::Unsupported);
}
let raw_formats: Vec<Format> = per_input.iter().map(|(_, f)| (**f).clone()).collect();
let all_identical_f32 = raw_formats
.iter()
.all(|f| f == &raw_formats[0] && f.sample() == SampleType::F32);
let desired_working = if all_identical_f32 {
raw_formats[0].clone()
} else {
let (wf, _) = resolve_mixer_working_format(
&raw_formats,
self.request.output_converter.as_ref(),
self.request.input_conversion,
)
.map_err(ManagerError::from)?;
wf
};
if desired_working.rate() > self.working_format.rate()
|| desired_working.channels() > self.working_format.channels()
{
return Err(ManagerError::WorkingFormatChanged);
}
for (_, fmt) in &per_input {
if matches!(fmt.layout(), crate::schema::Layout::Known(_)) {
validate_channel_mapping(fmt, &self.working_format)
.map_err(|_| ManagerError::WorkingFormatChanged)?;
} else if fmt.channels() != self.working_format.channels()
|| fmt.rate() != self.working_format.rate()
{
return Err(ManagerError::Unsupported);
}
}
let mapping = self
.mixer
.reconfigure_targets(&new_targets)
.map_err(ManagerError::from)?
.to_vec();
self.sync_diagnostics();
let mut next_pipes = Vec::with_capacity(self.request.budgets.max_targets);
let mut next_relaunch = Vec::with_capacity(new_targets.len());
for (idx, &mapped_old) in mapping.iter().enumerate() {
let (_, ref fmt) = per_input[idx];
let retained_relaunch = mapped_old
.and_then(|old_idx| self.relaunch_deadlines_ns.get(old_idx).copied().flatten());
next_relaunch.push(retained_relaunch);
if let Some(old_idx) = mapped_old
&& let Some(existing_pipe) = self.pipelines.get_mut(old_idx).and_then(Option::take)
&& existing_pipe.normalizer.input_format() == fmt.as_ref()
{
next_pipes.push(Some(existing_pipe));
} else if matches!(fmt.layout(), crate::schema::Layout::Known(_)) {
next_pipes.push(Some(
InputPipelineSlot::new(
(**fmt).clone(),
(*self.working_format).clone(),
self.block_frames,
self.max_frames_per_block,
)
.map_err(|_| ManagerError::Unsupported)?,
));
} else {
next_pipes.push(None);
}
}
self.pipelines = next_pipes;
self.relaunch_deadlines_ns = next_relaunch;
for (idx, pipe_opt) in self.pipelines.iter().enumerate() {
let reb = pipe_opt
.as_ref()
.map_or(0, |p| p.reblocker.buffered_frames());
self.mixer.set_subblock_buffered_frames(idx, reb);
}
self.input_handles = new_targets
.iter()
.zip(per_input)
.enumerate()
.map(|(idx, (t, (backend, in_fmt)))| {
let is_resampled = in_fmt.rate() != self.working_format.rate();
let identity_bypass = self
.pipelines
.get(idx)
.and_then(Option::as_ref)
.map_or(in_fmt == self.working_format, |p| {
p.normalizer.is_identity_bypass()
});
InputStatusHandle {
target_index: idx,
target_id: t.id.clone(),
backend,
native_format: in_fmt,
mixer_format: self.working_format.clone(),
is_resampled,
identity_bypass,
shared: self.diagnostics.clone(),
}
})
.collect();
self.request.targets = new_targets;
let _ = self.notifier.notify();
Ok(mapping)
}
#[allow(deprecated, reason = "fetch_update supports the minimum Rust version")]
pub fn acquire_pending_open(&self) -> Result<PendingOpenTicket, ManagerError> {
let max_pending = self.request.budgets.max_pending_opens;
self.pending_opens
.fetch_update(SeqCst, SeqCst, |used| {
used.checked_add(1).filter(|next| *next <= max_pending)
})
.map_err(|_| ManagerError::Capacity)?;
Ok(PendingOpenTicket {
_guard: PendingOpenGuard {
pending: self.pending_opens.clone(),
},
})
}
pub fn input_handles(&self) -> &[InputStatusHandle] {
&self.input_handles
}
pub fn membership_descriptor(&self) -> MembershipDescriptor {
self.mixer.membership_descriptor()
}
pub fn attach_topology_source(
&mut self,
target_index: usize,
source_id: impl Into<Arc<str>>,
) -> Result<bool, ManagerError> {
self.topology.attach_source(target_index, source_id)
}
pub fn retire_topology_target(&mut self, target_index: usize) -> Vec<Arc<str>> {
self.topology.retire_target(target_index)
}
#[inline]
fn sync_diagnostics(&self) {
self.mixer.write_input_diagnostics(
&mut self.diagnostics.lock().unwrap_or_else(|e| e.into_inner()),
);
}
#[inline]
pub fn record_input_activity(&mut self, now_ns: u64, frames: usize, rate_hz: u32) {
if frames > 0 {
self.output_stage.evict_pending_silence();
self.output_stage
.idle_clock_mut()
.note_input_activity(now_ns, frames, rate_hz);
}
}
pub fn push_raw_input_bytes(
&mut self,
input_index: usize,
raw_bytes: &[u8],
timestamp: Option<Stamp>,
now_ns: u64,
) -> Result<usize, Reason> {
let block_frames = self.block_frames;
let (in_frames, in_rate_hz, pushed_blocks) = {
let pipe = self
.pipelines
.get_mut(input_index)
.and_then(Option::as_mut)
.ok_or(Reason::InvalidFormat)?;
let in_frames = pipe.normalizer.input_format().frames_in(raw_bytes.len())?;
let in_rate_hz = pipe.normalizer.input_format().rate();
pipe.normalizer
.normalize_into(raw_bytes, &mut pipe.norm_scratch)?;
pipe.reblocker.push_samples(&pipe.norm_scratch)?;
let mut pushed = 0usize;
while pipe.reblocker.pop_block_into(&mut pipe.out_block_scratch)? {
pipe.last_block.copy_from_slice(&pipe.out_block_scratch);
pipe.has_last_block = true;
self.mixer.push_input_samples(
input_index,
&pipe.out_block_scratch,
block_frames,
timestamp,
now_ns,
)?;
pushed += 1;
}
self.mixer
.set_subblock_buffered_frames(input_index, pipe.reblocker.buffered_frames());
(in_frames, in_rate_hz, pushed)
};
if pushed_blocks > 0 {
self.output_stage.evict_pending_silence();
if let Some(slot_dl) = self.relaunch_deadlines_ns.get_mut(input_index) {
*slot_dl = None;
}
} else if in_frames > 0 {
self.output_stage.evict_pending_silence();
self.output_stage
.idle_clock_mut()
.note_input_activity(now_ns, in_frames, in_rate_hz);
if let Some(slot_dl) = self.relaunch_deadlines_ns.get_mut(input_index) {
*slot_dl = None;
}
}
self.sync_diagnostics();
Ok(pushed_blocks)
}
fn flush_pipeline_slot(&mut self, input_index: usize, now_ns: u64) -> Result<usize, Reason> {
if matches!(
self.mixer.slot_state(input_index),
None | Some(ParticipationState::Exited) | Some(ParticipationState::Failed(_))
) {
return Ok(0);
}
let Some(pipe) = self.pipelines.get_mut(input_index).and_then(Option::as_mut) else {
return Ok(0);
};
let block_frames = self.block_frames;
let mut pushed = 0usize;
if pipe.normalizer.has_unflushed_tail() {
let flushed = pipe.normalizer.flush_tail_into(&mut pipe.norm_scratch)?;
if flushed > 0 {
pipe.reblocker.push_samples(&pipe.norm_scratch)?;
}
}
while pipe.reblocker.pop_block_into(&mut pipe.out_block_scratch)? {
pipe.last_block.copy_from_slice(&pipe.out_block_scratch);
pipe.has_last_block = true;
self.mixer.push_input_samples(
input_index,
&pipe.out_block_scratch,
block_frames,
None,
now_ns,
)?;
pushed += 1;
}
let partial = pipe
.reblocker
.flush_partial_into(&mut pipe.out_block_scratch)?;
if partial > 0 {
pipe.has_last_block = false;
self.mixer.push_input_samples(
input_index,
&pipe.out_block_scratch,
block_frames,
None,
now_ns,
)?;
pushed += 1;
}
pipe.sustained_deficit_since_ns = None;
self.mixer
.set_subblock_buffered_frames(input_index, pipe.reblocker.buffered_frames());
Ok(pushed)
}
fn flush_all_active_pipelines(&mut self, now_ns: u64) -> usize {
let mut total = 0usize;
for idx in 0..self.pipelines.len() {
if let Ok(n) = self.flush_pipeline_slot(idx, now_ns) {
total += n;
}
}
if total > 0 {
self.sync_diagnostics();
}
total
}
fn reconcile_cross_clock_deficit(&mut self, now_ns: u64) -> Result<(), Reason> {
if !self.mixer.is_cross_clock_drift_enabled() {
for pipe in self.pipelines.iter_mut().flatten() {
pipe.sustained_deficit_since_ns = None;
}
return Ok(());
}
let block_frames = self.block_frames;
let rate_hz = u64::from(self.working_format.rate().max(1));
let ch = usize::from(self.working_format.channels());
let threshold_ns = self.request.mixer_config.drift_threshold_ns;
let clear_ns = threshold_ns.saturating_sub(self.request.mixer_config.drift_hysteresis_ns);
let hold_ns = self.request.mixer_config.drift_hold_ns;
let threshold_frames =
((u128::from(threshold_ns) * u128::from(rate_hz)) / 1_000_000_000).max(1) as usize;
let threshold_frames = threshold_frames.min(block_frames.saturating_sub(1).max(1));
let mut max_avail = 0usize;
let count = self.mixer.input_count().min(self.pipelines.len());
for idx in 0..count {
if matches!(
self.mixer.slot_state(idx),
Some(ParticipationState::Active | ParticipationState::Late)
) {
let reb = self
.pipelines
.get(idx)
.and_then(Option::as_ref)
.map_or(0, |p| p.reblocker.buffered_frames());
let avail = self.mixer.queued_packets(idx) * block_frames + reb;
max_avail = max_avail.max(avail);
}
}
for idx in 0..count {
if !matches!(
self.mixer.slot_state(idx),
Some(ParticipationState::Active | ParticipationState::Late)
) {
if let Some(Some(pipe)) = self.pipelines.get_mut(idx) {
pipe.sustained_deficit_since_ns = None;
}
continue;
}
let queued_pkts = self.mixer.queued_packets(idx);
let Some(Some(pipe)) = self.pipelines.get_mut(idx) else {
continue;
};
let buffered = pipe.reblocker.buffered_frames();
let avail = queued_pkts * block_frames + buffered;
let deficit_frames = max_avail.saturating_sub(avail);
let deficit_ns = ((deficit_frames as u64).saturating_mul(1_000_000_000)) / rate_hz;
if deficit_ns >= threshold_ns {
let since = *pipe.sustained_deficit_since_ns.get_or_insert(now_ns);
if now_ns.saturating_sub(since) >= hold_ns
&& queued_pkts == 0
&& pipe.has_last_block
&& buffered > 0
&& buffered < block_frames
{
let consume_new = buffered.min(block_frames - threshold_frames);
let repeat_frames = block_frames - consume_new;
pipe.primary_scratch.copy_from_slice(&pipe.last_block);
pipe.shifted_scratch[..repeat_frames * ch]
.copy_from_slice(&pipe.last_block[consume_new * ch..]);
pipe.reblocker
.peek_into(0, &mut pipe.shifted_scratch[repeat_frames * ch..])?;
self.mixer.crossfade_and_record_drift_slip(
idx,
&pipe.primary_scratch,
&pipe.shifted_scratch,
&mut pipe.out_block_scratch,
)?;
pipe.reblocker.discard_frames(consume_new);
pipe.last_block.copy_from_slice(&pipe.out_block_scratch);
pipe.sustained_deficit_since_ns = Some(now_ns);
let new_buffered = pipe.reblocker.buffered_frames();
self.mixer.set_subblock_buffered_frames(idx, new_buffered);
self.mixer.push_input_samples(
idx,
&pipe.out_block_scratch,
block_frames,
None,
now_ns,
)?;
}
} else if deficit_ns <= clear_ns {
pipe.sustained_deficit_since_ns = None;
}
}
Ok(())
}
pub fn push_input_packet(
&mut self,
input_index: usize,
packet: MixerInputPacket,
) -> Result<(), Reason> {
self.output_stage.evict_pending_silence();
self.mixer.push_input_packet(input_index, packet)?;
if let Some(slot_dl) = self.relaunch_deadlines_ns.get_mut(input_index) {
*slot_dl = None;
}
self.sync_diagnostics();
Ok(())
}
pub fn set_input_state(
&mut self,
input_index: usize,
state: ParticipationState,
) -> Result<(), Reason> {
if matches!(
state,
ParticipationState::Idle
| ParticipationState::Exited
| ParticipationState::WaitingRelaunch
) {
let now_ns = self.clock.now_ns();
let _ = self.flush_pipeline_slot(input_index, now_ns);
}
self.mixer.set_input_state(input_index, state)?;
if state != ParticipationState::WaitingRelaunch
&& let Some(slot_dl) = self.relaunch_deadlines_ns.get_mut(input_index)
{
*slot_dl = None;
}
self.sync_diagnostics();
let _ = self.notifier.notify();
Ok(())
}
fn step_mix_into_stage(
&mut self,
frames: usize,
now_ns: u64,
oldest_wait_ns: u64,
) -> Result<(MixStepOutcome, MixedBlockMetadata), ReadError> {
self.step_mix_into_stage_ext(frames, now_ns, oldest_wait_ns, false)
}
fn step_mix_into_stage_ext(
&mut self,
frames: usize,
now_ns: u64,
oldest_wait_ns: u64,
is_flushed_tail: bool,
) -> Result<(MixStepOutcome, MixedBlockMetadata), ReadError> {
if !is_flushed_tail {
let _ = self.reconcile_cross_clock_deficit(now_ns);
}
let ch = usize::from(self.mixer.format().channels());
let total_samples = frames * ch;
if self.mix_scratch.len() < total_samples {
self.mix_scratch.resize(total_samples, 0.0);
}
let (outcome, mut meta) = self
.mixer
.mix_block_into(
frames,
now_ns,
oldest_wait_ns,
&mut self.mix_scratch[..total_samples],
)
.map_err(|_| ReadError::InvalidDestination)?;
self.sync_diagnostics();
let final_outcome = match outcome {
MixStepOutcome::Produced(_) => {
let out_frames = if is_flushed_tail {
self.output_stage
.process_f32_flushed_tail(&self.mix_scratch[..total_samples], &mut meta)?
} else {
self.output_stage.process_f32_samples(
&self.mix_scratch[..total_samples],
&mut meta,
now_ns,
)?
};
MixStepOutcome::Produced(out_frames)
}
MixStepOutcome::Eof => {
self.output_stage.evict_pending_silence();
if let Some((tail_frames, tail_meta)) = self.output_stage.flush_converter_tail(
self.mixer.membership_version(),
self.mixer.failed_inputs_mask(),
)? {
meta = tail_meta;
MixStepOutcome::Produced(tail_frames)
} else {
MixStepOutcome::Eof
}
}
other => other,
};
self.last_metadata = Some(meta);
Ok((final_outcome, meta))
}
fn poll_idle_or_tail_step(
&mut self,
now_ns: u64,
blocking: bool,
) -> Result<Result<(usize, MixedBlockMetadata), PartialReason>, ReadError> {
if !self.output_stage.silence_on_idle() {
return Ok(Err(if blocking {
PartialReason::Timeout
} else {
PartialReason::WouldBlock
}));
}
if self.output_stage.idle_clock_mut().is_due(now_ns) {
let flushed_blocks = self.flush_all_active_pipelines(now_ns);
if flushed_blocks > 0 {
while self.mixer.has_any_queued_input() {
let (outcome, meta) = self.step_mix_into_stage_ext(
self.block_frames,
now_ns,
self.request.mixer_config.alignment_window_ns,
true,
)?;
if let MixStepOutcome::Produced(out_frames) = outcome
&& out_frames > 0
{
let _ = self
.output_stage
.idle_clock_mut()
.poll_silence_quantum(now_ns, blocking);
return Ok(Ok((out_frames, meta)));
}
}
}
}
let res = self.output_stage.poll_idle_silence(
now_ns,
blocking,
self.mixer.membership_version(),
self.mixer.failed_inputs_mask(),
)?;
if let Ok((_, meta)) = res {
self.last_metadata = Some(meta);
}
Ok(res)
}
pub fn poll_mix_bytes(
&mut self,
frames: usize,
now_ns: u64,
oldest_wait_ns: u64,
out_bytes: &mut Vec<u8>,
) -> Result<(MixStepOutcome, MixedBlockMetadata), ReadError> {
let (mut outcome, mut meta) = self.step_mix_into_stage(frames, now_ns, oldest_wait_ns)?;
if outcome == MixStepOutcome::ParkedIdle
&& let Ok((idle_frames, idle_meta)) = self.poll_idle_or_tail_step(now_ns, false)?
{
outcome = MixStepOutcome::Produced(idle_frames);
meta = idle_meta;
}
out_bytes.clear();
if matches!(outcome, MixStepOutcome::Produced(f) if f > 0) {
out_bytes.extend_from_slice(self.output_stage.out_bytes());
}
Ok((outcome, meta))
}
pub fn try_pop_pending_owned(
&mut self,
requested_frames: usize,
) -> Result<Option<(ReadResult, MixedBlockMetadata)>, ReadError> {
let popped = self.output_stage.try_pop_pending_owned(requested_frames)?;
if let Some((_, meta)) = popped {
self.last_metadata = Some(meta);
}
Ok(popped)
}
pub fn try_pop_pending_into(
&mut self,
dst: &mut [u8],
requested_frames: usize,
) -> Result<Option<(ReadResult, MixedBlockMetadata)>, ReadError> {
let popped = self
.output_stage
.try_pop_pending_into(dst, requested_frames)?;
if let Some((_, meta)) = popped {
self.last_metadata = Some(meta);
}
Ok(popped)
}
pub fn read_mixed_owned(
&mut self,
requested_frames: usize,
now_ns: u64,
oldest_wait_ns: u64,
) -> Result<(ReadResult, MixedBlockMetadata), ReadError> {
let req_frames = requested_frames.max(1);
if self.mixer.has_any_queued_input() || self.mixer.is_terminal_or_fatal() {
self.output_stage.evict_pending_silence();
}
if let Some(res) = self.try_pop_pending_owned(req_frames)? {
return Ok(res);
}
let (outcome, meta) =
self.step_mix_into_stage(self.block_frames, now_ns, oldest_wait_ns)?;
match outcome {
MixStepOutcome::Produced(out_frames) if out_frames > 0 => {
self.output_stage.finish_owned(out_frames, req_frames, meta)
}
MixStepOutcome::Produced(_) | MixStepOutcome::ParkedIdle => {
if let Ok((idle_frames, idle_meta)) = self.poll_idle_or_tail_step(now_ns, false)? {
return self
.output_stage
.finish_owned(idle_frames, req_frames, idle_meta);
}
Ok((empty_read_result(PartialReason::Timeout), meta))
}
MixStepOutcome::Eof => Ok((empty_read_result(PartialReason::Eof), meta)),
MixStepOutcome::Failed(_) => Ok((
empty_read_result(PartialReason::Failure(Failure::Backend)),
meta,
)),
}
}
pub fn read_mixed_into(
&mut self,
dst: &mut [u8],
requested_frames: usize,
now_ns: u64,
oldest_wait_ns: u64,
) -> Result<(ReadResult, MixedBlockMetadata), ReadError> {
let req_frames = requested_frames.max(1);
let out_stride = self.output_format.bytes_per_frame();
if dst.len() < req_frames.saturating_mul(out_stride) {
return Err(ReadError::InvalidDestination);
}
if self.mixer.has_any_queued_input() || self.mixer.is_terminal_or_fatal() {
self.output_stage.evict_pending_silence();
}
if let Some(res) = self.try_pop_pending_into(dst, req_frames)? {
return Ok(res);
}
let (outcome, meta) =
self.step_mix_into_stage(self.block_frames, now_ns, oldest_wait_ns)?;
match outcome {
MixStepOutcome::Produced(out_frames) if out_frames > 0 => self
.output_stage
.finish_into(dst, out_frames, req_frames, meta),
MixStepOutcome::Produced(_) | MixStepOutcome::ParkedIdle => {
if let Ok((idle_frames, idle_meta)) = self.poll_idle_or_tail_step(now_ns, false)? {
return self
.output_stage
.finish_into(dst, idle_frames, req_frames, idle_meta);
}
Ok((empty_read_result(PartialReason::Timeout), meta))
}
MixStepOutcome::Eof => Ok((empty_read_result(PartialReason::Eof), meta)),
MixStepOutcome::Failed(_) => Ok((
empty_read_result(PartialReason::Failure(Failure::Backend)),
meta,
)),
}
}
pub fn schedule_mixed_owned(
&mut self,
requested_frames: usize,
wait: CallerWait,
cancel: &Cancellation,
drain_inputs: impl FnMut(&mut Self, u64),
) -> Result<(ReadResult, MixedBlockMetadata), ReadError> {
let mut clock = self.clock;
let result = self.schedule_mixed_owned_with_clock(
requested_frames,
wait,
cancel,
&mut clock,
drain_inputs,
);
self.clock = clock;
result
}
pub fn schedule_mixed_into(
&mut self,
dst: &mut [u8],
requested_frames: usize,
wait: CallerWait,
cancel: &Cancellation,
drain_inputs: impl FnMut(&mut Self, u64),
) -> Result<(ReadResult, MixedBlockMetadata), ReadError> {
let mut clock = self.clock;
let result = self.schedule_mixed_into_with_clock(
dst,
requested_frames,
wait,
cancel,
&mut clock,
drain_inputs,
);
self.clock = clock;
result
}
pub fn schedule_mixed_owned_with_clock<C: ReadClock>(
&mut self,
requested_frames: usize,
wait: CallerWait,
cancel: &Cancellation,
clock: &mut C,
drain_inputs: impl FnMut(&mut Self, u64),
) -> Result<(ReadResult, MixedBlockMetadata), ReadError> {
let req_frames = requested_frames.max(1);
if self.output_stage.has_pending_real_output()
&& let Some(res) = self.try_pop_pending_owned(req_frames)?
{
return Ok(res);
}
self.schedule_mixed_core(
req_frames,
wait,
cancel,
clock,
drain_inputs,
|stage, op| match op {
StageEmitOp::Deliver(out_frames, meta) => {
stage.finish_owned(out_frames, req_frames, meta).map(Some)
}
StageEmitOp::PopPending => stage.try_pop_pending_owned(req_frames),
},
)
}
pub fn schedule_mixed_into_with_clock<C: ReadClock>(
&mut self,
dst: &mut [u8],
requested_frames: usize,
wait: CallerWait,
cancel: &Cancellation,
clock: &mut C,
drain_inputs: impl FnMut(&mut Self, u64),
) -> Result<(ReadResult, MixedBlockMetadata), ReadError> {
let req_frames = requested_frames.max(1);
let out_stride = self.output_format.bytes_per_frame();
if dst.len() < req_frames.saturating_mul(out_stride) {
return Err(ReadError::InvalidDestination);
}
if self.output_stage.has_pending_real_output()
&& let Some(res) = self.try_pop_pending_into(dst, req_frames)?
{
return Ok(res);
}
self.schedule_mixed_core(
req_frames,
wait,
cancel,
clock,
drain_inputs,
|stage, op| match op {
StageEmitOp::Deliver(out_frames, meta) => stage
.finish_into(dst, out_frames, req_frames, meta)
.map(Some),
StageEmitOp::PopPending => stage.try_pop_pending_into(dst, req_frames),
},
)
}
fn expire_due_relaunches(&mut self, now_ns: u64) {
for idx in 0..self.relaunch_deadlines_ns.len() {
if let Some(due_ns) = self.relaunch_deadlines_ns[idx]
&& now_ns >= due_ns
{
self.relaunch_deadlines_ns[idx] = None;
let _ = self.flush_pipeline_slot(idx, now_ns);
let _ = self.mixer.set_input_state(idx, ParticipationState::Exited);
self.sync_diagnostics();
}
}
}
#[inline]
fn idle_metadata(&self) -> MixedBlockMetadata {
MixedBlockMetadata {
membership_version: self.mixer.membership_version(),
failed_inputs: self.mixer.failed_inputs_mask(),
..Default::default()
}
}
fn schedule_mixed_core<C: ReadClock>(
&mut self,
_req_frames: usize,
wait: CallerWait,
cancel: &Cancellation,
clock: &mut C,
mut drain_inputs: impl FnMut(&mut Self, u64),
mut finish_op: impl FnMut(
&mut OutputStage,
StageEmitOp,
)
-> Result<Option<(ReadResult, MixedBlockMetadata)>, ReadError>,
) -> Result<(ReadResult, MixedBlockMetadata), ReadError> {
let blocking = wait.is_blocking();
let start_ns = clock.now_ns();
let caller_ns = match wait {
CallerWait::Zero => Some(start_ns),
CallerWait::Bounded(dur) => {
let dur_ns = dur.as_nanos().min(u128::from(u64::MAX)) as u64;
Some(start_ns.saturating_add(dur_ns))
}
CallerWait::Unbounded => None,
};
let notifier = Arc::clone(&self.notifier);
let deadlines_cell = Cell::new(DeadlineSet {
caller_ns,
..DeadlineSet::default()
});
let mut first_poll_ns = Some(start_ns);
notifier.poll_until(
cancel,
|| first_poll_ns.take().unwrap_or_else(|| clock.now_ns()),
|now_ns| deadlines_cell.get().wait_from(now_ns, blocking),
|now_ns| {
if cancel.is_cancelled() {
let meta = self.idle_metadata();
self.last_metadata = Some(meta);
return Some(Ok((empty_read_result(PartialReason::Cancelled), meta)));
}
drain_inputs(self, now_ns);
self.expire_due_relaunches(now_ns);
if self.mixer.has_any_queued_input() {
let _ = self.reconcile_cross_clock_deficit(now_ns);
}
if cancel.is_cancelled() {
let meta = self.idle_metadata();
self.last_metadata = Some(meta);
return Some(Ok((empty_read_result(PartialReason::Cancelled), meta)));
}
if self.mixer.is_terminal_or_fatal() {
let res = self.step_mix_into_stage(self.block_frames, now_ns, 0);
return Some(match res {
Ok((MixStepOutcome::Eof, meta)) => {
Ok((empty_read_result(PartialReason::Eof), meta))
}
Ok((MixStepOutcome::Failed(_), meta)) => Ok((
empty_read_result(PartialReason::Failure(Failure::Backend)),
meta,
)),
Ok((MixStepOutcome::Produced(out_frames), meta)) if out_frames > 0 => {
match finish_op(
&mut self.output_stage,
StageEmitOp::Deliver(out_frames, meta),
) {
Ok(Some(r)) => Ok(r),
Ok(None) => Err(ReadError::InvalidDestination),
Err(err) => Err(err),
}
}
Ok((_, meta)) => Ok((empty_read_result(PartialReason::Eof), meta)),
Err(err) => Err(err),
});
}
while self.mixer.has_any_queued_input() {
let align = self.mixer.alignment_deadline_ns();
let align_ready = match align {
None => true,
Some((_, dl)) => now_ns >= dl,
};
if !align_ready {
break;
}
let oldest_wait_ns = align.map_or(
self.request.mixer_config.alignment_window_ns,
|(oldest, _)| now_ns.saturating_sub(oldest),
);
match self.step_mix_into_stage(self.block_frames, now_ns, oldest_wait_ns) {
Ok((MixStepOutcome::Produced(out_frames), meta)) if out_frames > 0 => {
return Some(
match finish_op(
&mut self.output_stage,
StageEmitOp::Deliver(out_frames, meta),
) {
Ok(Some(r)) => Ok(r),
Ok(None) => Err(ReadError::InvalidDestination),
Err(err) => Err(err),
},
);
}
Ok((MixStepOutcome::Produced(_), _)) => {
continue;
}
Ok((MixStepOutcome::Eof, meta)) => {
return Some(Ok((empty_read_result(PartialReason::Eof), meta)));
}
Ok((MixStepOutcome::Failed(_), meta)) => {
return Some(Ok((
empty_read_result(PartialReason::Failure(Failure::Backend)),
meta,
)));
}
Ok((MixStepOutcome::ParkedIdle, _)) => break,
Err(err) => return Some(Err(err)),
}
}
if !self.mixer.has_any_queued_input()
&& self.output_stage.has_pending_silence_output()
{
match finish_op(&mut self.output_stage, StageEmitOp::PopPending) {
Ok(Some((res, meta))) => {
self.last_metadata = Some(meta);
return Some(Ok((res, meta)));
}
Ok(None) => {}
Err(err) => return Some(Err(err)),
}
}
if !self.mixer.has_any_queued_input() && self.output_stage.silence_on_idle() {
match self.poll_idle_or_tail_step(now_ns, blocking) {
Ok(Ok((out_frames, meta))) => {
return Some(
match finish_op(
&mut self.output_stage,
StageEmitOp::Deliver(out_frames, meta),
) {
Ok(Some(r)) => Ok(r),
Ok(None) => Err(ReadError::InvalidDestination),
Err(err) => Err(err),
},
);
}
Ok(Err(reason)) => {
if !blocking {
let meta = self.idle_metadata();
self.last_metadata = Some(meta);
return Some(Ok((empty_read_result(reason), meta)));
}
}
Err(err) => return Some(Err(err)),
}
}
if !blocking {
let meta = self.idle_metadata();
self.last_metadata = Some(meta);
return Some(Ok((empty_read_result(PartialReason::WouldBlock), meta)));
}
if caller_ns.is_some_and(|dl| now_ns >= dl) {
let meta = self.idle_metadata();
self.last_metadata = Some(meta);
return Some(Ok((empty_read_result(PartialReason::Timeout), meta)));
}
let alignment_ns = self.mixer.alignment_deadline_ns().map(|(_, dl)| dl);
let relaunch_ns = self.earliest_relaunch_deadline_ns();
let silence_ns = if !self.mixer.has_any_queued_input() {
self.output_stage.next_silence_deadline_ns(now_ns)
} else {
None
};
deadlines_cell.set(DeadlineSet {
caller_ns,
alignment_ns,
relaunch_ns,
silence_ns,
});
None
},
)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{
schema::{
BackendId, Backends, ByteOrder, Channel, DefaultDeviceMode, Format, Header, Layout,
OnRootExit, ProcessScope, SampleType, TargetKind,
},
storage::Pool,
};
const ROOT: ProcessIdentity = ProcessIdentity {
pid: 10,
generation: 100,
};
const CHILD: ProcessIdentity = ProcessIdentity {
pid: 11,
generation: 200,
};
const GRANDCHILD: ProcessIdentity = ProcessIdentity {
pid: 12,
generation: 300,
};
#[test]
fn multi_input_manager_overlap_topology_and_remainder_slicing() {
let target = CaptureTarget::application(
ROOT,
Some("com.example.app".into()),
Some("Example".into()),
Some("/bin/example".into()),
ProcessScope::Tree,
OnRootExit::Wait {
wait_timeout_ns: 5_000_000_000,
},
)
.unwrap();
assert_eq!(
target.lower_to_process().unwrap().kind(),
TargetKind::Process
);
assert!(Backends::new(Some(vec![BackendId::PipeWire]), None, None).is_err());
let fmt_m3 = Arc::new(
Format::new(
SampleType::F32,
ByteOrder::Little,
48000,
2,
Layout::Known(Arc::from([Channel::FrontLeft, Channel::FrontRight])),
)
.unwrap(),
);
let t_dup = CaptureTarget::process(ROOT, ProcessScope::Tree, OnRootExit::Stop).unwrap();
let t_child = CaptureTarget::process(CHILD, ProcessScope::Tree, OnRootExit::Stop).unwrap();
let req_m3 = CaptureRequest::new(vec![t_dup.clone(), t_dup.clone(), t_child.clone()]);
let mut multi = MultiInputManager::new(req_m3, fmt_m3, 64).unwrap();
assert_eq!(multi.input_handles().len(), 3);
assert_eq!(
multi.input_handles()[0]
.snapshot()
.unwrap()
.participation_state,
ParticipationState::Starting
);
let p_tickets: Vec<_> = (0..4)
.map(|_| multi.acquire_pending_open().unwrap())
.collect();
assert!(matches!(
multi.acquire_pending_open(),
Err(ManagerError::Capacity)
));
drop(p_tickets);
assert!(multi.acquire_pending_open().is_ok());
assert!(multi.attach_topology_source(0, "pw-node-77").unwrap());
assert!(!multi.attach_topology_source(2, "pw-node-77").unwrap());
assert!(multi.retire_topology_target(0).is_empty());
assert_eq!(
multi.retire_topology_target(2),
vec![Arc::<str>::from("pw-node-77")]
);
for idx in 0..3 {
multi
.push_input_packet(
idx,
MixerInputPacket {
samples: vec![0.25_f32; 128],
frames: 64,
timestamp: None,
arrival_ns: 0,
},
)
.unwrap();
}
let (owned_r1, out_meta) = multi.read_mixed_owned(32, 1000, 0).unwrap();
assert_eq!(owned_r1.frames, 32);
assert!(multi.has_pending_output());
assert_eq!(out_meta.contributing_mask, 0b111);
let first_f32 = f32::from_le_bytes(owned_r1.chunks[0].bytes()[0..4].try_into().unwrap());
assert!((first_f32 - 0.75).abs() <= 1e-6);
let (owned_r2, _) = multi.read_mixed_owned(32, 1000, 0).unwrap();
assert_eq!(owned_r2.frames, 32);
assert!(!multi.has_pending_output());
assert_eq!(
multi.input_handles()[0]
.snapshot()
.unwrap()
.participation_state,
ParticipationState::Active
);
let t_grand =
CaptureTarget::process(GRANDCHILD, ProcessScope::Tree, OnRootExit::Stop).unwrap();
let mapping = multi
.reconfigure_targets(vec![t_child.clone(), t_grand.clone()])
.unwrap();
assert_eq!(mapping, vec![Some(2), None]);
assert_eq!(multi.targets(), &[t_child, t_grand]);
assert_eq!(multi.input_handles().len(), 2);
assert_eq!(
multi.input_handles()[0]
.snapshot()
.unwrap()
.participation_state,
ParticipationState::Active
);
assert_eq!(
multi.input_handles()[1]
.snapshot()
.unwrap()
.participation_state,
ParticipationState::Starting
);
}
#[test]
fn retained_block_keeps_session_charged() {
let limits = StorageLimits::new(8, 4096, 8, 262144).unwrap();
let budget = StorageBudget::new(2, 557056).unwrap();
let format = Arc::new(
Format::new(
SampleType::F32,
ByteOrder::Little,
48000,
2,
Layout::Unknown,
)
.unwrap(),
);
let mut pool =
Pool::new_reserved(limits, 4096, format, budget.reserve(limits, 16384).unwrap())
.unwrap();
let held = pool
.offer(
&[7; 8],
Header {
sequence: 1,
segment: 1,
generation: 1,
frames: 1,
sample_position: None,
timestamp: None,
},
)
.unwrap();
drop(pool);
let second = budget.reserve(limits, 16384).unwrap();
assert_eq!(budget.resident_sessions(), 2);
assert_eq!(budget.reserved_bytes(), 557056);
assert!(matches!(
budget.reserve(limits, 16384),
Err(AdmissionError::Full)
));
assert_eq!(held.bytes(), &[7; 8]);
std::thread::spawn(move || drop(held)).join().unwrap();
assert_eq!(budget.resident_sessions(), 1);
assert_eq!(budget.reserved_bytes(), 278528);
let replacement = budget.reserve(limits, 16384).unwrap();
drop(second);
drop(replacement);
assert_eq!(budget.reserved_bytes(), 0);
assert_eq!(budget.resident_sessions(), 0);
}
#[test]
fn admission_limits_overflow_and_reuse() {
let limits = StorageLimits::new(1, 1, 8, 8).unwrap();
assert!(matches!(
StorageBudget::new(0, 8),
Err(AdmissionError::Invalid(CapacityError::Zero))
));
let budget = StorageBudget::new(2, 24).unwrap();
assert!(matches!(
budget.reserve(limits, usize::MAX),
Err(AdmissionError::Invalid(CapacityError::Overflow))
));
assert!(matches!(
budget.reserve(limits, 17),
Err(AdmissionError::Invalid(CapacityError::ExceedsByteCeiling))
));
for _ in 0..1000 {
let first = budget.reserve(limits, 8).unwrap();
assert!(matches!(
budget.reserve(limits, 1),
Err(AdmissionError::Full)
));
assert_eq!(budget.resident_sessions(), 1);
let second = budget.reserve(limits, 0).unwrap();
assert_eq!(budget.reserved_bytes(), 24);
assert!(matches!(
budget.reserve(limits, 0),
Err(AdmissionError::Full)
));
let clone = first.retain();
drop(first);
assert_eq!(budget.reserved_bytes(), 24);
drop(clone);
drop(second);
assert_eq!(budget.resident_sessions(), 0);
assert_eq!(budget.reserved_bytes(), 0);
}
}
#[test]
fn heterogeneous_multi_input_manager_normalizes_compensates_drift_and_runs_zero_allocations() {
use crate::schema::Channel;
let t_app = CaptureTarget::application(
ROOT,
Some("us.zoom.xos".into()),
Some("Zoom".into()),
None,
ProcessScope::Exact,
OnRootExit::Stop,
)
.unwrap()
.with_backend(BackendId::ScreenCaptureKit);
let t_mic =
CaptureTarget::microphone(DefaultDeviceMode::Follow).with_backend(BackendId::CoreAudio);
let fmt_48k_stereo = Arc::new(
Format::new(
SampleType::F32,
ByteOrder::Little,
48_000,
2,
Layout::Known(Arc::from([Channel::FrontLeft, Channel::FrontRight])),
)
.unwrap(),
);
let fmt_16k_mono_i16 = Arc::new(
Format::new(
SampleType::I16,
ByteOrder::Little,
16_000,
1,
Layout::Known(Arc::from([Channel::Mono])),
)
.unwrap(),
);
let req = CaptureRequest::new(vec![t_app.clone(), t_mic.clone()]);
let mut multi = MultiInputManager::new_heterogeneous(
req,
vec![
(BackendId::ScreenCaptureKit, fmt_48k_stereo.clone()),
(BackendId::CoreAudio, fmt_16k_mono_i16.clone()),
],
480,
1024,
)
.unwrap();
assert_eq!(multi.working_format(), &fmt_48k_stereo);
assert_eq!(
multi.input_handles()[0].backend(),
BackendId::ScreenCaptureKit
);
assert!(!multi.input_handles()[0].is_resampled());
assert!(multi.input_handles()[0].is_identity_bypass());
assert_eq!(multi.input_handles()[1].backend(), BackendId::CoreAudio);
assert!(multi.input_handles()[1].is_resampled());
assert!(!multi.input_handles()[1].is_identity_bypass());
let mut app_pkt = Vec::with_capacity(480 * 8);
for _ in 0..(480 * 2) {
app_pkt.extend_from_slice(&0.25_f32.to_le_bytes());
}
let mut mic_fast_pkt = Vec::with_capacity(161 * 2);
for _ in 0..161 {
mic_fast_pkt.extend_from_slice(&(8192_i16).to_le_bytes()); }
let mut out_bytes = Vec::with_capacity(480 * 8);
multi.push_raw_input_bytes(0, &app_pkt, None, 0).unwrap();
multi
.push_raw_input_bytes(1, &mic_fast_pkt, None, 0)
.unwrap();
multi
.push_raw_input_bytes(1, &mic_fast_pkt, None, 5_000_000)
.unwrap();
let _ = multi
.poll_mix_bytes(480, 10_000_000, 0, &mut out_bytes)
.unwrap();
let allocs = allocation_counter::measure(|| {
for step in 1..=300u64 {
let now_ns = step * 10_000_000;
multi
.push_raw_input_bytes(0, &app_pkt, None, now_ns)
.unwrap();
multi
.push_raw_input_bytes(1, &mic_fast_pkt, None, now_ns)
.unwrap();
let (outcome, _) = multi
.poll_mix_bytes(480, now_ns, 0, &mut out_bytes)
.unwrap();
assert_eq!(outcome, MixStepOutcome::Produced(480));
}
});
assert_eq!(allocs.count_total, 0);
let mic_snap = multi.input_handles()[1].snapshot().unwrap();
assert!(mic_snap.drift_slips >= 2);
assert_eq!(mic_snap.dropped_frames, 0);
let mapping = multi
.reconfigure_targets_with_formats(
vec![t_mic.clone()],
vec![(BackendId::CoreAudio, fmt_16k_mono_i16.clone())],
)
.unwrap();
assert_eq!(mapping, vec![Some(1)]);
assert!(multi.input_handles()[0].is_resampled());
let mut dst_sub = vec![0u8; 240 * 8];
multi
.push_raw_input_bytes(0, &mic_fast_pkt, None, 3_010_000_000)
.unwrap();
let _ = multi
.read_mixed_into(&mut dst_sub, 240, 3_010_000_000, 0)
.unwrap();
let _ = multi
.read_mixed_into(&mut dst_sub, 240, 3_010_000_000, 0)
.unwrap();
let into_allocs = allocation_counter::measure(|| {
for step in 302..=400u64 {
let now_ns = step * 10_000_000;
multi
.push_raw_input_bytes(0, &mic_fast_pkt, None, now_ns)
.unwrap();
let (r1, m1) = multi.read_mixed_into(&mut dst_sub, 240, now_ns, 0).unwrap();
assert_eq!(r1.frames, 240);
assert!(multi.has_pending_output());
let (r2, m2) = multi.read_mixed_into(&mut dst_sub, 240, now_ns, 0).unwrap();
assert_eq!(r2.frames, 240);
assert!(!multi.has_pending_output());
assert_eq!(m1.membership_version, m2.membership_version);
}
});
assert_eq!(into_allocs.count_total, 0);
assert!(multi.last_block_metadata().is_some());
}
#[test]
fn multi_input_manager_charges_out_pool_budget_and_enforces_hot_swap_format_gates() {
use crate::schema::Channel;
let fmt_16k_mono = Arc::new(
Format::new(
SampleType::F32,
ByteOrder::Little,
16_000,
1,
Layout::Known(Arc::from([Channel::Mono])),
)
.unwrap(),
);
let fmt_48k_stereo = Arc::new(
Format::new(
SampleType::F32,
ByteOrder::Little,
48_000,
2,
Layout::Known(Arc::from([Channel::FrontLeft, Channel::FrontRight])),
)
.unwrap(),
);
let t1 = CaptureTarget::microphone(DefaultDeviceMode::Follow);
let t2 = CaptureTarget::default_output(DefaultDeviceMode::Follow);
let shared_budget = StorageBudget::new(16, 4 * 1024 * 1024).unwrap();
let req_16k = CaptureRequest::single(t1.clone());
let mut mgr_16k = MultiInputManager::new_heterogeneous_with_budget(
req_16k,
vec![(BackendId::Wasapi, fmt_16k_mono.clone())],
default_block_frames_for_rate(16_000, 1024),
1024,
shared_budget.clone(),
)
.unwrap();
assert_eq!(shared_budget.resident_sessions(), 0);
assert_eq!(shared_budget.reserved_bytes(), 8 * 1024 * 4);
let stream_limits = StorageLimits::new(8, 256, 8, 8 * 256 * 8).unwrap();
let mut stream_res = Vec::new();
for _ in 0..16 {
stream_res.push(shared_budget.reserve(stream_limits, 0).unwrap());
}
assert_eq!(shared_budget.resident_sessions(), 16);
drop(stream_res);
let tiny_budget = StorageBudget::new(4, 16 * 1024).unwrap();
let too_small = MultiInputManager::new_heterogeneous_with_budget(
CaptureRequest::single(t1.clone()),
vec![(BackendId::Wasapi, fmt_16k_mono.clone())],
160,
1024,
tiny_budget,
);
assert_eq!(too_small.err(), Some(ManagerError::Capacity));
let promote_err = mgr_16k.reconfigure_targets_with_formats(
vec![t1.clone(), t2.clone()],
vec![
(BackendId::Wasapi, fmt_16k_mono.clone()),
(BackendId::Wasapi, fmt_48k_stereo.clone()),
],
);
assert_eq!(promote_err, Err(ManagerError::WorkingFormatChanged));
assert_eq!(mgr_16k.targets().len(), 1);
drop(mgr_16k);
assert_eq!(shared_budget.reserved_bytes(), 0);
let strict_req = CaptureRequest::single(t2.clone())
.with_input_conversion(InputConversionPolicy::StrictNoResample);
let mut strict_mgr = MultiInputManager::new_heterogeneous(
strict_req,
vec![(BackendId::Wasapi, fmt_48k_stereo.clone())],
480,
1024,
)
.unwrap();
let strict_err = strict_mgr.reconfigure_targets_with_formats(
vec![t2, t1],
vec![
(BackendId::Wasapi, fmt_48k_stereo),
(BackendId::Wasapi, fmt_16k_mono),
],
);
assert_eq!(strict_err, Err(ManagerError::Unsupported));
assert_eq!(strict_mgr.targets().len(), 1);
}
#[test]
fn output_stage_and_idle_clock_rational_pacing_passthrough_raw_bytes_and_zero_allocs() {
use crate::schema::{Channel, DitherMode};
let mut clk_44k = IdleOutputClock::new(44_100, 441).unwrap();
assert_eq!(clk_44k.idle_grace_ns(), DEFAULT_IDLE_GRACE_NS);
assert_eq!(
clk_44k.poll_silence_quantum(0, false),
Err(PartialReason::WouldBlock)
);
assert_eq!(
clk_44k.poll_silence_quantum(29_999_999, true),
Err(PartialReason::Timeout)
);
for step in 0..1_000u64 {
let expected_due = 30_000_000 + step * 10_000_000;
let due = clk_44k.next_deadline_ns(expected_due.saturating_sub(5_000_000));
assert_eq!(due, expected_due);
assert_eq!(clk_44k.poll_silence_quantum(due, true), Ok(441));
}
assert_eq!(clk_44k.poll_silence_quantum(10_180_000_000, true), Ok(441));
assert_eq!(
clk_44k.poll_silence_quantum(10_185_000_000, false),
Err(PartialReason::WouldBlock)
);
let mut clk_48k = IdleOutputClock::new(48_000, 480).unwrap();
clk_48k.record_real_frames(52_500_000, 480, 48_000);
assert_eq!(clk_48k.next_deadline_ns(52_500_000), 92_500_000);
assert_eq!(
clk_48k.poll_silence_quantum(92_499_999, true),
Err(PartialReason::Timeout)
);
assert_eq!(clk_48k.poll_silence_quantum(92_500_000, true), Ok(480));
assert_eq!(clk_48k.next_deadline_ns(92_500_000), 102_500_000);
assert_eq!(clk_48k.poll_silence_quantum(102_500_000, true), Ok(480));
let budget = StorageBudget::new(4, 4 * 1024 * 1024).unwrap();
let in_48k = Arc::new(
Format::new(
SampleType::F32,
ByteOrder::Little,
48_000,
2,
Layout::Known(Arc::from([Channel::FrontLeft, Channel::FrontRight])),
)
.unwrap(),
);
let out_16k_i16 = Format::new(
SampleType::I16,
ByteOrder::Little,
16_000,
1,
Layout::Known(Arc::from([Channel::Mono])),
)
.unwrap();
let mut stage = OutputStage::new(
OutputStageConfig {
input_format: in_48k,
output_converter: Some(OutputConverterConfig::new(out_16k_i16, DitherMode::Tpdf)),
gain: 0.5,
clamp_f32: true,
silence_on_idle: true,
idle_grace_ns: DEFAULT_IDLE_GRACE_NS,
output_queue_slots: 8,
quantum_frames: 480,
max_frames_per_block: 1024,
},
&budget,
)
.unwrap();
let mut pkt_200 = Vec::with_capacity(200 * 8);
for _ in 0..(200 * 2) {
pkt_200.extend_from_slice(&0.8_f32.to_le_bytes());
}
let mut meta = MixedBlockMetadata::default();
let out_f = stage
.process_raw_bytes(&pkt_200, &mut meta, 5_000_000)
.unwrap();
assert!(out_f > 50);
let mut dst = [0u8; 256 * 2];
let (res0, _) = stage.finish_into(&mut dst, out_f, 256, meta).unwrap();
assert_eq!(res0.frames, out_f);
while stage.try_pop_pending_into(&mut dst, 256).unwrap().is_some() {}
let mut pkt_480 = Vec::with_capacity(480 * 8);
for _ in 0..(480 * 2) {
pkt_480.extend_from_slice(&0.8_f32.to_le_bytes());
}
let warm_f = stage
.process_raw_bytes(&pkt_480, &mut meta, 15_000_000)
.unwrap();
let _ = stage.finish_into(&mut dst, warm_f, 160, meta).unwrap();
while stage.try_pop_pending_into(&mut dst, 160).unwrap().is_some() {}
let allocs = allocation_counter::measure(|| {
for step in 2..=1_001u64 {
let mut m = MixedBlockMetadata::default();
let produced = stage
.process_raw_bytes(&pkt_480, &mut m, step * 10_000_000)
.unwrap();
assert_eq!(produced, 160);
let (r, _) = stage.finish_into(&mut dst, produced, 160, m).unwrap();
assert_eq!(r.frames, 160);
}
});
assert_eq!(allocs.count_total, 0);
}
#[test]
fn multi_input_manager_deadline_scheduler_starting_peer_zero_delay_and_instant_cancel() {
use crate::schema::{Channel, MixerConfig};
use std::sync::atomic::{AtomicU64, Ordering::Relaxed};
use std::time::Duration;
struct MockClock(Arc<AtomicU64>);
impl ReadClock for MockClock {
fn now_ns(&mut self) -> u64 {
self.0.load(Relaxed)
}
}
let fmt = Arc::new(
Format::new(
SampleType::F32,
ByteOrder::Little,
48_000,
2,
Layout::Known(Arc::from([Channel::FrontLeft, Channel::FrontRight])),
)
.unwrap(),
);
let t1 = CaptureTarget::process(ROOT, ProcessScope::Tree, OnRootExit::Stop).unwrap();
let t2 = CaptureTarget::process(CHILD, ProcessScope::Tree, OnRootExit::Stop).unwrap();
let req = CaptureRequest::new(vec![t1, t2]).with_mixer_config(MixerConfig {
alignment_window_ns: 20_000_000,
silence_on_idle: false,
..MixerConfig::default()
});
let mut multi = MultiInputManager::new(req, fmt, 64).unwrap();
let now_shared = Arc::new(AtomicU64::new(1_000_000));
let mut clock = MockClock(Arc::clone(&now_shared));
let cancel = Cancellation::default();
let mut dst = [0u8; 64 * 8];
let wakes_before = multi.session_notifier().park_wakeups();
let mut fed_once = false;
let (res, meta) = multi
.schedule_mixed_into_with_clock(
&mut dst,
64,
CallerWait::Bounded(Duration::from_millis(50)),
&cancel,
&mut clock,
|mgr, t_ns| {
if !fed_once {
fed_once = true;
mgr.push_input_packet(
0,
MixerInputPacket {
samples: vec![0.5_f32; 128],
frames: 64,
timestamp: None,
arrival_ns: t_ns,
},
)
.unwrap();
}
},
)
.unwrap();
assert_eq!(res.frames, 64);
assert_eq!(res.reason, PartialReason::Complete);
assert_eq!(meta.contributing_mask, 0b01);
assert_eq!(multi.session_notifier().park_wakeups(), wakes_before);
let (wb_res, _) = multi
.schedule_mixed_into_with_clock(
&mut dst,
64,
CallerWait::Zero,
&cancel,
&mut clock,
|_, _| {},
)
.unwrap();
assert_eq!(wb_res.frames, 0);
assert_eq!(wb_res.reason, PartialReason::WouldBlock);
multi
.set_input_state(0, ParticipationState::Exited)
.unwrap();
multi
.set_input_state(1, ParticipationState::WaitingRelaunch)
.unwrap();
multi.set_relaunch_deadline_ns(1, Some(5_000_000)).unwrap();
now_shared.store(5_000_000, Relaxed);
let (eof_res, _) = multi
.schedule_mixed_into_with_clock(
&mut dst,
64,
CallerWait::Bounded(Duration::from_millis(20)),
&cancel,
&mut clock,
|_, _| {},
)
.unwrap();
assert_eq!(eof_res.reason, PartialReason::Eof);
let t_live = CaptureTarget::process(ROOT, ProcessScope::Tree, OnRootExit::Stop).unwrap();
let mut live_multi = MultiInputManager::new(
CaptureRequest::single(t_live),
multi.working_format().clone(),
64,
)
.unwrap();
let cancel_live = Cancellation::default();
let cancel_clone = cancel_live.clone();
let killer = std::thread::spawn(move || {
std::thread::sleep(Duration::from_millis(12));
let t_cancel = Instant::now();
cancel_clone.cancel();
t_cancel
});
let (cancel_res, _) = live_multi
.schedule_mixed_into(&mut dst, 64, CallerWait::Unbounded, &cancel_live, |_, _| {})
.unwrap();
let cancel_at = killer.join().unwrap();
let wake_latency = cancel_at.elapsed();
assert_eq!(cancel_res.reason, PartialReason::Cancelled);
assert!(
wake_latency < Duration::from_millis(5),
"expected < 5ms cancel wake latency, observed {wake_latency:?}"
);
assert!(live_multi.session_notifier().park_wakeups() <= 1);
let t_steady = CaptureTarget::process(ROOT, ProcessScope::Tree, OnRootExit::Stop).unwrap();
let mut steady_multi = MultiInputManager::new(
CaptureRequest::single(t_steady),
multi.working_format().clone(),
64,
)
.unwrap();
let mut raw_pkt = [0u8; 64 * 8];
for chunk in raw_pkt.as_chunks_mut::<4>().0 {
chunk.copy_from_slice(&0.25_f32.to_le_bytes());
}
let idle_cancel = Cancellation::default();
let _ = steady_multi
.schedule_mixed_into(&mut dst, 64, CallerWait::Zero, &idle_cancel, |mgr, t_ns| {
mgr.push_raw_input_bytes(0, &raw_pkt, None, t_ns).unwrap();
})
.unwrap();
let allocs = allocation_counter::measure(|| {
for _ in 0..1_000 {
let (r, _) = steady_multi
.schedule_mixed_into(
&mut dst,
64,
CallerWait::Zero,
&idle_cancel,
|mgr, t_ns| {
mgr.push_raw_input_bytes(0, &raw_pkt, None, t_ns).unwrap();
},
)
.unwrap();
assert_eq!(r.frames, 64);
}
});
assert_eq!(allocs.count_total, 0);
}
#[test]
fn passthrough_and_multi_input_media_horizon_jitter_burst_and_silence_preemption() {
use crate::{
measurements::Trace,
ordering::{self, ControlHandle, Overflow, Stop},
reads::ReadStream,
schema::{Channel, DitherMode, MixerConfig, Provenance},
stream_runtime::{
EndReason, StreamReadContext, poll_read_stream, poll_read_stream_into,
},
};
use std::sync::atomic::{AtomicU64, Ordering::Relaxed};
use std::time::Duration;
struct MockClock(Arc<AtomicU64>);
impl ReadClock for MockClock {
fn now_ns(&mut self) -> u64 {
self.0.load(Relaxed)
}
}
struct PooledTestStream {
format: Arc<Format>,
reads: ReadStream,
ready: Arc<ReadySignal>,
cancel: Cancellation,
}
impl AudioStreamBackend for PooledTestStream {
fn format(&self) -> &Arc<Format> {
&self.format
}
fn trace(&self) -> Option<&Arc<Trace>> {
None
}
fn control_handle(&self) -> ControlHandle {
self.reads.control_handle()
}
fn default_cancel(&self) -> Cancellation {
self.cancel.clone()
}
fn end_reason(&self) -> Option<EndReason> {
None
}
fn read_with_cancel(
&mut self,
frames: usize,
timeout: Duration,
cancel: Cancellation,
) -> Result<ReadResult, ReadError> {
poll_read_stream(
StreamReadContext {
reads: &self.reads,
ready: &self.ready,
trace: None,
},
frames,
timeout,
cancel,
)
}
fn read_into_with_cancel(
&mut self,
destination: &mut [u8],
frames: usize,
timeout: Duration,
cancel: Cancellation,
) -> Result<ReadResult, ReadError> {
poll_read_stream_into(
StreamReadContext {
reads: &self.reads,
ready: &self.ready,
trace: None,
},
self.format.clone(),
destination,
frames,
timeout,
cancel,
)
}
fn stop(&self, mode: Stop) {
self.reads.control_handle().stop(mode);
}
fn resources_done(&self) -> bool {
true
}
fn wait_cleanup(&self, _timeout: Duration) -> bool {
true
}
}
let budget = StorageBudget::new(8, 8 * 1024 * 1024).unwrap();
let stereo_48k = Arc::new(
Format::new(
SampleType::F32,
ByteOrder::Little,
48_000,
2,
Layout::Known(Arc::from([Channel::FrontLeft, Channel::FrontRight])),
)
.unwrap(),
);
let limits = StorageLimits::new(8, 2048, 8, 8 * 2048 * 8).unwrap();
let res = budget.reserve(limits, 0).unwrap();
let (mut prod, reader) = ordering::channel(
Pool::new_reserved(limits, 2048, stereo_48k.clone(), res).unwrap(),
8,
)
.unwrap();
let ready = Arc::new(ReadySignal::new());
let mut stream = PooledTestStream {
format: stereo_48k.clone(),
reads: ReadStream::new(reader),
ready: ready.clone(),
cancel: Cancellation::default(),
};
let t_proc = CaptureTarget::process(ROOT, ProcessScope::Tree, OnRootExit::Stop).unwrap();
let req = CaptureRequest::single(t_proc).with_mixer_config(MixerConfig {
silence_on_idle: true,
idle_grace_ns: 30_000_000,
..MixerConfig::default()
});
let mut pt = PassThroughStage::new(&req, stereo_48k.clone(), 2048, &budget).unwrap();
pt.bind_stream_ready(&ready).unwrap();
let now_shared = Arc::new(AtomicU64::new(0));
let mut clock = MockClock(Arc::clone(&now_shared));
let cancel = Cancellation::default();
let mut dst = vec![0u8; 480 * 8];
let mut seq = 0u64;
let offer_frames = |prod: &mut ordering::Producer,
ready: &ReadySignal,
seq: &mut u64,
frames: usize,
val: f32| {
*seq += 1;
let mut bytes = Vec::with_capacity(frames * 8);
for _ in 0..(frames * 2) {
bytes.extend_from_slice(&val.to_le_bytes());
}
prod.offer(
&bytes,
Header {
sequence: *seq,
segment: 1,
generation: 1,
frames,
sample_position: None,
timestamp: Some(Stamp {
ticks: *seq * 100_000,
ticks_per_second: 10_000_000,
clock_domain: 1,
provenance: Provenance::Native,
uncertainty_ns: None,
}),
},
Overflow::DropOldest,
);
ready.notify();
};
for &arrival_ns in &[10_000_000u64, 25_000_000, 30_000_000, 50_000_000] {
now_shared.store(arrival_ns, Relaxed);
if arrival_ns == 50_000_000 {
offer_frames(&mut prod, &ready, &mut seq, 480, 0.4);
offer_frames(&mut prod, &ready, &mut seq, 480, 0.4);
for _ in 0..2 {
let (r, m) = pt
.read_into_with_clock(
Some(&mut stream),
&mut dst,
480,
CallerWait::Zero,
&cancel,
&mut clock,
1,
None,
)
.unwrap();
assert_eq!(r.frames, 480);
assert!(!m.synthesized_silence);
}
} else {
offer_frames(&mut prod, &ready, &mut seq, 480, 0.4);
let (r, m) = pt
.read_into_with_clock(
Some(&mut stream),
&mut dst,
480,
CallerWait::Zero,
&cancel,
&mut clock,
1,
None,
)
.unwrap();
assert_eq!(r.frames, 480);
assert!(!m.synthesized_silence);
}
}
now_shared.store(65_000_000, Relaxed);
let (wb, _) = pt
.read_into_with_clock(
Some(&mut stream),
&mut dst,
480,
CallerWait::Zero,
&cancel,
&mut clock,
1,
None,
)
.unwrap();
assert_eq!(wb.reason, PartialReason::WouldBlock);
now_shared.store(70_000_000, Relaxed);
offer_frames(&mut prod, &ready, &mut seq, 960, 0.5);
for sub in 0..2u64 {
now_shared.store(70_000_000 + sub * 100_000, Relaxed);
let (r, m) = pt
.read_into_with_clock(
Some(&mut stream),
&mut dst,
480,
CallerWait::Zero,
&cancel,
&mut clock,
1,
None,
)
.unwrap();
assert_eq!(r.frames, 480);
assert!(!m.synthesized_silence);
}
now_shared.store(112_000_000, Relaxed);
offer_frames(&mut prod, &ready, &mut seq, 2048, 0.6);
let mut drained_2048 = 0usize;
while drained_2048 < 2048 {
let (r, m) = pt
.read_into_with_clock(
Some(&mut stream),
&mut dst,
480,
CallerWait::Zero,
&cancel,
&mut clock,
1,
None,
)
.unwrap();
assert!(r.frames > 0);
assert!(!m.synthesized_silence);
drained_2048 += r.frames;
}
assert_eq!(drained_2048, 2048);
now_shared.store(200_000_000, Relaxed);
let mut dst_120 = vec![0u8; 120 * 8];
let (sil_r, sil_m) = pt
.read_into_with_clock(
Some(&mut stream),
&mut dst_120,
120,
CallerWait::Zero,
&cancel,
&mut clock,
1,
None,
)
.unwrap();
assert_eq!(sil_r.frames, 120);
assert!(sil_m.synthesized_silence);
assert!(dst_120.iter().all(|&b| b == 0));
now_shared.store(202_000_000, Relaxed);
offer_frames(&mut prod, &ready, &mut seq, 480, 0.75);
let (preempt_r, preempt_m) = pt
.read_into_with_clock(
Some(&mut stream),
&mut dst_120,
120,
CallerWait::Zero,
&cancel,
&mut clock,
1,
None,
)
.unwrap();
assert_eq!(preempt_r.frames, 120);
assert!(!preempt_m.synthesized_silence);
let first_sample = f32::from_le_bytes(dst_120[0..4].try_into().unwrap());
assert!((first_sample - 0.75).abs() <= 1e-6);
let out_16k_f32 = Format::new(
SampleType::F32,
ByteOrder::Little,
16_000,
2,
Layout::Known(Arc::from([Channel::FrontLeft, Channel::FrontRight])),
)
.unwrap();
let res2 = budget.reserve(limits, 0).unwrap();
let (mut prod2, reader2) = ordering::channel(
Pool::new_reserved(limits, 2048, stereo_48k.clone(), res2).unwrap(),
8,
)
.unwrap();
let ready2 = Arc::new(ReadySignal::new());
let mut stream2 = PooledTestStream {
format: stereo_48k.clone(),
reads: ReadStream::new(reader2),
ready: ready2.clone(),
cancel: Cancellation::default(),
};
let req_conv = CaptureRequest::single(
CaptureTarget::process(ROOT, ProcessScope::Tree, OnRootExit::Stop).unwrap(),
)
.with_output_converter(Some(OutputConverterConfig::new(
out_16k_f32,
DitherMode::None,
)));
let mut pt_conv = PassThroughStage::new(&req_conv, stereo_48k, 480, &budget).unwrap();
pt_conv.bind_stream_ready(&ready2).unwrap();
for _ in 0..3 {
offer_frames(&mut prod2, &ready2, &mut seq, 480, 0.5);
}
prod2.close();
drop(prod2);
let mut dst_16k = vec![0u8; 256 * 8];
let mut total_16k_frames = 0usize;
loop {
let (r, m) = pt_conv
.read_into_with_clock(
Some(&mut stream2),
&mut dst_16k,
160,
CallerWait::Zero,
&cancel,
&mut clock,
1,
None,
)
.unwrap();
if r.reason == PartialReason::Eof && r.frames == 0 {
break;
}
assert!(r.frames > 0);
assert!(!m.synthesized_silence);
total_16k_frames += r.frames;
}
assert_eq!(total_16k_frames, 480);
}
#[test]
fn multi_input_lossless_idle_eof_tail_flush_and_cross_clock_drift_gating() {
use crate::schema::{Channel, DitherMode, MixerConfig, Provenance};
use std::sync::atomic::{AtomicU64, Ordering::Relaxed};
struct MockClock(Arc<AtomicU64>);
impl ReadClock for MockClock {
fn now_ns(&mut self) -> u64 {
self.0.load(Relaxed)
}
}
let stereo_48k = Arc::new(
Format::new(
SampleType::F32,
ByteOrder::Little,
48_000,
2,
Layout::Known(Arc::from([Channel::FrontLeft, Channel::FrontRight])),
)
.unwrap(),
);
let out_16k_f32 = Format::new(
SampleType::F32,
ByteOrder::Little,
16_000,
2,
Layout::Known(Arc::from([Channel::FrontLeft, Channel::FrontRight])),
)
.unwrap();
let t1 = CaptureTarget::process(ROOT, ProcessScope::Tree, OnRootExit::Stop).unwrap();
let req = CaptureRequest::single(t1)
.with_output_converter(Some(OutputConverterConfig::new(
out_16k_f32,
DitherMode::None,
)))
.with_mixer_config(MixerConfig {
silence_on_idle: true,
idle_grace_ns: 30_000_000,
..MixerConfig::default()
});
let mut multi = MultiInputManager::new_heterogeneous(
req,
vec![(BackendId::Wasapi, stereo_48k.clone())],
480,
1024,
)
.unwrap();
let now_shared = Arc::new(AtomicU64::new(0));
let mut clock = MockClock(Arc::clone(&now_shared));
let cancel = Cancellation::default();
let mut dst = vec![0u8; 256 * 8];
let make_f32_bytes = |frames: usize, val: f32| -> Vec<u8> {
let mut v = Vec::with_capacity(frames * 8);
for _ in 0..(frames * 2) {
v.extend_from_slice(&val.to_le_bytes());
}
v
};
let pkt_256 = make_f32_bytes(256, 0.5);
now_shared.store(5_000_000, Relaxed);
assert_eq!(
multi
.push_raw_input_bytes(0, &pkt_256, None, 5_000_000)
.unwrap(),
0
);
now_shared.store(32_000_000, Relaxed);
let (wb_res, _) = multi
.schedule_mixed_into_with_clock(
&mut dst,
160,
CallerWait::Zero,
&cancel,
&mut clock,
|_, _| {},
)
.unwrap();
assert_eq!(wb_res.reason, PartialReason::WouldBlock);
let pkt_424 = make_f32_bytes(424, 0.5);
now_shared.store(15_000_000, Relaxed);
assert_eq!(
multi
.push_raw_input_bytes(0, &pkt_424, None, 15_000_000)
.unwrap(),
1
);
let (act_res, act_meta) = multi
.schedule_mixed_into_with_clock(
&mut dst,
160,
CallerWait::Zero,
&cancel,
&mut clock,
|_, _| {},
)
.unwrap();
assert_eq!(act_res.frames, 150);
assert!(!act_meta.synthesized_silence);
now_shared.store(60_000_000, Relaxed);
let (reb_tail_res, reb_tail_meta) = multi
.schedule_mixed_into_with_clock(
&mut dst,
160,
CallerWait::Zero,
&cancel,
&mut clock,
|_, _| {},
)
.unwrap();
assert_eq!(reb_tail_res.frames, 160);
assert!(!reb_tail_meta.synthesized_silence);
now_shared.store(70_000_000, Relaxed);
let (conv_tail_res, conv_tail_meta) = multi
.schedule_mixed_into_with_clock(
&mut dst,
160,
CallerWait::Zero,
&cancel,
&mut clock,
|_, _| {},
)
.unwrap();
assert_eq!(conv_tail_res.frames, 10);
assert!(!conv_tail_meta.synthesized_silence);
now_shared.store(80_000_000, Relaxed);
let (pure_sil_res, pure_sil_meta) = multi
.schedule_mixed_into_with_clock(
&mut dst,
160,
CallerWait::Zero,
&cancel,
&mut clock,
|_, _| {},
)
.unwrap();
assert_eq!(pure_sil_res.frames, 160);
assert!(pure_sil_meta.synthesized_silence);
assert!(dst[..160 * 8].iter().all(|&b| b == 0));
let pkt_resume = make_f32_bytes(200, -0.25);
now_shared.store(85_000_000, Relaxed);
assert_eq!(
multi
.push_raw_input_bytes(0, &pkt_resume, None, 85_000_000)
.unwrap(),
0
);
multi
.set_input_state(0, ParticipationState::Exited)
.unwrap();
let mut post_resume_frames = 0usize;
loop {
let (r, m) = multi
.schedule_mixed_into_with_clock(
&mut dst,
160,
CallerWait::Zero,
&cancel,
&mut clock,
|_, _| {},
)
.unwrap();
if r.reason == PartialReason::Eof && r.frames == 0 {
break;
}
assert!(!m.synthesized_silence);
for chunk in dst[..r.frames * 8].as_chunks::<4>().0 {
let s = f32::from_le_bytes(*chunk);
assert!(s <= 0.05, "unexpected pre-pause positive sample bleed: {s}");
}
post_resume_frames += r.frames;
}
assert_eq!(post_resume_frames, 160);
let ta = CaptureTarget::process(ROOT, ProcessScope::Tree, OnRootExit::Stop).unwrap();
let tb = CaptureTarget::process(CHILD, ProcessScope::Tree, OnRootExit::Stop).unwrap();
let mut lone_sub = MultiInputManager::new_heterogeneous(
CaptureRequest::single(ta.clone()),
vec![(BackendId::Wasapi, stereo_48k.clone())],
480,
1024,
)
.unwrap();
let pkt_300 = make_f32_bytes(300, 0.3);
let mut out_480 = vec![0u8; 480 * 8];
for step in 1..=200u64 {
let t_ns = step * 6_250_000;
lone_sub
.push_raw_input_bytes(0, &pkt_300, None, t_ns)
.unwrap();
let _ = lone_sub
.read_mixed_into(&mut out_480, 480, t_ns, 0)
.unwrap();
}
assert_eq!(
lone_sub.input_handles()[0].snapshot().unwrap().drift_slips,
0
);
let mut slow_peer_mgr = MultiInputManager::new_heterogeneous(
CaptureRequest::new(vec![ta.clone(), tb.clone()]),
vec![
(BackendId::Wasapi, stereo_48k.clone()),
(BackendId::Wasapi, stereo_48k.clone()),
],
480,
1024,
)
.unwrap();
let pkt_480 = make_f32_bytes(480, 0.25);
let pkt_477 = make_f32_bytes(477, 0.25);
let stamp_dom1 = Some(Stamp {
ticks: 100_000,
ticks_per_second: 10_000_000,
clock_domain: 1,
provenance: Provenance::Native,
uncertainty_ns: None,
});
let stamp_dom2 = Some(Stamp {
ticks: 100_000,
ticks_per_second: 10_000_000,
clock_domain: 2,
provenance: Provenance::Native,
uncertainty_ns: None,
});
let slow_now = Arc::new(AtomicU64::new(0));
let mut slow_clock = MockClock(Arc::clone(&slow_now));
slow_peer_mgr
.push_raw_input_bytes(0, &pkt_480, stamp_dom1, 0)
.unwrap();
slow_peer_mgr
.push_raw_input_bytes(1, &pkt_480, stamp_dom2, 0)
.unwrap();
let _ = slow_peer_mgr
.schedule_mixed_into_with_clock(
&mut out_480,
480,
CallerWait::Zero,
&cancel,
&mut slow_clock,
|_, _| {},
)
.unwrap();
let mut produced_slow_blocks = 0usize;
let drift_allocs = allocation_counter::measure(|| {
for step in 1..=300u64 {
let t_ns = step * 10_000_000;
slow_now.store(t_ns, Relaxed);
slow_peer_mgr
.push_raw_input_bytes(0, &pkt_480, stamp_dom1, t_ns)
.unwrap();
slow_peer_mgr
.push_raw_input_bytes(1, &pkt_477, stamp_dom2, t_ns)
.unwrap();
loop {
let (r, m) = slow_peer_mgr
.schedule_mixed_into_with_clock(
&mut out_480,
480,
CallerWait::Zero,
&cancel,
&mut slow_clock,
|_, _| {},
)
.unwrap();
if r.frames == 0 {
break;
}
assert_eq!(r.frames, 480);
assert_eq!(m.late_inputs, 0, "unexpected Late dropout on slow peer");
produced_slow_blocks += 1;
}
if step == 60 {
assert_eq!(
slow_peer_mgr.input_handles()[0]
.snapshot()
.unwrap()
.drift_slips,
0
);
}
}
});
assert_eq!(drift_allocs.count_total, 0);
assert!(produced_slow_blocks >= 298);
assert_eq!(
slow_peer_mgr.input_handles()[0]
.snapshot()
.unwrap()
.drift_slips,
2
);
let mut repeat_mgr = MultiInputManager::new_heterogeneous(
CaptureRequest::new(vec![ta, tb]),
vec![
(BackendId::Wasapi, stereo_48k.clone()),
(BackendId::Wasapi, stereo_48k),
],
480,
1024,
)
.unwrap();
let pkt_200 = make_f32_bytes(200, 0.25);
repeat_mgr
.push_raw_input_bytes(0, &pkt_480, stamp_dom1, 0)
.unwrap();
repeat_mgr
.push_raw_input_bytes(1, &pkt_480, stamp_dom2, 0)
.unwrap();
let _ = repeat_mgr
.read_mixed_into(&mut out_480, 480, 5_000_000, 0)
.unwrap();
repeat_mgr
.push_raw_input_bytes(1, &pkt_200, stamp_dom2, 10_000_000)
.unwrap();
let repeat_allocs = allocation_counter::measure(|| {
for step in 1..=60u64 {
let t_ns = step * 10_000_000;
repeat_mgr
.push_raw_input_bytes(0, &pkt_480, stamp_dom1, t_ns)
.unwrap();
let (r, _) = repeat_mgr
.read_mixed_into(&mut out_480, 480, t_ns, 20_000_000)
.unwrap();
assert_eq!(r.frames, 480);
}
});
assert_eq!(repeat_allocs.count_total, 0);
assert_eq!(
repeat_mgr.input_handles()[0]
.snapshot()
.unwrap()
.drift_slips,
0
);
assert_eq!(
repeat_mgr.input_handles()[1]
.snapshot()
.unwrap()
.drift_slips,
1
);
}
#[test]
fn native_tree_mix_topology_prune_missing_sources_detaches_dead_links() {
let mut topo = NativeTreeMixTopology::new(8).unwrap();
assert!(topo.attach_source(0, "41:70->12").unwrap());
assert!(!topo.attach_source(1, "41:70->12").unwrap());
assert!(topo.attach_source(1, "52:88->13").unwrap());
assert_eq!(topo.active_link_count(), 2);
let pruned = topo.prune_missing_sources(|src| src.starts_with("52:"));
assert_eq!(pruned.len(), 1);
assert_eq!(pruned[0].as_ref(), "41:70->12");
assert_eq!(topo.active_link_count(), 1);
let pruned_all = topo.prune_missing_sources(|_| false);
assert_eq!(pruned_all.len(), 1);
assert_eq!(topo.active_link_count(), 0);
}
}