1use crate::{
2 capabilities::resolve_windows_plan,
3 core::{
4 manager::{
5 BoundaryKind, InputStatusHandle, ManagerError, MultiInputManager, SessionBoundary,
6 StorageBudget, default_block_frames_for_rate,
7 },
8 ordering::{self, Failure, Overflow, Stop},
9 planner::{CapturePlanReport, CaptureRequest},
10 reads::{Cancellation, PartialReason, ReadError, ReadResult},
11 routing::RouteRollbackGuard,
12 schema::{
13 BackendId, ByteOrder, CaptureTarget, Channel, CombineResolution, DefaultDeviceMode,
14 Format, Layout, MembershipDescriptor, MixedBlockMetadata, OnFormatChange, OnRootExit,
15 ParticipationState, ProcessScope, SampleType, TargetKind,
16 },
17 stream_runtime::{EndReason, StartupCleanup},
18 traits::{
19 AudioStreamBackend, CapabilityError, CaptureManagerBackend, DefaultEndpointObserver,
20 TimingRequirement,
21 },
22 },
23 discovery::{
24 PlatformDefaultInputObserver, PlatformDefaultOutputObserver,
25 query_default_capture_endpoint_id, query_default_render_endpoint_id,
26 },
27 endpoint::{PlatformStream, WasapiOpenTarget},
28 process::inspect_process_executable,
29};
30use std::{
31 sync::{Arc, Mutex, TryLockError},
32 thread,
33 time::{Duration, Instant},
34};
35
36const MAX_FRAMES_PER_SLOT: usize = 4096;
37
38enum PlatformExecutionEngine {
39 PassThrough {
40 stream: Option<Box<PlatformStream>>,
41 waiting_relaunch: bool,
42 wait_deadline: Option<Instant>,
43 },
44 SoftwareMix {
45 block_frames: usize,
46 multi: Box<MultiInputManager>,
47 streams: Vec<Option<PlatformStream>>,
48 last_active_at: Vec<Option<Instant>>,
49 wait_deadlines: Vec<Option<Instant>>,
50 started_at: Instant,
51 in_bytes_scratch: Vec<u8>,
52 },
53}
54
55pub struct PlatformManager {
56 request: CaptureRequest,
57 plan: CapturePlanReport,
58 route_guard: RouteRollbackGuard,
59 policy: Overflow,
60 timing: TimingRequirement,
61 cleanup_timeout: Duration,
62 budget: StorageBudget,
63 engine: PlatformExecutionEngine,
64 default_cancel: Cancellation,
65 pending_cleanup: Option<StartupCleanup>,
66 pending_boundary: Option<SessionBoundary>,
67 last_metadata: Option<MixedBlockMetadata>,
68 default_observer: Option<PlatformDefaultOutputObserver>,
69 default_input_observer: Option<PlatformDefaultInputObserver>,
70 last_default_check: Instant,
71 session_counter: u64,
72 segment_counter: u64,
73 stopped: bool,
74 terminal_error: Option<ManagerError>,
75 read_lock: Mutex<()>,
76}
77
78fn fallback_working_format() -> Result<Arc<Format>, CapabilityError> {
79 Format::new(
80 SampleType::F32,
81 ByteOrder::Little,
82 48_000,
83 2,
84 Layout::Known(Arc::from([Channel::FrontLeft, Channel::FrontRight])),
85 )
86 .map(Arc::new)
87 .map_err(|_| CapabilityError::UnsupportedFormat)
88}
89
90fn resolve_pinned_capture_target(target: &mut CaptureTarget, endpoint: &Arc<str>) {
91 if target.default_device_mode() != DefaultDeviceMode::Pin {
92 return;
93 }
94 *target = match target.kind() {
95 TargetKind::DefaultOutput => target.resolve_pinned_endpoint(Some(endpoint.as_ref()), None),
96 TargetKind::DefaultInput => target.resolve_pinned_endpoint(None, Some(endpoint.as_ref())),
97 _ => return,
98 };
99}
100
101fn map_manager_error(err: ManagerError) -> CapabilityError {
102 match err {
103 ManagerError::Capacity => CapabilityError::CapacityExceeded,
104 ManagerError::CleanupTimeout => CapabilityError::CleanupTimeout,
105 ManagerError::WorkingFormatChanged => CapabilityError::FormatChangeRejected,
106 ManagerError::Unsupported | ManagerError::InvalidConfiguration => {
107 CapabilityError::UnsupportedFormat
108 }
109 ManagerError::InvalidState => CapabilityError::Stopped,
110 _ => CapabilityError::NotImplemented,
111 }
112}
113
114fn build_software_mix_engine(
115 request: CaptureRequest,
116 streams: Vec<Option<PlatformStream>>,
117 last_active_at: Vec<Option<Instant>>,
118 wait_deadlines: Vec<Option<Instant>>,
119 shared_budget: StorageBudget,
120 cleanup_timeout: Duration,
121) -> Result<PlatformExecutionEngine, CapabilityError> {
122 let fallback_fmt = fallback_working_format()?;
123 let per_input: Vec<(BackendId, Arc<Format>)> = streams
124 .iter()
125 .map(|s| {
126 let fmt = s
127 .as_ref()
128 .map_or_else(|| fallback_fmt.clone(), |st| st.native_format.pcm.clone());
129 (BackendId::Wasapi, fmt)
130 })
131 .collect();
132 let max_rate = per_input
133 .iter()
134 .map(|(_, f)| f.rate())
135 .max()
136 .unwrap_or(48_000);
137 let block_frames = default_block_frames_for_rate(max_rate, MAX_FRAMES_PER_SLOT);
138 let max_in_stride = streams
139 .iter()
140 .flatten()
141 .map(|s| s.native_format.pcm.bytes_per_frame())
142 .max()
143 .unwrap_or(8)
144 .max(8);
145
146 let multi = match MultiInputManager::new_heterogeneous_with_budget(
147 request,
148 per_input,
149 block_frames,
150 MAX_FRAMES_PER_SLOT,
151 shared_budget,
152 ) {
153 Ok(m) => m,
154 Err(err) => {
155 for existing in streams.into_iter().flatten() {
156 existing.stop(Stop::Abort);
157 let _ = existing.wait_cleanup(cleanup_timeout);
158 }
159 return Err(map_manager_error(err));
160 }
161 };
162
163 for (idx, s) in streams.iter().enumerate() {
164 if s.is_some() {
165 let _ = multi.set_input_state(idx, ParticipationState::Active);
166 } else if wait_deadlines.get(idx).and_then(|d| *d).is_some() {
167 let _ = multi.set_input_state(idx, ParticipationState::WaitingRelaunch);
168 }
169 }
170
171 Ok(PlatformExecutionEngine::SoftwareMix {
172 block_frames,
173 multi: Box::new(multi),
174 streams,
175 last_active_at,
176 wait_deadlines,
177 started_at: Instant::now(),
178 in_bytes_scratch: vec![0u8; MAX_FRAMES_PER_SLOT * max_in_stride],
179 })
180}
181
182impl PlatformManager {
183 fn open_impl(
184 request: CaptureRequest,
185 policy: Overflow,
186 timing: TimingRequirement,
187 ) -> Result<Self, CapabilityError> {
188 let plan = resolve_windows_plan(&request, timing)?;
189 for target in request.targets() {
190 crate::permissions::ensure_windows_target_permission(target)?;
191 }
192 let cleanup_timeout = Duration::from_nanos(request.budgets().cleanup_timeout_ns);
193 if cleanup_timeout < Duration::from_millis(50) || cleanup_timeout > Duration::from_secs(30)
194 {
195 return Err(CapabilityError::InvalidTarget);
196 }
197
198 let max_streams = if plan.combine_resolution == CombineResolution::CspaMixer {
199 request.budgets().max_active_streams
200 } else {
201 request.budgets().max_active_streams.max(2)
202 };
203 let budget = StorageBudget::new(max_streams, request.budgets().max_total_pcm_memory)
204 .map_err(|_| CapabilityError::CapacityExceeded)?;
205
206 let mut resolved_targets = request.targets().to_vec();
207 let engine = match plan.combine_resolution {
208 CombineResolution::PassThrough(BackendId::Wasapi) => {
209 let target = &mut resolved_targets[0];
210 let open_target = WasapiOpenTarget::from_capture_target(target)?;
211 let initial = match PlatformStream::open_reserved_target(
212 open_target,
213 target.clone(),
214 policy,
215 budget.clone(),
216 Duration::from_secs(5),
217 ) {
218 Ok(stream) => stream,
219 Err((cleanup, err)) => {
220 if let Some(c) = cleanup {
221 let _ = c.wait(cleanup_timeout);
222 }
223 return Err(err);
224 }
225 };
226 resolve_pinned_capture_target(target, &initial.native_format.endpoint);
227 PlatformExecutionEngine::PassThrough {
228 stream: Some(Box::new(initial)),
229 waiting_relaunch: false,
230 wait_deadline: None,
231 }
232 }
233 CombineResolution::CspaMixer => {
234 let mut streams: Vec<Option<PlatformStream>> =
235 Vec::with_capacity(resolved_targets.len());
236 let mut last_active_at = Vec::with_capacity(resolved_targets.len());
237 let mut wait_deadlines = Vec::with_capacity(resolved_targets.len());
238
239 for target in &mut resolved_targets {
240 let open_target = match WasapiOpenTarget::from_capture_target(target) {
241 Ok(ot) => ot,
242 Err(err) => {
243 for existing in streams.into_iter().flatten() {
244 existing.stop(Stop::Abort);
245 let _ = existing.wait_cleanup(cleanup_timeout);
246 }
247 return Err(err);
248 }
249 };
250 match PlatformStream::open_reserved_target(
251 open_target,
252 target.clone(),
253 policy,
254 budget.clone(),
255 Duration::from_secs(5),
256 ) {
257 Ok(stream) => {
258 resolve_pinned_capture_target(target, &stream.native_format.endpoint);
259 streams.push(Some(stream));
260 last_active_at.push(Some(Instant::now()));
261 wait_deadlines.push(None);
262 }
263 Err((cleanup, err)) => {
264 if let Some(c) = cleanup {
265 let _ = c.wait(cleanup_timeout);
266 }
267 for existing in streams.into_iter().flatten() {
268 existing.stop(Stop::Abort);
269 let _ = existing.wait_cleanup(cleanup_timeout);
270 }
271 return Err(err);
272 }
273 }
274 }
275
276 let resolved_req = request.clone().with_targets(resolved_targets.clone());
277 build_software_mix_engine(
278 resolved_req,
279 streams,
280 last_active_at,
281 wait_deadlines,
282 budget.clone(),
283 cleanup_timeout,
284 )?
285 }
286 _ => return Err(CapabilityError::InvalidBackend),
287 };
288
289 let final_request = request.with_targets(resolved_targets);
290 let route_guard = RouteRollbackGuard::new(final_request.allow_reroute());
291 let final_plan = resolve_windows_plan(&final_request, timing).unwrap_or(plan);
292 let mut mgr = Self {
293 request: final_request,
294 plan: final_plan,
295 route_guard,
296 policy,
297 timing,
298 cleanup_timeout,
299 budget,
300 engine,
301 default_cancel: Cancellation::default(),
302 pending_cleanup: None,
303 pending_boundary: None,
304 last_metadata: None,
305 default_observer: None,
306 default_input_observer: None,
307 last_default_check: Instant::now(),
308 session_counter: 1,
309 segment_counter: 1,
310 stopped: false,
311 terminal_error: None,
312 read_lock: Mutex::new(()),
313 };
314 mgr.refresh_default_observers();
315 Ok(mgr)
316 }
317
318 #[cfg(any(test, feature = "native-tests"))]
319 pub fn from_synthetic_streams(
320 request: CaptureRequest,
321 streams: Vec<PlatformStream>,
322 shared_budget: StorageBudget,
323 ) -> Result<Self, CapabilityError> {
324 let plan = resolve_windows_plan(&request, TimingRequirement::Raw)?;
325 let cleanup_timeout = Duration::from_nanos(request.budgets().cleanup_timeout_ns);
326 let route_guard = RouteRollbackGuard::new(request.allow_reroute());
327 let engine = if plan.combine_resolution == CombineResolution::PassThrough(BackendId::Wasapi)
328 && streams.len() == 1
329 {
330 PlatformExecutionEngine::PassThrough {
331 stream: streams.into_iter().next().map(Box::new),
332 waiting_relaunch: false,
333 wait_deadline: None,
334 }
335 } else {
336 let len = streams.len();
337 build_software_mix_engine(
338 request.clone(),
339 streams.into_iter().map(Some).collect(),
340 vec![Some(Instant::now()); len],
341 vec![None; len],
342 shared_budget.clone(),
343 cleanup_timeout,
344 )?
345 };
346 Ok(Self {
347 request,
348 plan,
349 route_guard,
350 policy: Overflow::Fail,
351 timing: TimingRequirement::Raw,
352 cleanup_timeout,
353 budget: shared_budget,
354 engine,
355 default_cancel: Cancellation::default(),
356 pending_cleanup: None,
357 pending_boundary: None,
358 last_metadata: None,
359 default_observer: None,
360 default_input_observer: None,
361 last_default_check: Instant::now(),
362 session_counter: 1,
363 segment_counter: 1,
364 stopped: false,
365 terminal_error: None,
366 read_lock: Mutex::new(()),
367 })
368 }
369
370 pub fn budget(&self) -> &StorageBudget {
371 &self.budget
372 }
373
374 fn refresh_default_observers(&mut self) {
375 let has_follow_out = self.request.targets().iter().any(|t| {
376 t.kind() == TargetKind::DefaultOutput
377 && t.default_device_mode() == DefaultDeviceMode::Follow
378 });
379 if has_follow_out {
380 if self.default_observer.is_none() {
381 self.default_observer = Some(PlatformDefaultOutputObserver::acquire());
382 }
383 } else {
384 self.default_observer = None;
385 }
386
387 let has_follow_in = self.request.targets().iter().any(|t| {
388 t.kind() == TargetKind::DefaultInput
389 && t.default_device_mode() == DefaultDeviceMode::Follow
390 });
391 if has_follow_in {
392 if self.default_input_observer.is_none() {
393 self.default_input_observer = Some(PlatformDefaultInputObserver::acquire());
394 }
395 } else {
396 self.default_input_observer = None;
397 }
398 }
399
400 #[cfg(test)]
401 fn apply_opened_default_stream_for_test(
402 &mut self,
403 expected_kind: TargetKind,
404 next: PlatformStream,
405 ) -> Result<bool, CapabilityError> {
406 if self.stopped || self.terminal_error.is_some() {
407 return Err(CapabilityError::Stopped);
408 }
409 match &mut self.engine {
410 PlatformExecutionEngine::PassThrough { stream, .. } => {
411 let target = self
412 .request
413 .targets()
414 .first()
415 .ok_or(CapabilityError::InvalidTarget)?;
416 if target.kind() != expected_kind
417 || target.default_device_mode() != DefaultDeviceMode::Follow
418 {
419 return Err(CapabilityError::InvalidTarget);
420 }
421 let old_pcm = stream.as_ref().map(|s| s.native_format.pcm.clone());
422 if let Some(old) = stream.take() {
423 old.stop(Stop::Drain);
424 let _ = old.wait_cleanup(self.cleanup_timeout);
425 }
426 if old_pcm
427 .as_ref()
428 .is_some_and(|prev| prev != &next.native_format.pcm)
429 && self.request.on_format_change() == OnFormatChange::Fail
430 {
431 next.stop(Stop::Abort);
432 let _ = next.wait_cleanup(self.cleanup_timeout);
433 self.terminal_error = Some(ManagerError::Unsupported);
434 return Err(CapabilityError::FormatChangeRejected);
435 }
436 self.session_counter = self.session_counter.saturating_add(1);
437 self.segment_counter = self.segment_counter.saturating_add(1);
438 self.pending_boundary = Some(SessionBoundary {
439 session: self.session_counter,
440 segment: self.segment_counter,
441 kind: BoundaryKind::DeviceChanged,
442 format: next.native_format.pcm.clone(),
443 device_id: Some(next.native_format.endpoint.clone()),
444 identity: None,
445 });
446 *stream = Some(Box::new(next));
447 Ok(true)
448 }
449 PlatformExecutionEngine::SoftwareMix {
450 multi,
451 streams,
452 last_active_at,
453 in_bytes_scratch,
454 ..
455 } => {
456 let idx = self
457 .request
458 .targets()
459 .iter()
460 .position(|t| {
461 t.kind() == expected_kind
462 && t.default_device_mode() == DefaultDeviceMode::Follow
463 })
464 .ok_or(CapabilityError::InvalidTarget)?;
465 let old_pcm = streams[idx]
466 .as_ref()
467 .map(|s| s.native_format.pcm.clone())
468 .or_else(|| {
469 multi
470 .input_handles()
471 .get(idx)
472 .map(|h| h.native_format().clone())
473 });
474 if old_pcm
475 .as_ref()
476 .is_some_and(|prev| prev != &next.native_format.pcm)
477 && self.request.on_format_change() == OnFormatChange::Fail
478 {
479 next.stop(Stop::Abort);
480 let _ = next.wait_cleanup(self.cleanup_timeout);
481 self.terminal_error = Some(ManagerError::Unsupported);
482 return Err(CapabilityError::FormatChangeRejected);
483 }
484 if let Some(old) = streams[idx].take() {
485 old.stop(Stop::Drain);
486 let _ = old.wait_cleanup(self.cleanup_timeout);
487 }
488 let stride = next.native_format.pcm.bytes_per_frame();
489 if in_bytes_scratch.len() < MAX_FRAMES_PER_SLOT * stride {
490 in_bytes_scratch.resize(MAX_FRAMES_PER_SLOT * stride, 0);
491 }
492 streams[idx] = Some(next);
493 last_active_at[idx] = Some(Instant::now());
494 let _ = multi.set_input_state(idx, ParticipationState::Active);
495 self.reconcile_software_mix_after_stream_change()?;
496 self.segment_counter = self.segment_counter.saturating_add(1);
497 Ok(true)
498 }
499 }
500 }
501
502 fn reconcile_software_mix_after_stream_change(&mut self) -> Result<(), CapabilityError> {
503 let PlatformExecutionEngine::SoftwareMix { multi, streams, .. } = &mut self.engine else {
504 return Ok(());
505 };
506 let fallback_fmt = multi.working_format().clone();
507 let per_input: Vec<(BackendId, Arc<Format>)> = streams
508 .iter()
509 .enumerate()
510 .map(|(idx, s)| {
511 let fmt = s.as_ref().map_or_else(
512 || {
513 multi
514 .input_handles()
515 .get(idx)
516 .map_or_else(|| fallback_fmt.clone(), |h| h.native_format().clone())
517 },
518 |st| st.native_format.pcm.clone(),
519 );
520 (BackendId::Wasapi, fmt)
521 })
522 .collect();
523
524 match multi.reconfigure_targets_with_formats(self.request.targets().to_vec(), per_input) {
525 Ok(_) => Ok(()),
526 Err(ManagerError::WorkingFormatChanged) => {
527 let PlatformExecutionEngine::SoftwareMix {
529 streams,
530 last_active_at,
531 wait_deadlines,
532 ..
533 } = &mut self.engine
534 else {
535 unreachable!()
536 };
537 let taken_streams = std::mem::take(streams);
538 let taken_active = std::mem::take(last_active_at);
539 let taken_deadlines = std::mem::take(wait_deadlines);
540 self.engine = build_software_mix_engine(
541 self.request.clone(),
542 taken_streams,
543 taken_active,
544 taken_deadlines,
545 self.budget.clone(),
546 self.cleanup_timeout,
547 )?;
548 Ok(())
549 }
550 Err(err) => {
551 self.terminal_error = Some(err);
552 Err(map_manager_error(err))
553 }
554 }
555 }
556
557 fn notify_default_flow_changed(
558 &mut self,
559 expected_kind: TargetKind,
560 new_endpoint: Option<&str>,
561 ) -> Result<bool, CapabilityError> {
562 if self.stopped || self.terminal_error.is_some() {
563 return Err(CapabilityError::Stopped);
564 }
565 let is_input = expected_kind == TargetKind::DefaultInput;
566 let has_follow = self.request.targets().iter().any(|t| {
567 t.kind() == expected_kind && t.default_device_mode() == DefaultDeviceMode::Follow
568 });
569 if !has_follow {
570 return Err(CapabilityError::InvalidTarget);
571 }
572
573 let resolved_id = match new_endpoint {
574 Some(id) => Some(id.to_owned()),
575 None if is_input => query_default_capture_endpoint_id()?,
576 None => query_default_render_endpoint_id()?,
577 };
578
579 match &mut self.engine {
580 PlatformExecutionEngine::PassThrough { stream, .. } => {
581 let target = self
582 .request
583 .targets()
584 .first()
585 .cloned()
586 .ok_or(CapabilityError::InvalidTarget)?;
587 if target.kind() != expected_kind
588 || target.default_device_mode() != DefaultDeviceMode::Follow
589 {
590 return Err(CapabilityError::InvalidTarget);
591 }
592 let old_pcm = stream.as_ref().map(|s| s.native_format.pcm.clone());
593 if let Some(old) = stream.take() {
594 old.stop_checked(Stop::Drain)?;
595 if !old.wait_cleanup(self.cleanup_timeout) {
596 self.terminal_error = Some(ManagerError::CleanupTimeout);
597 return Err(CapabilityError::CleanupTimeout);
598 }
599 }
600 let open_target = match (is_input, resolved_id.as_deref()) {
601 (false, Some(id)) => WasapiOpenTarget::RenderEndpoint(id.into()),
602 (false, None) => WasapiOpenTarget::DefaultRender,
603 (true, Some(id)) => WasapiOpenTarget::CaptureEndpoint(id.into()),
604 (true, None) => WasapiOpenTarget::DefaultCapture,
605 };
606 let next = match PlatformStream::open_reserved_target(
607 open_target,
608 target,
609 self.policy,
610 self.budget.clone(),
611 Duration::from_secs(5),
612 ) {
613 Ok(s) => s,
614 Err((cleanup, err)) => {
615 self.pending_cleanup = cleanup;
616 self.terminal_error = Some(ManagerError::OpenFailed);
617 return Err(err);
618 }
619 };
620 if old_pcm
621 .as_ref()
622 .is_some_and(|prev| prev != &next.native_format.pcm)
623 && self.request.on_format_change() == OnFormatChange::Fail
624 {
625 next.stop(Stop::Abort);
626 let _ = next.wait_cleanup(self.cleanup_timeout);
627 self.terminal_error = Some(ManagerError::Unsupported);
628 return Err(CapabilityError::FormatChangeRejected);
629 }
630 self.session_counter = self.session_counter.saturating_add(1);
631 self.segment_counter = self.segment_counter.saturating_add(1);
632 self.pending_boundary = Some(SessionBoundary {
633 session: self.session_counter,
634 segment: self.segment_counter,
635 kind: BoundaryKind::DeviceChanged,
636 format: next.native_format.pcm.clone(),
637 device_id: Some(next.native_format.endpoint.clone()),
638 identity: None,
639 });
640 *stream = Some(Box::new(next));
641 Ok(true)
642 }
643 PlatformExecutionEngine::SoftwareMix {
644 multi,
645 streams,
646 last_active_at,
647 in_bytes_scratch,
648 ..
649 } => {
650 let mut switched = 0usize;
651 for idx in 0..self.request.targets().len() {
652 let target = &self.request.targets()[idx];
653 if target.kind() != expected_kind
654 || target.default_device_mode() != DefaultDeviceMode::Follow
655 {
656 continue;
657 }
658 if let (Some(new_id), Some(active)) = (resolved_id.as_deref(), &streams[idx])
659 && active.native_format.endpoint.as_ref() == new_id
660 {
661 continue;
662 }
663 let old_pcm = streams[idx]
664 .as_ref()
665 .map(|s| s.native_format.pcm.clone())
666 .or_else(|| {
667 multi
668 .input_handles()
669 .get(idx)
670 .map(|h| h.native_format().clone())
671 });
672 if let Some(old) = streams[idx].take() {
673 old.stop(Stop::Drain);
674 if !old.wait_cleanup(self.cleanup_timeout) {
675 self.terminal_error = Some(ManagerError::CleanupTimeout);
676 return Err(CapabilityError::CleanupTimeout);
677 }
678 }
679 let _ticket = multi.acquire_pending_open().map_err(map_manager_error)?;
680 let open_target = match (is_input, resolved_id.as_deref()) {
681 (false, Some(id)) => WasapiOpenTarget::RenderEndpoint(id.into()),
682 (false, None) => WasapiOpenTarget::DefaultRender,
683 (true, Some(id)) => WasapiOpenTarget::CaptureEndpoint(id.into()),
684 (true, None) => WasapiOpenTarget::DefaultCapture,
685 };
686 let next = match PlatformStream::open_reserved_target(
687 open_target,
688 target.clone(),
689 self.policy,
690 multi.storage_budget().clone(),
691 Duration::from_secs(5),
692 ) {
693 Ok(s) => s,
694 Err((cleanup, err)) => {
695 self.pending_cleanup = cleanup;
696 return Err(err);
697 }
698 };
699 if old_pcm
700 .as_ref()
701 .is_some_and(|prev| prev != &next.native_format.pcm)
702 && self.request.on_format_change() == OnFormatChange::Fail
703 {
704 next.stop(Stop::Abort);
705 let _ = next.wait_cleanup(self.cleanup_timeout);
706 self.terminal_error = Some(ManagerError::Unsupported);
707 return Err(CapabilityError::FormatChangeRejected);
708 }
709 let stride = next.native_format.pcm.bytes_per_frame();
710 if in_bytes_scratch.len() < MAX_FRAMES_PER_SLOT * stride {
711 in_bytes_scratch.resize(MAX_FRAMES_PER_SLOT * stride, 0);
712 }
713 streams[idx] = Some(next);
714 last_active_at[idx] = Some(Instant::now());
715 let _ = multi.set_input_state(idx, ParticipationState::Active);
716 switched += 1;
717 }
718 if switched > 0 {
719 self.reconcile_software_mix_after_stream_change()?;
720 self.segment_counter = self.segment_counter.saturating_add(1);
721 }
722 Ok(switched > 0)
723 }
724 }
725 }
726
727 fn poll_default_device_follow(&mut self) {
728 if self.stopped
729 || self.terminal_error.is_some()
730 || self.pending_boundary.is_some()
731 || self.last_default_check.elapsed() < Duration::from_millis(200)
732 {
733 return;
734 }
735 self.last_default_check = Instant::now();
736
737 if let Some(ref obs) = self.default_observer {
738 let switched_id = match &self.engine {
739 PlatformExecutionEngine::PassThrough { stream, .. } => self
740 .request
741 .targets()
742 .first()
743 .filter(|t| {
744 t.kind() == TargetKind::DefaultOutput
745 && t.default_device_mode() == DefaultDeviceMode::Follow
746 })
747 .and_then(|_| stream.as_ref().map(|s| s.native_format.endpoint.as_ref()))
748 .and_then(|cur| obs.changed_from(Some(cur))),
749 PlatformExecutionEngine::SoftwareMix { streams, .. } => self
750 .request
751 .targets()
752 .iter()
753 .enumerate()
754 .find_map(|(idx, t)| {
755 if t.kind() == TargetKind::DefaultOutput
756 && t.default_device_mode() == DefaultDeviceMode::Follow
757 {
758 streams.get(idx).and_then(Option::as_ref).and_then(|s| {
759 obs.changed_from(Some(s.native_format.endpoint.as_ref()))
760 })
761 } else {
762 None
763 }
764 }),
765 };
766 if let Some(current_out) = switched_id {
767 let _ =
768 self.notify_default_flow_changed(TargetKind::DefaultOutput, Some(¤t_out));
769 }
770 }
771
772 if let Some(ref obs) = self.default_input_observer {
773 let switched_in_id = match &self.engine {
774 PlatformExecutionEngine::PassThrough { stream, .. } => self
775 .request
776 .targets()
777 .first()
778 .filter(|t| {
779 t.kind() == TargetKind::DefaultInput
780 && t.default_device_mode() == DefaultDeviceMode::Follow
781 })
782 .and_then(|_| stream.as_ref().map(|s| s.native_format.endpoint.as_ref()))
783 .and_then(|cur| obs.changed_from(Some(cur))),
784 PlatformExecutionEngine::SoftwareMix { streams, .. } => self
785 .request
786 .targets()
787 .iter()
788 .enumerate()
789 .find_map(|(idx, t)| {
790 if t.kind() == TargetKind::DefaultInput
791 && t.default_device_mode() == DefaultDeviceMode::Follow
792 {
793 streams.get(idx).and_then(Option::as_ref).and_then(|s| {
794 obs.changed_from(Some(s.native_format.endpoint.as_ref()))
795 })
796 } else {
797 None
798 }
799 }),
800 };
801 if let Some(current_in) = switched_in_id {
802 let _ =
803 self.notify_default_flow_changed(TargetKind::DefaultInput, Some(¤t_in));
804 }
805 }
806 }
807
808 fn update_targets_impl(
809 &mut self,
810 mut new_targets: Vec<CaptureTarget>,
811 ) -> Result<u64, CapabilityError> {
812 if self.stopped || self.terminal_error.is_some() {
813 return Err(CapabilityError::Stopped);
814 }
815 let candidate_req = self.request.clone().with_targets(new_targets.clone());
816 let new_plan = resolve_windows_plan(&candidate_req, self.timing)?;
817
818 if let PlatformExecutionEngine::PassThrough {
819 stream,
820 waiting_relaunch,
821 wait_deadline,
822 } = &mut self.engine
823 && new_plan.combine_resolution == CombineResolution::PassThrough(BackendId::Wasapi)
824 {
825 let mut new_target = new_targets.remove(0);
826 let cur_target = &self.request.targets()[0];
827 if cur_target.logical_id() == new_target.logical_id()
828 && cur_target.backend() == new_target.backend()
829 && cur_target.scope() == new_target.scope()
830 && cur_target.default_device_mode() == new_target.default_device_mode()
831 {
832 let updated = cur_target
833 .clone()
834 .with_on_root_exit(new_target.on_root_exit())
835 .map_err(CapabilityError::from)?;
836 self.request = self.request.clone().with_targets(vec![updated]);
837 self.plan = new_plan;
838 return Ok(self.segment_counter);
839 }
840
841 let open_target = WasapiOpenTarget::from_capture_target(&new_target)?;
842 let next = match PlatformStream::open_reserved_target(
843 open_target,
844 new_target.clone(),
845 self.policy,
846 self.budget.clone(),
847 Duration::from_secs(5),
848 ) {
849 Ok(s) => s,
850 Err((cleanup, err)) => {
851 if let Some(c) = cleanup {
852 let _ = c.wait(self.cleanup_timeout);
853 }
854 return Err(err);
855 }
856 };
857 if let Some(old) = stream.take() {
858 old.stop(Stop::Drain);
859 let _ = old.wait_cleanup(self.cleanup_timeout);
860 }
861 resolve_pinned_capture_target(&mut new_target, &next.native_format.endpoint);
862 self.session_counter = self.session_counter.saturating_add(1);
863 self.segment_counter = self.segment_counter.saturating_add(1);
864 self.pending_boundary = Some(SessionBoundary {
865 session: self.session_counter,
866 segment: self.segment_counter,
867 kind: BoundaryKind::ConfigurationChanged,
868 format: next.native_format.pcm.clone(),
869 device_id: Some(next.native_format.endpoint.clone()),
870 identity: new_target.process_identity(),
871 });
872 *stream = Some(Box::new(next));
873 *waiting_relaunch = false;
874 *wait_deadline = None;
875 let next_req = self.request.clone().with_targets(vec![new_target]);
876 self.plan = resolve_windows_plan(&next_req, self.timing).unwrap_or(new_plan);
877 self.request = next_req;
878 self.refresh_default_observers();
879 return Ok(self.segment_counter);
880 }
881
882 if let PlatformExecutionEngine::SoftwareMix {
883 multi,
884 streams,
885 last_active_at,
886 wait_deadlines,
887 in_bytes_scratch,
888 ..
889 } = &mut self.engine
890 && new_plan.combine_resolution == CombineResolution::CspaMixer
891 {
892 let old_targets = self.request.targets();
893 let mut preview_used = vec![false; old_targets.len()];
894 let mut planned_old_slot: Vec<Option<usize>> = Vec::with_capacity(new_targets.len());
895 for target in &new_targets {
896 let mut found = None;
897 for (old_idx, old_target) in old_targets.iter().enumerate() {
898 if !preview_used[old_idx]
899 && old_target.logical_id() == target.logical_id()
900 && old_target.backend() == target.backend()
901 && old_target.scope() == target.scope()
902 && (streams[old_idx].is_some() || wait_deadlines[old_idx].is_some())
903 {
904 preview_used[old_idx] = true;
905 found = Some(old_idx);
906 break;
907 }
908 }
909 planned_old_slot.push(found);
910 }
911
912 let budget = multi.storage_budget().clone();
913 let mut newly_opened: Vec<Option<PlatformStream>> =
914 Vec::with_capacity(new_targets.len());
915 for (new_idx, target) in new_targets.iter_mut().enumerate() {
916 if planned_old_slot[new_idx].is_some() {
917 newly_opened.push(None);
918 continue;
919 }
920 let _open_ticket = multi.acquire_pending_open().map_err(map_manager_error)?;
921 let open_target = match WasapiOpenTarget::from_capture_target(target) {
922 Ok(ot) => ot,
923 Err(err) => {
924 for opened in newly_opened.into_iter().flatten() {
925 opened.stop(Stop::Abort);
926 let _ = opened.wait_cleanup(self.cleanup_timeout);
927 }
928 return Err(err);
929 }
930 };
931 match PlatformStream::open_reserved_target(
932 open_target,
933 target.clone(),
934 self.policy,
935 budget.clone(),
936 Duration::from_secs(5),
937 ) {
938 Ok(s) => {
939 resolve_pinned_capture_target(target, &s.native_format.endpoint);
940 newly_opened.push(Some(s));
941 }
942 Err((cleanup, err)) => {
943 if let Some(c) = cleanup {
944 let _ = c.wait(self.cleanup_timeout);
945 }
946 for opened in newly_opened.into_iter().flatten() {
947 opened.stop(Stop::Abort);
948 let _ = opened.wait_cleanup(self.cleanup_timeout);
949 }
950 return Err(err);
951 }
952 }
953 }
954
955 let fallback_fmt = multi.working_format().clone();
956 let per_input: Vec<(BackendId, Arc<Format>)> = (0..new_targets.len())
957 .map(|new_idx| {
958 let fmt = if let Some(old_idx) = planned_old_slot[new_idx] {
959 streams
960 .get(old_idx)
961 .and_then(Option::as_ref)
962 .map(|s| s.native_format.pcm.clone())
963 .or_else(|| {
964 multi
965 .input_handles()
966 .get(old_idx)
967 .map(|h| h.native_format().clone())
968 })
969 .unwrap_or_else(|| fallback_fmt.clone())
970 } else {
971 newly_opened[new_idx]
972 .as_ref()
973 .map_or_else(|| fallback_fmt.clone(), |s| s.native_format.pcm.clone())
974 };
975 (BackendId::Wasapi, fmt)
976 })
977 .collect();
978
979 match multi.reconfigure_targets_with_formats(new_targets.clone(), per_input) {
980 Ok(mapping) => {
981 let mut next_streams = Vec::with_capacity(new_targets.len());
982 let mut next_last_active = Vec::with_capacity(new_targets.len());
983 let mut next_wait_deadlines = Vec::with_capacity(new_targets.len());
984
985 for (new_idx, mapped_old) in mapping.iter().enumerate() {
986 if let Some(old_idx) = *mapped_old {
987 let retained_stream = streams
988 .get_mut(old_idx)
989 .and_then(Option::take)
990 .or_else(|| newly_opened[new_idx].take());
991 let retained_active = last_active_at
992 .get_mut(old_idx)
993 .and_then(Option::take)
994 .or_else(|| Some(Instant::now()));
995 let retained_deadline =
996 wait_deadlines.get_mut(old_idx).and_then(Option::take);
997 if retained_stream.is_some() {
998 let _ = multi.set_input_state(new_idx, ParticipationState::Active);
999 }
1000 next_streams.push(retained_stream);
1001 next_last_active.push(retained_active);
1002 next_wait_deadlines.push(retained_deadline);
1003 } else {
1004 let opened = newly_opened[new_idx].take();
1005 if opened.is_some() {
1006 let _ = multi.set_input_state(new_idx, ParticipationState::Active);
1007 }
1008 next_streams.push(opened);
1009 next_last_active.push(Some(Instant::now()));
1010 next_wait_deadlines.push(None);
1011 }
1012 }
1013
1014 for retired in streams
1015 .drain(..)
1016 .flatten()
1017 .chain(newly_opened.into_iter().flatten())
1018 {
1019 retired.stop(Stop::Drain);
1020 let _ = retired.wait_cleanup(self.cleanup_timeout);
1021 }
1022
1023 let max_stride = next_streams
1024 .iter()
1025 .flatten()
1026 .map(|s| s.native_format.pcm.bytes_per_frame())
1027 .max()
1028 .unwrap_or(8)
1029 .max(8);
1030 if in_bytes_scratch.len() < MAX_FRAMES_PER_SLOT * max_stride {
1031 in_bytes_scratch.resize(MAX_FRAMES_PER_SLOT * max_stride, 0);
1032 }
1033
1034 *streams = next_streams;
1035 *last_active_at = next_last_active;
1036 *wait_deadlines = next_wait_deadlines;
1037 }
1038 Err(ManagerError::WorkingFormatChanged) => {
1039 let mut next_streams = Vec::with_capacity(new_targets.len());
1040 let mut next_last_active = Vec::with_capacity(new_targets.len());
1041 let mut next_wait_deadlines = Vec::with_capacity(new_targets.len());
1042 for new_idx in 0..new_targets.len() {
1043 if let Some(old_idx) = planned_old_slot[new_idx] {
1044 next_streams.push(streams[old_idx].take());
1045 next_last_active.push(
1046 last_active_at[old_idx]
1047 .take()
1048 .or_else(|| Some(Instant::now())),
1049 );
1050 next_wait_deadlines.push(wait_deadlines[old_idx].take());
1051 } else {
1052 next_streams.push(newly_opened[new_idx].take());
1053 next_last_active.push(Some(Instant::now()));
1054 next_wait_deadlines.push(None);
1055 }
1056 }
1057 for retired in streams
1058 .drain(..)
1059 .flatten()
1060 .chain(newly_opened.into_iter().flatten())
1061 {
1062 retired.stop(Stop::Drain);
1063 let _ = retired.wait_cleanup(self.cleanup_timeout);
1064 }
1065 let rebuilt_req = self.request.clone().with_targets(new_targets.clone());
1066 self.engine = build_software_mix_engine(
1067 rebuilt_req,
1068 next_streams,
1069 next_last_active,
1070 next_wait_deadlines,
1071 self.budget.clone(),
1072 self.cleanup_timeout,
1073 )?;
1074 self.session_counter = self.session_counter.saturating_add(1);
1075 }
1076 Err(err) => {
1077 for opened in newly_opened.into_iter().flatten() {
1078 opened.stop(Stop::Abort);
1079 let _ = opened.wait_cleanup(self.cleanup_timeout);
1080 }
1081 return Err(map_manager_error(err));
1082 }
1083 }
1084
1085 let next_req = self.request.clone().with_targets(new_targets);
1086 self.plan = resolve_windows_plan(&next_req, self.timing).unwrap_or(new_plan);
1087 self.request = next_req;
1088 self.refresh_default_observers();
1089 self.segment_counter = self.segment_counter.saturating_add(1);
1090 return Ok(self.segment_counter);
1091 }
1092
1093 match new_plan.combine_resolution {
1095 CombineResolution::CspaMixer => {
1096 let PlatformExecutionEngine::PassThrough {
1097 stream: old_pt_stream,
1098 waiting_relaunch,
1099 wait_deadline,
1100 } = &mut self.engine
1101 else {
1102 return Err(CapabilityError::NotImplemented);
1103 };
1104 let old_t = &self.request.targets()[0];
1105 let reusable_new_idx = new_targets.iter().position(|nt| {
1106 old_t.logical_id() == nt.logical_id()
1107 && old_t.backend() == nt.backend()
1108 && old_t.scope() == nt.scope()
1109 && (old_pt_stream.is_some() || *waiting_relaunch)
1110 });
1111
1112 let mut newly_opened: Vec<Option<PlatformStream>> =
1113 Vec::with_capacity(new_targets.len());
1114 for (idx, nt) in new_targets.iter_mut().enumerate() {
1115 if Some(idx) == reusable_new_idx {
1116 if let Some(s) = old_pt_stream.as_ref() {
1117 resolve_pinned_capture_target(nt, &s.native_format.endpoint);
1118 }
1119 newly_opened.push(None);
1120 continue;
1121 }
1122 let open_target = match WasapiOpenTarget::from_capture_target(nt) {
1123 Ok(ot) => ot,
1124 Err(err) => {
1125 for s in newly_opened.into_iter().flatten() {
1126 s.stop(Stop::Abort);
1127 let _ = s.wait_cleanup(self.cleanup_timeout);
1128 }
1129 return Err(err);
1130 }
1131 };
1132 match PlatformStream::open_reserved_target(
1133 open_target,
1134 nt.clone(),
1135 self.policy,
1136 self.budget.clone(),
1137 Duration::from_secs(5),
1138 ) {
1139 Ok(s) => {
1140 resolve_pinned_capture_target(nt, &s.native_format.endpoint);
1141 newly_opened.push(Some(s));
1142 }
1143 Err((cleanup, err)) => {
1144 if let Some(c) = cleanup {
1145 let _ = c.wait(self.cleanup_timeout);
1146 }
1147 for s in newly_opened.into_iter().flatten() {
1148 s.stop(Stop::Abort);
1149 let _ = s.wait_cleanup(self.cleanup_timeout);
1150 }
1151 return Err(err);
1152 }
1153 }
1154 }
1155
1156 let fallback_fmt = fallback_working_format()?;
1157 let preview_formats: Vec<Format> = (0..new_targets.len())
1158 .map(|idx| {
1159 if Some(idx) == reusable_new_idx {
1160 old_pt_stream.as_ref().map_or_else(
1161 || (*fallback_fmt).clone(),
1162 |s| (*s.native_format.pcm).clone(),
1163 )
1164 } else {
1165 newly_opened[idx].as_ref().map_or_else(
1166 || (*fallback_fmt).clone(),
1167 |s| (*s.native_format.pcm).clone(),
1168 )
1169 }
1170 })
1171 .collect();
1172 if crate::core::converter::resolve_mixer_working_format(
1173 &preview_formats,
1174 self.request.output_converter(),
1175 self.request.input_conversion(),
1176 )
1177 .is_err()
1178 {
1179 for s in newly_opened.into_iter().flatten() {
1180 s.stop(Stop::Abort);
1181 let _ = s.wait_cleanup(self.cleanup_timeout);
1182 }
1183 return Err(CapabilityError::UnsupportedFormat);
1184 }
1185
1186 let mut next_streams = Vec::with_capacity(new_targets.len());
1187 let mut next_active = Vec::with_capacity(new_targets.len());
1188 let mut next_deadlines = Vec::with_capacity(new_targets.len());
1189 for (idx, opened_slot) in
1190 newly_opened.iter_mut().enumerate().take(new_targets.len())
1191 {
1192 if Some(idx) == reusable_new_idx {
1193 next_streams.push(old_pt_stream.take().map(|b| *b));
1194 next_active.push(Some(Instant::now()));
1195 next_deadlines.push(if *waiting_relaunch {
1196 *wait_deadline
1197 } else {
1198 None
1199 });
1200 } else {
1201 next_streams.push(opened_slot.take());
1202 next_active.push(Some(Instant::now()));
1203 next_deadlines.push(None);
1204 }
1205 }
1206 if let Some(retired) = old_pt_stream.take() {
1207 retired.stop(Stop::Drain);
1208 let _ = retired.wait_cleanup(self.cleanup_timeout);
1209 }
1210
1211 let next_req = self.request.clone().with_targets(new_targets);
1212 self.engine = build_software_mix_engine(
1213 next_req.clone(),
1214 next_streams,
1215 next_active,
1216 next_deadlines,
1217 self.budget.clone(),
1218 self.cleanup_timeout,
1219 )?;
1220 self.plan = resolve_windows_plan(&next_req, self.timing).unwrap_or(new_plan);
1221 self.request = next_req;
1222 self.pending_boundary = None;
1223 self.refresh_default_observers();
1224 self.session_counter = self.session_counter.saturating_add(1);
1225 self.segment_counter = self.segment_counter.saturating_add(1);
1226 Ok(self.segment_counter)
1227 }
1228 CombineResolution::PassThrough(BackendId::Wasapi) => {
1229 let PlatformExecutionEngine::SoftwareMix {
1230 multi,
1231 streams,
1232 wait_deadlines,
1233 ..
1234 } = &mut self.engine
1235 else {
1236 return Err(CapabilityError::NotImplemented);
1237 };
1238 let mut new_target = new_targets.remove(0);
1239 let old_targets = self.request.targets();
1240 let reusable_old_idx = old_targets.iter().enumerate().find_map(|(idx, ot)| {
1241 (ot.logical_id() == new_target.logical_id()
1242 && ot.backend() == new_target.backend()
1243 && ot.scope() == new_target.scope()
1244 && (streams[idx].is_some() || wait_deadlines[idx].is_some()))
1245 .then_some(idx)
1246 });
1247
1248 let (pt_stream, pt_waiting, pt_deadline) = if let Some(old_idx) = reusable_old_idx {
1249 let s = streams[old_idx].take();
1250 if let Some(ref st) = s {
1251 resolve_pinned_capture_target(&mut new_target, &st.native_format.endpoint);
1252 }
1253 let dl = wait_deadlines[old_idx].take();
1254 (s, dl.is_some(), dl)
1255 } else {
1256 let open_target = WasapiOpenTarget::from_capture_target(&new_target)?;
1257 let s = match PlatformStream::open_reserved_target(
1258 open_target,
1259 new_target.clone(),
1260 self.policy,
1261 self.budget.clone(),
1262 Duration::from_secs(5),
1263 ) {
1264 Ok(st) => st,
1265 Err((cleanup, err)) => {
1266 if let Some(c) = cleanup {
1267 let _ = c.wait(self.cleanup_timeout);
1268 }
1269 return Err(err);
1270 }
1271 };
1272 resolve_pinned_capture_target(&mut new_target, &s.native_format.endpoint);
1273 (Some(s), false, None)
1274 };
1275
1276 multi.clear_pending_output();
1277 for retired in streams.drain(..).flatten() {
1278 retired.stop(Stop::Drain);
1279 let _ = retired.wait_cleanup(self.cleanup_timeout);
1280 }
1281
1282 self.session_counter = self.session_counter.saturating_add(1);
1283 self.segment_counter = self.segment_counter.saturating_add(1);
1284 if let Some(ref st) = pt_stream {
1285 self.pending_boundary = Some(SessionBoundary {
1286 session: self.session_counter,
1287 segment: self.segment_counter,
1288 kind: BoundaryKind::ConfigurationChanged,
1289 format: st.native_format.pcm.clone(),
1290 device_id: Some(st.native_format.endpoint.clone()),
1291 identity: new_target.process_identity(),
1292 });
1293 }
1294 self.engine = PlatformExecutionEngine::PassThrough {
1295 stream: pt_stream.map(Box::new),
1296 waiting_relaunch: pt_waiting,
1297 wait_deadline: pt_deadline,
1298 };
1299 let next_req = self.request.clone().with_targets(vec![new_target]);
1300 self.plan = resolve_windows_plan(&next_req, self.timing).unwrap_or(new_plan);
1301 self.request = next_req;
1302 self.refresh_default_observers();
1303 Ok(self.segment_counter)
1304 }
1305 _ => Err(CapabilityError::InvalidBackend),
1306 }
1307 }
1308
1309 fn reopen_relaunched_target_impl(
1310 &mut self,
1311 target_index: usize,
1312 candidate_pid: u32,
1313 ) -> Result<(), CapabilityError> {
1314 if self.stopped || self.terminal_error.is_some() {
1315 return Err(CapabilityError::Stopped);
1316 }
1317 let target = self
1318 .request
1319 .targets()
1320 .get(target_index)
1321 .cloned()
1322 .ok_or(CapabilityError::InvalidTarget)?;
1323 let OnRootExit::Wait { wait_timeout_ns } = target.on_root_exit() else {
1324 return Err(CapabilityError::InvalidTarget);
1325 };
1326 let old_id = target
1327 .process_identity()
1328 .ok_or(CapabilityError::InvalidTarget)?;
1329 if target.scope() == ProcessScope::Exact {
1330 return Err(CapabilityError::UnsupportedScope);
1331 }
1332
1333 match &mut self.engine {
1334 PlatformExecutionEngine::PassThrough {
1335 stream,
1336 waiting_relaunch,
1337 wait_deadline,
1338 } => {
1339 if target_index != 0 {
1340 return Err(CapabilityError::InvalidTarget);
1341 }
1342 let deadline = wait_deadline
1343 .unwrap_or_else(|| Instant::now() + Duration::from_nanos(wait_timeout_ns));
1344 if Instant::now() >= deadline {
1345 self.terminal_error = Some(ManagerError::Deadline);
1346 return Err(CapabilityError::CleanupTimeout);
1347 }
1348 let (cand_id, cand_exe) = inspect_process_executable(candidate_pid)?;
1349 if cand_id == old_id || cand_id.generation <= old_id.generation {
1350 self.terminal_error = Some(ManagerError::InvalidObservation);
1351 return Err(CapabilityError::PidReused);
1352 }
1353 if let Some(expected_exe) = target.executable_path()
1354 && !expected_exe.eq_ignore_ascii_case(&cand_exe)
1355 {
1356 self.terminal_error = Some(ManagerError::InvalidObservation);
1357 return Err(CapabilityError::InvalidTarget);
1358 }
1359 if let Some(old) = stream.take() {
1360 old.stop_checked(Stop::Drain)?;
1361 if !old.wait_cleanup(self.cleanup_timeout) {
1362 self.terminal_error = Some(ManagerError::CleanupTimeout);
1363 return Err(CapabilityError::CleanupTimeout);
1364 }
1365 }
1366 let updated_target = target
1367 .with_process_identity(cand_id)
1368 .map_err(CapabilityError::from)?;
1369 let next = match PlatformStream::open_reserved_target(
1370 WasapiOpenTarget::ProcessTree(cand_id),
1371 updated_target.clone(),
1372 self.policy,
1373 self.budget.clone(),
1374 Duration::from_secs(5),
1375 ) {
1376 Ok(s) => s,
1377 Err((cleanup, err)) => {
1378 self.pending_cleanup = cleanup;
1379 self.terminal_error = Some(ManagerError::OpenFailed);
1380 return Err(err);
1381 }
1382 };
1383 self.session_counter = self.session_counter.saturating_add(1);
1384 self.segment_counter = self.segment_counter.saturating_add(1);
1385 *waiting_relaunch = false;
1386 *wait_deadline = None;
1387 self.pending_boundary = Some(SessionBoundary {
1388 session: self.session_counter,
1389 segment: self.segment_counter,
1390 kind: BoundaryKind::ConfigurationChanged,
1391 format: next.native_format.pcm.clone(),
1392 device_id: Some(next.native_format.endpoint.clone()),
1393 identity: Some(cand_id),
1394 });
1395 *stream = Some(Box::new(next));
1396 self.request = self.request.clone().with_targets(vec![updated_target]);
1397 Ok(())
1398 }
1399 PlatformExecutionEngine::SoftwareMix {
1400 multi,
1401 streams,
1402 last_active_at,
1403 wait_deadlines,
1404 ..
1405 } => {
1406 let deadline = wait_deadlines[target_index]
1407 .unwrap_or_else(|| Instant::now() + Duration::from_nanos(wait_timeout_ns));
1408 if Instant::now() >= deadline {
1409 let _ = multi.set_input_state(target_index, ParticipationState::Failed(9));
1410 return Err(CapabilityError::CleanupTimeout);
1411 }
1412 let (cand_id, cand_exe) = inspect_process_executable(candidate_pid)?;
1413 if cand_id == old_id || cand_id.generation <= old_id.generation {
1414 return Err(CapabilityError::PidReused);
1415 }
1416 if let Some(expected_exe) = target.executable_path()
1417 && !expected_exe.eq_ignore_ascii_case(&cand_exe)
1418 {
1419 return Err(CapabilityError::InvalidTarget);
1420 }
1421 if let Some(old) = streams[target_index].take() {
1422 old.stop(Stop::Drain);
1423 let _ = old.wait_cleanup(self.cleanup_timeout);
1424 }
1425 let _ticket = multi.acquire_pending_open().map_err(map_manager_error)?;
1426 let updated_target = target
1427 .with_process_identity(cand_id)
1428 .map_err(CapabilityError::from)?;
1429 let next = match PlatformStream::open_reserved_target(
1430 WasapiOpenTarget::ProcessTree(cand_id),
1431 updated_target.clone(),
1432 self.policy,
1433 multi.storage_budget().clone(),
1434 Duration::from_secs(5),
1435 ) {
1436 Ok(s) => s,
1437 Err((cleanup, err)) => {
1438 self.pending_cleanup = cleanup;
1439 return Err(err);
1440 }
1441 };
1442 let mut next_targets = self.request.targets().to_vec();
1443 next_targets[target_index] = updated_target;
1444 self.request = self.request.clone().with_targets(next_targets);
1445 streams[target_index] = Some(next);
1446 last_active_at[target_index] = Some(Instant::now());
1447 wait_deadlines[target_index] = None;
1448 let _ = multi.set_input_state(target_index, ParticipationState::Active);
1449 self.segment_counter = self.segment_counter.saturating_add(1);
1450 Ok(())
1451 }
1452 }
1453 }
1454
1455 fn drain_software_mix_inputs(&mut self, timeout: Duration, cancel: &Cancellation) -> u64 {
1456 let targets_ref = &self.request;
1457 let cleanup_timeout = self.cleanup_timeout;
1458 let PlatformExecutionEngine::SoftwareMix {
1459 block_frames,
1460 multi,
1461 streams,
1462 last_active_at,
1463 wait_deadlines,
1464 started_at,
1465 in_bytes_scratch,
1466 } = &mut self.engine
1467 else {
1468 return 0;
1469 };
1470
1471 let working_rate = u64::from(multi.working_format().rate().max(1));
1472 let mix_quantum = *block_frames;
1473 let call_started = Instant::now();
1474
1475 loop {
1476 let any_recently_active = last_active_at
1477 .iter()
1478 .any(|t| t.is_some_and(|inst| inst.elapsed() < Duration::from_millis(80)));
1479 let mut waited_on_idle_leader = false;
1480 let mut pushed_any = false;
1481
1482 for idx in 0..streams.len() {
1483 if let Some(deadline) = wait_deadlines[idx]
1484 && Instant::now() >= deadline
1485 {
1486 wait_deadlines[idx] = None;
1487 let _ = multi.set_input_state(idx, ParticipationState::Failed(9));
1488 }
1489 let already_queued = multi
1490 .input_handles()
1491 .get(idx)
1492 .and_then(|h| h.snapshot())
1493 .map_or(0, |s| s.queued_packets);
1494 if already_queued > 0 {
1495 pushed_any = true;
1496 continue;
1497 }
1498
1499 let mut target_exited = false;
1500 let mut target_failed = false;
1501 if let Some(stream) = &mut streams[idx] {
1502 let bpf = stream.native_format.pcm.bytes_per_frame();
1503 let stream_rate = u64::from(stream.native_format.pcm.rate().max(1));
1504 let is_resampled = stream_rate != working_rate;
1505 let in_quantum = ((stream_rate * mix_quantum as u64).div_ceil(working_rate)
1506 as usize)
1507 .clamp(1, MAX_FRAMES_PER_SLOT);
1508 let dst_bytes = in_quantum * bpf;
1509 if in_bytes_scratch.len() < dst_bytes {
1510 in_bytes_scratch.resize(dst_bytes, 0);
1511 }
1512 let max_passes = if is_resampled { 3 } else { 2 };
1513
1514 for pass in 0..max_passes {
1515 let is_this_active = last_active_at[idx]
1516 .is_some_and(|inst| inst.elapsed() < Duration::from_millis(80));
1517 let stream_timeout = if pass > 0 {
1518 timeout.min(Duration::from_millis(12))
1519 } else if is_this_active {
1520 timeout.min(Duration::from_millis(20))
1521 } else if !any_recently_active && !pushed_any && !waited_on_idle_leader {
1522 waited_on_idle_leader = true;
1523 timeout.min(Duration::from_millis(10))
1524 } else {
1525 Duration::ZERO
1526 };
1527
1528 match stream.read_into_with_cancel(
1529 &mut in_bytes_scratch[..dst_bytes],
1530 in_quantum,
1531 stream_timeout,
1532 cancel.clone(),
1533 ) {
1534 Ok(res) if res.frames > 0 => {
1535 last_active_at[idx] = Some(Instant::now());
1536 let now_ns = started_at.elapsed().as_nanos() as u64;
1537 let stamp = res.first_packet.and_then(|a| a.header.timestamp);
1538 if multi
1539 .push_raw_input_bytes(
1540 idx,
1541 &in_bytes_scratch[..res.frames * bpf],
1542 stamp,
1543 now_ns,
1544 )
1545 .is_err()
1546 {
1547 target_failed = true;
1548 break;
1549 }
1550 if res.reason == PartialReason::Eof {
1551 target_exited = true;
1552 break;
1553 }
1554 let now_queued = multi
1555 .input_handles()
1556 .get(idx)
1557 .and_then(|h| h.snapshot())
1558 .map_or(0, |s| s.queued_packets);
1559 if now_queued > 0 {
1560 pushed_any = true;
1561 break;
1562 }
1563 }
1564 Ok(res) if res.reason == PartialReason::Boundary => continue,
1565 Ok(res) if res.reason == PartialReason::Eof => {
1566 target_exited = true;
1567 break;
1568 }
1569 Ok(res) if matches!(res.reason, PartialReason::Failure(_)) => {
1570 target_failed = true;
1571 break;
1572 }
1573 Ok(_) => {
1574 if pass == 0
1575 && last_active_at[idx].is_none_or(|inst| {
1576 inst.elapsed() >= Duration::from_millis(500)
1577 })
1578 {
1579 let _ = multi.set_input_state(idx, ParticipationState::Idle);
1580 }
1581 break;
1582 }
1583 Err(_) => {
1584 target_failed = true;
1585 break;
1586 }
1587 }
1588 }
1589 }
1590
1591 if target_exited {
1592 if let Some(old) = streams[idx].take() {
1593 old.stop(Stop::Drain);
1594 let _ = old.wait_cleanup(cleanup_timeout);
1595 }
1596 match targets_ref.targets()[idx].on_root_exit() {
1597 OnRootExit::Stop => {
1598 let _ = multi.set_input_state(idx, ParticipationState::Exited);
1599 }
1600 OnRootExit::Wait { wait_timeout_ns } => {
1601 wait_deadlines[idx] =
1602 Some(Instant::now() + Duration::from_nanos(wait_timeout_ns));
1603 let _ = multi.set_input_state(idx, ParticipationState::WaitingRelaunch);
1604 }
1605 }
1606 } else if target_failed {
1607 if let Some(old) = streams[idx].take() {
1608 old.stop(Stop::Abort);
1609 }
1610 let _ = multi.set_input_state(idx, ParticipationState::Failed(13));
1611 }
1612 }
1613
1614 if pushed_any
1615 || targets_ref.mixer_config().silence_on_idle
1616 || timeout.is_zero()
1617 || call_started.elapsed() >= timeout
1618 || cancel.is_cancelled()
1619 {
1620 break;
1621 }
1622 thread::park_timeout(
1623 Duration::from_millis(5).min(timeout.saturating_sub(call_started.elapsed())),
1624 );
1625 }
1626
1627 started_at.elapsed().as_nanos() as u64
1628 }
1629}
1630
1631impl CaptureManagerBackend for PlatformManager {
1632 fn open_with_options(
1633 request: CaptureRequest,
1634 overflow: Overflow,
1635 timing: TimingRequirement,
1636 ) -> Result<Self, CapabilityError> {
1637 Self::open_impl(request, overflow, timing)
1638 }
1639
1640 #[inline]
1641 fn plan(&self) -> &CapturePlanReport {
1642 &self.plan
1643 }
1644
1645 #[inline]
1646 fn selected_backend(&self) -> BackendId {
1647 BackendId::Wasapi
1648 }
1649
1650 #[inline]
1651 fn is_software_mix(&self) -> bool {
1652 matches!(self.engine, PlatformExecutionEngine::SoftwareMix { .. })
1653 }
1654
1655 fn working_format(&self) -> Option<&Arc<Format>> {
1656 match &self.engine {
1657 PlatformExecutionEngine::PassThrough { stream, .. } => {
1658 stream.as_deref().map(AudioStreamBackend::format)
1659 }
1660 PlatformExecutionEngine::SoftwareMix { multi, .. } => Some(multi.working_format()),
1661 }
1662 }
1663
1664 fn output_format(&self) -> Option<&Arc<Format>> {
1665 match &self.engine {
1666 PlatformExecutionEngine::PassThrough { stream, .. } => {
1667 stream.as_deref().map(AudioStreamBackend::format)
1668 }
1669 PlatformExecutionEngine::SoftwareMix { multi, .. } => Some(multi.output_format()),
1670 }
1671 }
1672
1673 #[inline]
1674 fn targets(&self) -> &[CaptureTarget] {
1675 self.request.targets()
1676 }
1677
1678 fn input_handles(&self) -> &[InputStatusHandle] {
1679 match &self.engine {
1680 PlatformExecutionEngine::SoftwareMix { multi, .. } => multi.input_handles(),
1681 PlatformExecutionEngine::PassThrough { .. } => &[],
1682 }
1683 }
1684
1685 fn membership_descriptor(&self) -> Option<MembershipDescriptor> {
1686 match &self.engine {
1687 PlatformExecutionEngine::SoftwareMix { multi, .. } => {
1688 Some(multi.membership_descriptor())
1689 }
1690 PlatformExecutionEngine::PassThrough { .. } => None,
1691 }
1692 }
1693
1694 #[inline]
1695 fn last_block_metadata(&self) -> Option<MixedBlockMetadata> {
1696 self.last_metadata
1697 }
1698
1699 #[inline]
1700 fn session_id(&self) -> u64 {
1701 self.session_counter
1702 }
1703
1704 #[inline]
1705 fn segment_id(&self) -> u64 {
1706 self.segment_counter
1707 }
1708
1709 #[inline]
1710 fn on_format_change(&self) -> OnFormatChange {
1711 self.request.on_format_change()
1712 }
1713
1714 #[inline]
1715 fn route_guard(&self) -> Option<&RouteRollbackGuard> {
1716 Some(&self.route_guard)
1717 }
1718
1719 fn update_targets(&mut self, new_targets: Vec<CaptureTarget>) -> Result<u64, CapabilityError> {
1720 self.update_targets_impl(new_targets)
1721 }
1722
1723 fn notify_default_device_changed(
1724 &mut self,
1725 new_device_id: Option<&str>,
1726 ) -> Result<bool, CapabilityError> {
1727 self.notify_default_flow_changed(TargetKind::DefaultOutput, new_device_id)
1728 }
1729
1730 fn notify_default_input_changed(
1731 &mut self,
1732 new_device_id: Option<&str>,
1733 ) -> Result<bool, CapabilityError> {
1734 self.notify_default_flow_changed(TargetKind::DefaultInput, new_device_id)
1735 }
1736
1737 fn reopen_relaunched_target(
1738 &mut self,
1739 target_index: usize,
1740 new_pid: u32,
1741 ) -> Result<(), CapabilityError> {
1742 self.reopen_relaunched_target_impl(target_index, new_pid)
1743 }
1744
1745 #[inline]
1746 fn default_cancel(&self) -> Cancellation {
1747 self.default_cancel.clone()
1748 }
1749
1750 fn read_with_cancel(
1751 &mut self,
1752 frames: usize,
1753 timeout: Duration,
1754 cancel: Cancellation,
1755 ) -> Result<ReadResult, ReadError> {
1756 if frames == 0 {
1757 return Err(ReadError::InvalidRequest);
1758 }
1759 self.poll_default_device_follow();
1760 let _guard = self.read_lock.try_lock().map_err(|err| match err {
1761 TryLockError::WouldBlock => ReadError::AlreadyPending,
1762 TryLockError::Poisoned(_) => ReadError::Poisoned,
1763 })?;
1764
1765 if let Some(boundary) = self.pending_boundary.take() {
1766 return Ok(ReadResult {
1767 frames: 0,
1768 chunks: Vec::new(),
1769 first_packet: None,
1770 last_packet: None,
1771 reason: PartialReason::Boundary,
1772 control: Some(ordering::Control {
1773 sequence: 0,
1774 generation: boundary.session,
1775 segment: boundary.segment,
1776 format: boundary.format,
1777 kind: ordering::ControlKind::Recovered,
1778 losses: ordering::Losses::default(),
1779 records: 1,
1780 }),
1781 copies: Default::default(),
1782 });
1783 }
1784
1785 if self.stopped {
1786 return Ok(ReadResult {
1787 frames: 0,
1788 chunks: Vec::new(),
1789 first_packet: None,
1790 last_packet: None,
1791 reason: PartialReason::Eof,
1792 control: None,
1793 copies: Default::default(),
1794 });
1795 }
1796 if self.terminal_error.is_some() {
1797 return Ok(ReadResult {
1798 frames: 0,
1799 chunks: Vec::new(),
1800 first_packet: None,
1801 last_packet: None,
1802 reason: PartialReason::Failure(Failure::Backend),
1803 control: None,
1804 copies: Default::default(),
1805 });
1806 }
1807 if cancel.is_cancelled() {
1808 return Ok(ReadResult {
1809 frames: 0,
1810 chunks: Vec::new(),
1811 first_packet: None,
1812 last_packet: None,
1813 reason: PartialReason::Cancelled,
1814 control: None,
1815 copies: Default::default(),
1816 });
1817 }
1818 drop(_guard);
1819
1820 match &mut self.engine {
1821 PlatformExecutionEngine::PassThrough {
1822 stream,
1823 waiting_relaunch,
1824 wait_deadline,
1825 } => {
1826 let Some(active) = stream.as_mut() else {
1827 return Ok(ReadResult {
1828 frames: 0,
1829 chunks: Vec::new(),
1830 first_packet: None,
1831 last_packet: None,
1832 reason: PartialReason::Eof,
1833 control: None,
1834 copies: Default::default(),
1835 });
1836 };
1837 let res = active.read_with_cancel(frames, timeout, cancel)?;
1838 if res.reason == PartialReason::Eof
1839 && active.end_reason() == Some(EndReason::TargetExited)
1840 && let Some(t) = self.request.targets().first()
1841 && let OnRootExit::Wait { wait_timeout_ns } = t.on_root_exit()
1842 && !*waiting_relaunch
1843 {
1844 *waiting_relaunch = true;
1845 *wait_deadline = Some(Instant::now() + Duration::from_nanos(wait_timeout_ns));
1846 }
1847 if res.frames > 0 {
1848 self.last_metadata = Some(MixedBlockMetadata {
1849 membership_version: self.segment_counter,
1850 contributing_mask: 1,
1851 late_inputs: 0,
1852 failed_inputs: 0,
1853 nonfinite_inputs: 0,
1854 synthesized_silence: false,
1855 clipped_samples: 0,
1856 nonfinite_samples: 0,
1857 drift_slips: 0,
1858 skew_estimate_ns: Some(0),
1859 skew_uncertainty_ns: Some(0),
1860 });
1861 }
1862 Ok(res)
1863 }
1864 PlatformExecutionEngine::SoftwareMix { multi, .. } => {
1865 if let Some((res, meta)) = multi.try_pop_pending_owned(frames)? {
1866 self.last_metadata = Some(meta);
1867 return Ok(res);
1868 }
1869 let now_ns = self.drain_software_mix_inputs(timeout, &cancel);
1870 if cancel.is_cancelled() {
1871 return Ok(ReadResult {
1872 frames: 0,
1873 chunks: Vec::new(),
1874 first_packet: None,
1875 last_packet: None,
1876 reason: PartialReason::Cancelled,
1877 control: None,
1878 copies: Default::default(),
1879 });
1880 }
1881 let align_ns = self.request.mixer_config().alignment_window_ns;
1882 let PlatformExecutionEngine::SoftwareMix { multi, .. } = &self.engine else {
1883 unreachable!()
1884 };
1885 let (res, meta) = multi.read_mixed_owned(frames, now_ns, align_ns)?;
1886 self.last_metadata = Some(meta);
1887 Ok(res)
1888 }
1889 }
1890 }
1891
1892 fn read_into_with_cancel(
1893 &mut self,
1894 destination: &mut [u8],
1895 frames: usize,
1896 timeout: Duration,
1897 cancel: Cancellation,
1898 ) -> Result<ReadResult, ReadError> {
1899 if frames == 0 {
1900 return Err(ReadError::InvalidRequest);
1901 }
1902 self.poll_default_device_follow();
1903 let _guard = self.read_lock.try_lock().map_err(|err| match err {
1904 TryLockError::WouldBlock => ReadError::AlreadyPending,
1905 TryLockError::Poisoned(_) => ReadError::Poisoned,
1906 })?;
1907
1908 if let Some(boundary) = self.pending_boundary.take() {
1909 return Ok(ReadResult {
1910 frames: 0,
1911 chunks: Vec::new(),
1912 first_packet: None,
1913 last_packet: None,
1914 reason: PartialReason::Boundary,
1915 control: Some(ordering::Control {
1916 sequence: 0,
1917 generation: boundary.session,
1918 segment: boundary.segment,
1919 format: boundary.format,
1920 kind: ordering::ControlKind::Recovered,
1921 losses: ordering::Losses::default(),
1922 records: 1,
1923 }),
1924 copies: Default::default(),
1925 });
1926 }
1927
1928 if self.stopped {
1929 return Ok(ReadResult {
1930 frames: 0,
1931 chunks: Vec::new(),
1932 first_packet: None,
1933 last_packet: None,
1934 reason: PartialReason::Eof,
1935 control: None,
1936 copies: Default::default(),
1937 });
1938 }
1939 if self.terminal_error.is_some() {
1940 return Ok(ReadResult {
1941 frames: 0,
1942 chunks: Vec::new(),
1943 first_packet: None,
1944 last_packet: None,
1945 reason: PartialReason::Failure(Failure::Backend),
1946 control: None,
1947 copies: Default::default(),
1948 });
1949 }
1950 if cancel.is_cancelled() {
1951 return Ok(ReadResult {
1952 frames: 0,
1953 chunks: Vec::new(),
1954 first_packet: None,
1955 last_packet: None,
1956 reason: PartialReason::Cancelled,
1957 control: None,
1958 copies: Default::default(),
1959 });
1960 }
1961 drop(_guard);
1962
1963 match &mut self.engine {
1964 PlatformExecutionEngine::PassThrough {
1965 stream,
1966 waiting_relaunch,
1967 wait_deadline,
1968 } => {
1969 let Some(active) = stream.as_mut() else {
1970 return Ok(ReadResult {
1971 frames: 0,
1972 chunks: Vec::new(),
1973 first_packet: None,
1974 last_packet: None,
1975 reason: PartialReason::Eof,
1976 control: None,
1977 copies: Default::default(),
1978 });
1979 };
1980 let res = active.read_into_with_cancel(destination, frames, timeout, cancel)?;
1981 if res.reason == PartialReason::Eof
1982 && active.end_reason() == Some(EndReason::TargetExited)
1983 && let Some(t) = self.request.targets().first()
1984 && let OnRootExit::Wait { wait_timeout_ns } = t.on_root_exit()
1985 && !*waiting_relaunch
1986 {
1987 *waiting_relaunch = true;
1988 *wait_deadline = Some(Instant::now() + Duration::from_nanos(wait_timeout_ns));
1989 }
1990 if res.frames > 0 {
1991 self.last_metadata = Some(MixedBlockMetadata {
1992 membership_version: self.segment_counter,
1993 contributing_mask: 1,
1994 late_inputs: 0,
1995 failed_inputs: 0,
1996 nonfinite_inputs: 0,
1997 synthesized_silence: false,
1998 clipped_samples: 0,
1999 nonfinite_samples: 0,
2000 drift_slips: 0,
2001 skew_estimate_ns: Some(0),
2002 skew_uncertainty_ns: Some(0),
2003 });
2004 }
2005 Ok(res)
2006 }
2007 PlatformExecutionEngine::SoftwareMix { multi, .. } => {
2008 let out_stride = multi.output_format().bytes_per_frame();
2009 if destination.len() < frames.saturating_mul(out_stride) {
2010 return Err(ReadError::InvalidDestination);
2011 }
2012 if let Some((res, meta)) = multi.try_pop_pending_into(destination, frames)? {
2013 self.last_metadata = Some(meta);
2014 return Ok(res);
2015 }
2016 let now_ns = self.drain_software_mix_inputs(timeout, &cancel);
2017 if cancel.is_cancelled() {
2018 return Ok(ReadResult {
2019 frames: 0,
2020 chunks: Vec::new(),
2021 first_packet: None,
2022 last_packet: None,
2023 reason: PartialReason::Cancelled,
2024 control: None,
2025 copies: Default::default(),
2026 });
2027 }
2028 let align_ns = self.request.mixer_config().alignment_window_ns;
2029 let PlatformExecutionEngine::SoftwareMix { multi, .. } = &self.engine else {
2030 unreachable!()
2031 };
2032 let (res, meta) = multi.read_mixed_into(destination, frames, now_ns, align_ns)?;
2033 self.last_metadata = Some(meta);
2034 Ok(res)
2035 }
2036 }
2037 }
2038
2039 fn stop(&mut self, mode: Stop) {
2040 self.stopped = true;
2041 self.default_observer = None;
2042 self.default_input_observer = None;
2043 if mode == Stop::Abort {
2044 self.pending_boundary = None;
2045 }
2046 if let Some(cleanup) = &self.pending_cleanup {
2047 cleanup.cancel();
2048 }
2049 match &mut self.engine {
2050 PlatformExecutionEngine::PassThrough {
2051 stream,
2052 waiting_relaunch,
2053 wait_deadline,
2054 } => {
2055 *waiting_relaunch = false;
2056 *wait_deadline = None;
2057 if let Some(active) = stream.as_ref() {
2058 active.stop(mode);
2059 }
2060 }
2061 PlatformExecutionEngine::SoftwareMix {
2062 multi,
2063 streams,
2064 wait_deadlines,
2065 ..
2066 } => {
2067 if mode == Stop::Abort {
2068 multi.clear_pending_output();
2069 }
2070 for d in wait_deadlines.iter_mut() {
2071 *d = None;
2072 }
2073 for stream in streams.iter().flatten() {
2074 stream.stop(mode);
2075 }
2076 }
2077 }
2078 }
2079
2080 fn wait_cleanup(&mut self, timeout: Duration) -> bool {
2081 let started = Instant::now();
2082 match &mut self.engine {
2083 PlatformExecutionEngine::PassThrough { stream, .. } => {
2084 if let Some(active) = stream.as_ref() {
2085 let _ = active.wait_cleanup(timeout);
2086 }
2087 }
2088 PlatformExecutionEngine::SoftwareMix { streams, .. } => {
2089 for stream in streams.iter().flatten() {
2090 let rem = timeout.saturating_sub(started.elapsed());
2091 let _ = stream.wait_cleanup(rem);
2092 }
2093 }
2094 }
2095 if let Some(cleanup) = &self.pending_cleanup {
2096 let rem = timeout.saturating_sub(started.elapsed());
2097 let _ = cleanup.wait(rem);
2098 }
2099 self.resources_done()
2100 }
2101
2102 fn resources_done(&self) -> bool {
2103 let engine_done = match &self.engine {
2104 PlatformExecutionEngine::PassThrough { stream, .. } => stream
2105 .as_deref()
2106 .is_none_or(AudioStreamBackend::resources_done),
2107 PlatformExecutionEngine::SoftwareMix { streams, .. } => streams
2108 .iter()
2109 .flatten()
2110 .all(AudioStreamBackend::resources_done),
2111 };
2112 let cleanup_done = self
2113 .pending_cleanup
2114 .as_ref()
2115 .is_none_or(StartupCleanup::is_complete);
2116 engine_done && cleanup_done
2117 }
2118}
2119
2120impl Drop for PlatformManager {
2121 fn drop(&mut self) {
2122 self.stop(Stop::Abort);
2123 let _ = self.wait_cleanup(self.cleanup_timeout.min(Duration::from_millis(500)));
2124 }
2125}
2126
2127#[cfg(test)]
2128mod tests {
2129 use super::*;
2130 use crate::{
2131 CaptureManager, NativeFormat,
2132 core::schema::{CombineMode, DitherMode, InputConversionPolicy, OutputConverterConfig},
2133 };
2134
2135 fn read_into_via_generic_manager<B: CaptureManagerBackend>(
2136 mgr: &mut crate::core::traits::CaptureManager<B>,
2137 dst: &mut [u8],
2138 frames: usize,
2139 timeout: Duration,
2140 ) -> Result<ReadResult, ReadError> {
2141 mgr.read_into(dst, frames, timeout)
2142 }
2143
2144 fn make_tone_packets_i16_mono(
2145 rate_hz: u32,
2146 freq_hz: f64,
2147 packets: usize,
2148 frames_per_pkt: usize,
2149 ) -> Vec<(Vec<u8>, usize, u64)> {
2150 let mut out = Vec::with_capacity(packets);
2151 let step_qpc = (frames_per_pkt as u64 * 10_000_000) / u64::from(rate_hz);
2152 for p in 0..packets {
2153 let mut bytes = Vec::with_capacity(frames_per_pkt * 2);
2154 for n in 0..frames_per_pkt {
2155 let idx = p * frames_per_pkt + n;
2156 let t = idx as f64 / f64::from(rate_hz);
2157 let v = (0.25 * (2.0 * std::f64::consts::PI * freq_hz * t).sin() * 32767.0).round()
2158 as i16;
2159 bytes.extend_from_slice(&v.to_le_bytes());
2160 }
2161 out.push((bytes, frames_per_pkt, 1_000_000 + (p as u64) * step_qpc));
2162 }
2163 out
2164 }
2165
2166 fn make_tone_packets_f32_stereo(
2167 rate_hz: u32,
2168 freq_l: f64,
2169 freq_r: f64,
2170 packets: usize,
2171 frames_per_pkt: usize,
2172 ) -> Vec<(Vec<u8>, usize, u64)> {
2173 let mut out = Vec::with_capacity(packets);
2174 let step_qpc = (frames_per_pkt as u64 * 10_000_000) / u64::from(rate_hz);
2175 for p in 0..packets {
2176 let mut bytes = Vec::with_capacity(frames_per_pkt * 8);
2177 for n in 0..frames_per_pkt {
2178 let idx = p * frames_per_pkt + n;
2179 let t = idx as f64 / f64::from(rate_hz);
2180 let l = (0.25 * (2.0 * std::f64::consts::PI * freq_l * t).sin()) as f32;
2181 let r = (0.25 * (2.0 * std::f64::consts::PI * freq_r * t).sin()) as f32;
2182 bytes.extend_from_slice(&l.to_le_bytes());
2183 bytes.extend_from_slice(&r.to_le_bytes());
2184 }
2185 out.push((bytes, frames_per_pkt, 1_000_000 + (p as u64) * step_qpc));
2186 }
2187 out
2188 }
2189
2190 #[test]
2191 fn unified_manager_heterogeneous_mix_runs_zero_steady_allocations_and_preserves_tones()
2192 -> Result<(), CapabilityError> {
2193 let mic_fmt = Arc::new(
2194 Format::new(
2195 SampleType::I16,
2196 ByteOrder::Little,
2197 16_000,
2198 1,
2199 Layout::Known(Arc::from([Channel::Mono])),
2200 )
2201 .unwrap(),
2202 );
2203 let sys_fmt = Arc::new(
2204 Format::new(
2205 SampleType::F32,
2206 ByteOrder::Little,
2207 48_000,
2208 2,
2209 Layout::Known(Arc::from([Channel::FrontLeft, Channel::FrontRight])),
2210 )
2211 .unwrap(),
2212 );
2213 let budget = StorageBudget::new(8, 32 * 1024 * 1024).unwrap();
2214 let mic_pkts = make_tone_packets_i16_mono(16_000, 500.0, 50, 160);
2215 let sys_pkts = make_tone_packets_f32_stereo(48_000, 1000.0, 1500.0, 50, 480);
2216
2217 let mic_target = CaptureTarget::input_device("synth-mic-0").unwrap();
2218 let sys_target = CaptureTarget::device("synth-sys-0").unwrap();
2219 let mic_stream = PlatformStream::from_synthetic_packets(
2220 NativeFormat {
2221 target: mic_target.clone(),
2222 native_mix_known: true,
2223 endpoint: "synth-mic-0".into(),
2224 pcm: mic_fmt,
2225 buffer_frames: 1600,
2226 channel_mask: Some(0x4),
2227 },
2228 crate::core::stream_runtime::endpoint_clock_domain("synth-mic-0", 2),
2229 mic_pkts,
2230 budget.clone(),
2231 )?;
2232 let sys_stream = PlatformStream::from_synthetic_packets(
2233 NativeFormat {
2234 target: sys_target.clone(),
2235 native_mix_known: true,
2236 endpoint: "synth-sys-0".into(),
2237 pcm: sys_fmt,
2238 buffer_frames: 4800,
2239 channel_mask: Some(0x3),
2240 },
2241 1,
2242 sys_pkts,
2243 budget.clone(),
2244 )?;
2245
2246 let req = CaptureRequest::new(vec![mic_target, sys_target]);
2247 let mut mgr = CaptureManager::from_backend(PlatformManager::from_synthetic_streams(
2248 req,
2249 vec![mic_stream, sys_stream],
2250 budget,
2251 )?);
2252 assert!(mgr.is_software_mix());
2253 assert!(mgr.route_guard().is_some_and(|g| !g.allow_reroute()));
2254 assert_eq!(mgr.working_format().unwrap().rate(), 48_000);
2255 assert_eq!(mgr.working_format().unwrap().channels(), 2);
2256 assert!(mgr.input_handles()[0].is_resampled());
2257 assert!(!mgr.input_handles()[0].is_identity_bypass());
2258 assert!(!mgr.input_handles()[1].is_resampled());
2259 assert!(mgr.input_handles()[1].is_identity_bypass());
2260
2261 let mut dst = [0u8; 256 * 8];
2262 let mut mixed_samples = Vec::with_capacity(48_000);
2263 for _ in 0..2 {
2264 let res =
2265 read_into_via_generic_manager(&mut mgr, &mut dst, 256, Duration::from_millis(40))
2266 .unwrap();
2267 for b in dst[..res.frames * 8].chunks_exact(4) {
2268 mixed_samples.push(f32::from_le_bytes([b[0], b[1], b[2], b[3]]));
2269 }
2270 }
2271 let mut measured_reads = 0usize;
2272 let allocs = allocation_counter::measure(|| {
2273 for _ in 0..64 {
2274 let res = read_into_via_generic_manager(
2275 &mut mgr,
2276 &mut dst,
2277 256,
2278 Duration::from_millis(40),
2279 )
2280 .unwrap();
2281 if res.frames > 0 {
2282 measured_reads += 1;
2283 }
2284 }
2285 });
2286 assert!(measured_reads >= 40);
2287 assert_eq!(
2288 allocs.count_total, 0,
2289 "CaptureManager<PlatformManager>::read_into allocated {} times in steady state",
2290 allocs.count_total
2291 );
2292
2293 drop(mgr);
2294 let budget2 = StorageBudget::new(8, 32 * 1024 * 1024).unwrap();
2295 let mic_t2 = CaptureTarget::input_device("synth-mic-1").unwrap();
2296 let sys_t2 = CaptureTarget::device("synth-sys-1").unwrap();
2297 let m2 = PlatformStream::from_synthetic_packets(
2298 NativeFormat {
2299 target: mic_t2.clone(),
2300 native_mix_known: true,
2301 endpoint: "synth-mic-1".into(),
2302 pcm: Arc::new(
2303 Format::new(
2304 SampleType::I16,
2305 ByteOrder::Little,
2306 16_000,
2307 1,
2308 Layout::Known(Arc::from([Channel::Mono])),
2309 )
2310 .unwrap(),
2311 ),
2312 buffer_frames: 1600,
2313 channel_mask: Some(0x4),
2314 },
2315 3,
2316 make_tone_packets_i16_mono(16_000, 500.0, 40, 160),
2317 budget2.clone(),
2318 )?;
2319 let s2 = PlatformStream::from_synthetic_packets(
2320 NativeFormat {
2321 target: sys_t2.clone(),
2322 native_mix_known: true,
2323 endpoint: "synth-sys-1".into(),
2324 pcm: Arc::new(
2325 Format::new(
2326 SampleType::F32,
2327 ByteOrder::Little,
2328 48_000,
2329 2,
2330 Layout::Known(Arc::from([Channel::FrontLeft, Channel::FrontRight])),
2331 )
2332 .unwrap(),
2333 ),
2334 buffer_frames: 4800,
2335 channel_mask: Some(0x3),
2336 },
2337 1,
2338 make_tone_packets_f32_stereo(48_000, 1000.0, 1500.0, 40, 480),
2339 budget2.clone(),
2340 )?;
2341 let mut mgr2 = CaptureManager::from_backend(PlatformManager::from_synthetic_streams(
2342 CaptureRequest::new(vec![mic_t2, sys_t2]),
2343 vec![m2, s2],
2344 budget2,
2345 )?);
2346 mixed_samples.clear();
2347 for _ in 0..80 {
2348 let res = mgr2
2349 .read_into(&mut dst, 256, Duration::from_millis(40))
2350 .unwrap();
2351 for b in dst[..res.frames * 8].chunks_exact(4) {
2352 mixed_samples.push(f32::from_le_bytes([b[0], b[1], b[2], b[3]]));
2353 }
2354 if mixed_samples.len() >= 14_400 * 2 {
2355 break;
2356 }
2357 }
2358 mgr2.stop(Stop::Abort);
2359 assert!(mgr2.wait_cleanup(Duration::from_secs(2)));
2360 assert!(mixed_samples.len() >= 9_600 * 2);
2361
2362 let window_frames = 4_800usize;
2363 let start_frame = 2_400usize;
2364 let tone_amp = |ch_offset: usize, freq: f64| -> f64 {
2365 let (mut sin_acc, mut cos_acc) = (0.0_f64, 0.0_f64);
2366 for k in 0..window_frames {
2367 let s = f64::from(mixed_samples[(start_frame + k) * 2 + ch_offset]);
2368 let angle = 2.0 * std::f64::consts::PI * freq * (k as f64 / 48_000.0);
2369 sin_acc += s * angle.sin();
2370 cos_acc += s * angle.cos();
2371 }
2372 2.0 * sin_acc.hypot(cos_acc) / (window_frames as f64)
2373 };
2374 assert!((tone_amp(0, 500.0) - 0.25).abs() < 2e-4);
2375 assert!((tone_amp(1, 500.0) - 0.25).abs() < 2e-4);
2376 assert!((tone_amp(0, 1000.0) - 0.25).abs() < 1e-5);
2377 assert!(tone_amp(1, 1000.0) < 1e-5);
2378 assert!(tone_amp(0, 1500.0) < 1e-5);
2379 assert!((tone_amp(1, 1500.0) - 0.25).abs() < 1e-5);
2380 Ok(())
2381 }
2382
2383 #[test]
2384 fn unified_manager_enforces_on_format_change_fail_strict_no_resample_and_single_target_mixer_routing()
2385 -> Result<(), CapabilityError> {
2386 let fmt_48k = Arc::new(
2387 Format::new(
2388 SampleType::F32,
2389 ByteOrder::Little,
2390 48_000,
2391 2,
2392 Layout::Known(Arc::from([Channel::FrontLeft, Channel::FrontRight])),
2393 )
2394 .unwrap(),
2395 );
2396 let fmt_44k = Arc::new(
2397 Format::new(
2398 SampleType::F32,
2399 ByteOrder::Little,
2400 44_100,
2401 2,
2402 Layout::Known(Arc::from([Channel::FrontLeft, Channel::FrontRight])),
2403 )
2404 .unwrap(),
2405 );
2406 let budget = StorageBudget::new(8, 16 * 1024 * 1024).unwrap();
2407
2408 let gain_target = CaptureTarget::device("synth-gain")
2409 .unwrap()
2410 .with_gain(0.5)
2411 .unwrap();
2412 let gain_stream = PlatformStream::from_synthetic_packets(
2413 NativeFormat {
2414 target: gain_target.clone(),
2415 native_mix_known: true,
2416 endpoint: "synth-gain".into(),
2417 pcm: fmt_48k.clone(),
2418 buffer_frames: 4800,
2419 channel_mask: Some(0x3),
2420 },
2421 1,
2422 make_tone_packets_f32_stereo(48_000, 1000.0, 1000.0, 4, 480),
2423 budget.clone(),
2424 )?;
2425 let gain_mgr = CaptureManager::from_backend(PlatformManager::from_synthetic_streams(
2426 CaptureRequest::single(gain_target),
2427 vec![gain_stream],
2428 budget.clone(),
2429 )?);
2430 assert!(gain_mgr.is_software_mix());
2431 drop(gain_mgr);
2432
2433 let i16_16k = Format::new(
2434 SampleType::I16,
2435 ByteOrder::Little,
2436 16_000,
2437 1,
2438 Layout::Known(Arc::from([Channel::Mono])),
2439 )
2440 .unwrap();
2441 let conv_target = CaptureTarget::device("synth-conv").unwrap();
2442 let conv_stream = PlatformStream::from_synthetic_packets(
2443 NativeFormat {
2444 target: conv_target.clone(),
2445 native_mix_known: true,
2446 endpoint: "synth-conv".into(),
2447 pcm: fmt_48k.clone(),
2448 buffer_frames: 4800,
2449 channel_mask: Some(0x3),
2450 },
2451 1,
2452 make_tone_packets_f32_stereo(48_000, 1000.0, 1000.0, 4, 480),
2453 budget.clone(),
2454 )?;
2455 let mut conv_mgr = CaptureManager::from_backend(PlatformManager::from_synthetic_streams(
2456 CaptureRequest::single(conv_target)
2457 .with_output_converter(Some(OutputConverterConfig::new(i16_16k, DitherMode::None))),
2458 vec![conv_stream],
2459 budget.clone(),
2460 )?);
2461 assert!(conv_mgr.is_software_mix());
2462 assert_eq!(conv_mgr.output_format().unwrap().rate(), 16_000);
2463 let mut i16_dst = [0u8; 160 * 2];
2464 let conv_res = conv_mgr
2465 .read_into(&mut i16_dst, 160, Duration::from_millis(40))
2466 .unwrap();
2467 assert_eq!(conv_res.frames, 160);
2468 drop(conv_mgr);
2469
2470 let follow_out = CaptureTarget::default_output(DefaultDeviceMode::Follow);
2471 let pt_s1 = PlatformStream::from_synthetic_packets(
2472 NativeFormat {
2473 target: follow_out.clone(),
2474 native_mix_known: true,
2475 endpoint: "out-48k".into(),
2476 pcm: fmt_48k.clone(),
2477 buffer_frames: 4800,
2478 channel_mask: Some(0x3),
2479 },
2480 1,
2481 make_tone_packets_f32_stereo(48_000, 440.0, 440.0, 2, 480),
2482 budget.clone(),
2483 )?;
2484 let pt_s2 = PlatformStream::from_synthetic_packets(
2485 NativeFormat {
2486 target: follow_out.clone(),
2487 native_mix_known: true,
2488 endpoint: "out-44k".into(),
2489 pcm: fmt_44k.clone(),
2490 buffer_frames: 4410,
2491 channel_mask: Some(0x3),
2492 },
2493 1,
2494 make_tone_packets_f32_stereo(44_100, 440.0, 440.0, 2, 441),
2495 budget.clone(),
2496 )?;
2497 let mut pt_fail_mgr = PlatformManager::from_synthetic_streams(
2498 CaptureRequest::single(follow_out.clone()).with_on_format_change(OnFormatChange::Fail),
2499 vec![pt_s1],
2500 budget.clone(),
2501 )?;
2502 assert!(!pt_fail_mgr.is_software_mix());
2503 assert_eq!(
2504 pt_fail_mgr.apply_opened_default_stream_for_test(TargetKind::DefaultOutput, pt_s2),
2505 Err(CapabilityError::FormatChangeRejected)
2506 );
2507 drop(pt_fail_mgr);
2508
2509 let mix_s1 = PlatformStream::from_synthetic_packets(
2510 NativeFormat {
2511 target: follow_out.clone(),
2512 native_mix_known: true,
2513 endpoint: "out-48k".into(),
2514 pcm: fmt_48k.clone(),
2515 buffer_frames: 4800,
2516 channel_mask: Some(0x3),
2517 },
2518 1,
2519 make_tone_packets_f32_stereo(48_000, 440.0, 440.0, 2, 480),
2520 budget.clone(),
2521 )?;
2522 let mix_s2 = PlatformStream::from_synthetic_packets(
2523 NativeFormat {
2524 target: follow_out.clone(),
2525 native_mix_known: true,
2526 endpoint: "out-44k".into(),
2527 pcm: fmt_44k.clone(),
2528 buffer_frames: 4410,
2529 channel_mask: Some(0x3),
2530 },
2531 1,
2532 make_tone_packets_f32_stereo(44_100, 440.0, 440.0, 2, 441),
2533 budget.clone(),
2534 )?;
2535 let mut mix_fail_mgr = PlatformManager::from_synthetic_streams(
2536 CaptureRequest::single(follow_out)
2537 .with_combine_mode(CombineMode::CspaMixer)
2538 .with_on_format_change(OnFormatChange::Fail),
2539 vec![mix_s1],
2540 budget.clone(),
2541 )?;
2542 assert!(mix_fail_mgr.is_software_mix());
2543 assert_eq!(
2544 mix_fail_mgr.apply_opened_default_stream_for_test(TargetKind::DefaultOutput, mix_s2),
2545 Err(CapabilityError::FormatChangeRejected)
2546 );
2547 drop(mix_fail_mgr);
2548
2549 let strict_a = CaptureTarget::device("strict-48k").unwrap();
2550 let strict_b = CaptureTarget::input_device("strict-44k").unwrap();
2551 let sa = PlatformStream::from_synthetic_packets(
2552 NativeFormat {
2553 target: strict_a.clone(),
2554 native_mix_known: true,
2555 endpoint: "strict-48k".into(),
2556 pcm: fmt_48k,
2557 buffer_frames: 4800,
2558 channel_mask: Some(0x3),
2559 },
2560 1,
2561 make_tone_packets_f32_stereo(48_000, 440.0, 440.0, 2, 480),
2562 budget.clone(),
2563 )?;
2564 let sb = PlatformStream::from_synthetic_packets(
2565 NativeFormat {
2566 target: strict_b.clone(),
2567 native_mix_known: true,
2568 endpoint: "strict-44k".into(),
2569 pcm: fmt_44k,
2570 buffer_frames: 4410,
2571 channel_mask: Some(0x3),
2572 },
2573 2,
2574 make_tone_packets_f32_stereo(44_100, 440.0, 440.0, 2, 441),
2575 budget.clone(),
2576 )?;
2577 let strict_res = PlatformManager::from_synthetic_streams(
2578 CaptureRequest::new(vec![strict_a, strict_b])
2579 .with_input_conversion(InputConversionPolicy::StrictNoResample),
2580 vec![sa, sb],
2581 budget.clone(),
2582 );
2583 assert_eq!(strict_res.err(), Some(CapabilityError::UnsupportedFormat));
2584
2585 let can_a = CaptureTarget::device("cancel-a").unwrap();
2586 let can_b = CaptureTarget::input_device("cancel-b").unwrap();
2587 let fmt_can = Arc::new(
2588 Format::new(
2589 SampleType::F32,
2590 ByteOrder::Little,
2591 48_000,
2592 2,
2593 Layout::Known(Arc::from([Channel::FrontLeft, Channel::FrontRight])),
2594 )
2595 .unwrap(),
2596 );
2597 let sc_a = PlatformStream::from_synthetic_packets(
2598 NativeFormat {
2599 target: can_a.clone(),
2600 native_mix_known: true,
2601 endpoint: "cancel-a".into(),
2602 pcm: fmt_can.clone(),
2603 buffer_frames: 4800,
2604 channel_mask: Some(0x3),
2605 },
2606 1,
2607 Vec::new(),
2608 budget.clone(),
2609 )?;
2610 let sc_b = PlatformStream::from_synthetic_packets(
2611 NativeFormat {
2612 target: can_b.clone(),
2613 native_mix_known: true,
2614 endpoint: "cancel-b".into(),
2615 pcm: fmt_can,
2616 buffer_frames: 4800,
2617 channel_mask: Some(0x3),
2618 },
2619 2,
2620 Vec::new(),
2621 budget,
2622 )?;
2623 let mut can_mgr = CaptureManager::from_backend(PlatformManager::from_synthetic_streams(
2624 CaptureRequest::new(vec![can_a, can_b]),
2625 vec![sc_a, sc_b],
2626 StorageBudget::new(8, 16 * 1024 * 1024).unwrap(),
2627 )?);
2628 let cancel = Cancellation::default();
2629 cancel.cancel();
2630 let mut can_dst = [0u8; 256 * 8];
2631 let can_res = can_mgr
2632 .read_into_with_cancel(&mut can_dst, 256, Duration::from_secs(2), cancel)
2633 .unwrap();
2634 assert_eq!(can_res.frames, 0);
2635 assert_eq!(can_res.reason, PartialReason::Cancelled);
2636 Ok(())
2637 }
2638}