Skip to main content

capture_system_or_process_audio_linux/
manager.rs

1#![cfg_attr(not(target_os = "linux"), allow(dead_code))]
2
3use crate::{
4    capabilities::{PulseServerKind, resolve_linux_plan_with_readiness},
5    core::{
6        converter::FrameReblocker,
7        manager::{
8            BoundaryKind, InputStatusHandle, ManagerError, MultiInputManager, SessionBoundary,
9            StorageBudget, default_block_frames_for_rate,
10        },
11        ordering::{self, Failure, Overflow, Stop},
12        planner::{CapturePlanReport, CaptureRequest},
13        reads::{Cancellation, PartialReason, ReadError, ReadResult},
14        routing::RouteRollbackGuard,
15        schema::{
16            BackendId, ByteOrder, CaptureTarget, Channel, CombineResolution, DefaultDeviceMode,
17            Format, Layout, MembershipDescriptor, MixedBlockMetadata, OnFormatChange, OnRootExit,
18            ParticipationState, ProcessIdentity, ProcessScope, SampleType, Stamp, TargetKind,
19        },
20        traits::{
21            AudioStreamBackend, CapabilityError, CaptureManagerBackend, DefaultEndpointObserver,
22            TimingRequirement, TopologyControllerBackend,
23        },
24    },
25    discovery::{
26        PlatformDefaultInputObserver, PlatformDefaultOutputObserver, collect_pulse_state,
27        query_linux_default_sink_now, query_linux_default_source_now,
28        spawn_pulse_new_sink_input_watcher,
29    },
30    loader::{LinuxClientPaths, probe_pipewire_server, probe_pulse_server},
31    pipewire_stream::{
32        PlatformTopologyController, open_pipewire_point, open_pipewire_source_point,
33        start_pipewire_topology_controller,
34    },
35    procfs::{
36        collect_proc_stat_table, inspect_process_executable, inspect_process_in_proc_root,
37        pid_belongs_to_target,
38    },
39    pulse_stream::{PlatformStream, open_pulse_point, open_pulse_source_point},
40};
41use std::{
42    collections::{BTreeMap, BTreeSet},
43    path::Path,
44    sync::{
45        Arc, Mutex, TryLockError,
46        atomic::{AtomicBool, Ordering::SeqCst},
47    },
48    thread::{self, JoinHandle},
49    time::{Duration, Instant},
50};
51
52const MAX_FRAMES_PER_SLOT: usize = 4096;
53const PA_PROC_QUANTUM_FRAMES: usize = 480;
54
55fn fallback_working_format() -> Result<Arc<Format>, CapabilityError> {
56    Format::new(
57        SampleType::F32,
58        ByteOrder::Little,
59        48_000,
60        2,
61        Layout::Known(Arc::from([Channel::FrontLeft, Channel::FrontRight])),
62    )
63    .map(Arc::new)
64    .map_err(|_| CapabilityError::UnsupportedFormat)
65}
66
67fn clean_target_device_id(target: &CaptureTarget) -> Option<String> {
68    target.clean_device_id().map(str::to_owned)
69}
70
71fn resolve_pinned_linux_target(
72    target: &mut CaptureTarget,
73    backend: BackendId,
74    paths: &LinuxClientPaths,
75) {
76    if target.default_device_mode() != DefaultDeviceMode::Pin {
77        return;
78    }
79    let resolved = match target.kind() {
80        TargetKind::DefaultOutput => {
81            let out_id = query_linux_default_sink_now(backend, paths);
82            target.resolve_pinned_endpoint(out_id.as_deref(), None)
83        }
84        TargetKind::DefaultInput => {
85            let in_id = query_linux_default_source_now(backend, paths);
86            target.resolve_pinned_endpoint(None, in_id.as_deref())
87        }
88        _ => return,
89    };
90    *target = resolved;
91}
92
93fn validate_linux_process_targets(targets: &[CaptureTarget]) -> Result<(), CapabilityError> {
94    if targets.is_empty() {
95        return Err(CapabilityError::InvalidTarget);
96    }
97    for target in targets {
98        target.validate()?;
99        if matches!(target.kind(), TargetKind::Process | TargetKind::Application) {
100            let pid = target.pid().ok_or(CapabilityError::InvalidTarget)?;
101            let expected_gen = target
102                .process_start_time()
103                .ok_or(CapabilityError::InvalidTarget)?;
104            let (stat, _) = inspect_process_in_proc_root(Path::new("/proc"), pid)?;
105            if expected_gen != 0 && stat.starttime_ticks != expected_gen {
106                return Err(CapabilityError::PidReused);
107            }
108        }
109    }
110    Ok(())
111}
112
113struct SoftwareMixInput {
114    target_idx: usize,
115    backend: BackendId,
116    stream: PlatformStream,
117    last_active: Option<Instant>,
118    sub_reblocker: Option<FrameReblocker>,
119    last_stamp: Option<Stamp>,
120    eof: bool,
121}
122
123impl SoftwareMixInput {
124    fn new_direct(target_idx: usize, backend: BackendId, stream: PlatformStream) -> Self {
125        Self {
126            target_idx,
127            backend,
128            stream,
129            last_active: Some(Instant::now()),
130            sub_reblocker: None,
131            last_stamp: None,
132            eof: false,
133        }
134    }
135
136    fn new_pulse_substream(
137        target_idx: usize,
138        backend: BackendId,
139        stream: PlatformStream,
140    ) -> Result<Self, CapabilityError> {
141        let reblocker = FrameReblocker::new(2, PA_PROC_QUANTUM_FRAMES, MAX_FRAMES_PER_SLOT * 4)
142            .map_err(|_| CapabilityError::CapacityExceeded)?;
143        Ok(Self {
144            target_idx,
145            backend,
146            stream,
147            last_active: Some(Instant::now()),
148            sub_reblocker: Some(reblocker),
149            last_stamp: None,
150            eof: false,
151        })
152    }
153}
154
155struct PaSubWatch {
156    dirty: Arc<AtomicBool>,
157    stop: Arc<AtomicBool>,
158    join: Option<JoinHandle<()>>,
159}
160
161impl PaSubWatch {
162    fn spawn(paths: &LinuxClientPaths) -> Self {
163        let dirty = Arc::new(AtomicBool::new(false));
164        let stop = Arc::new(AtomicBool::new(false));
165        let join = spawn_pulse_new_sink_input_watcher(paths, dirty.clone(), stop.clone());
166        Self { dirty, stop, join }
167    }
168
169    fn stop_and_join(&mut self) {
170        self.stop.store(true, SeqCst);
171        if let Some(join) = self.join.take() {
172            let _ = join.join();
173        }
174    }
175}
176
177impl Drop for PaSubWatch {
178    fn drop(&mut self) {
179        self.stop_and_join();
180    }
181}
182
183#[allow(clippy::large_enum_variant)]
184enum PlatformExecutionEngine {
185    PassThrough {
186        stream: Option<PlatformStream>,
187        topology: Option<PlatformTopologyController>,
188    },
189    SoftwareMix {
190        block_frames: usize,
191        multi: Box<MultiInputManager>,
192        inputs: Vec<SoftwareMixInput>,
193        sub_topologies: Vec<(usize, PlatformTopologyController)>,
194        opened_sink_inputs: BTreeSet<(usize, u32)>,
195        pa_sub_watch: Option<PaSubWatch>,
196        last_sink_input_scan: Instant,
197        started_at: Instant,
198        in_bytes_scratch: Vec<u8>,
199        pulse_sub_f32: Vec<f32>,
200        pulse_sum_f32: Vec<f32>,
201        pulse_sum_bytes: Vec<u8>,
202        drained_blocks: u64,
203    },
204}
205
206fn build_software_mix_multi(
207    request: CaptureRequest,
208    per_input_formats: Vec<(BackendId, Arc<Format>)>,
209    target_active: &[bool],
210    shared_budget: StorageBudget,
211) -> Result<(usize, Box<MultiInputManager>), CapabilityError> {
212    let max_rate = per_input_formats
213        .iter()
214        .map(|(_, f)| f.rate())
215        .max()
216        .unwrap_or(48_000);
217    let block_frames = default_block_frames_for_rate(max_rate, MAX_FRAMES_PER_SLOT);
218    let multi = MultiInputManager::new_heterogeneous_with_budget(
219        request,
220        per_input_formats,
221        block_frames,
222        MAX_FRAMES_PER_SLOT,
223        shared_budget,
224    )
225    .map_err(CapabilityError::from)?;
226
227    for (t_idx, &is_act) in target_active.iter().enumerate() {
228        let st = if is_act {
229            ParticipationState::Active
230        } else {
231            ParticipationState::Idle
232        };
233        let _ = multi.set_input_state(t_idx, st);
234    }
235    Ok((block_frames, Box::new(multi)))
236}
237
238/// Supports pass-through, shared PipeWire graph mixing, and cross-backend software mixing.
239/// Steady-state `read_into` uses no heap allocations; the output pool shares the storage budget.
240pub struct PlatformManager {
241    request: CaptureRequest,
242    paths: LinuxClientPaths,
243    plan: CapturePlanReport,
244    policy: Overflow,
245    timing: TimingRequirement,
246    pulse_server_kind: Option<PulseServerKind>,
247    budget: StorageBudget,
248    cleanup_timeout: Duration,
249    engine: PlatformExecutionEngine,
250    route_guard: RouteRollbackGuard,
251    default_cancel: Cancellation,
252    last_metadata: Option<MixedBlockMetadata>,
253    pending_boundary: Option<SessionBoundary>,
254    opened_default_device: Option<String>,
255    default_observer: Option<PlatformDefaultOutputObserver>,
256    opened_default_source: Option<String>,
257    default_source_observer: Option<PlatformDefaultInputObserver>,
258    last_default_check: Instant,
259    session_counter: u64,
260    segment_counter: u64,
261    stopped: bool,
262    terminal_error: Option<ManagerError>,
263    read_lock: Mutex<()>,
264}
265
266impl PlatformManager {
267    fn open_impl(
268        request: CaptureRequest,
269        paths: LinuxClientPaths,
270        policy: Overflow,
271        timing: TimingRequirement,
272        observed: bool,
273    ) -> Result<Self, CapabilityError> {
274        let cleanup_timeout = Duration::from_nanos(request.budgets().cleanup_timeout_ns);
275        if cleanup_timeout < Duration::from_millis(50) || cleanup_timeout > Duration::from_secs(30)
276        {
277            return Err(CapabilityError::InvalidTarget);
278        }
279
280        validate_linux_process_targets(request.targets())?;
281
282        let pw_ready = probe_pipewire_server(&paths).map(|_| ());
283        let pa_probe = probe_pulse_server(&paths);
284        let pa_ready = pa_probe.as_ref().map(|_| ()).map_err(Clone::clone);
285        if pw_ready.is_err() && pa_ready.is_err() {
286            crate::permissions::ensure_linux_socket_permissions(request.backends(), &paths)?;
287        }
288
289        let plan = resolve_linux_plan_with_readiness(
290            &request,
291            timing,
292            pw_ready.clone(),
293            pa_ready.clone(),
294        )?;
295
296        let any_pulse = plan
297            .target_plans
298            .iter()
299            .any(|p| p.resolved_backend == BackendId::PulseAudio);
300        let pulse_server_kind = if any_pulse {
301            pa_probe.as_ref().ok().map(|info| info.server_kind)
302        } else {
303            None
304        };
305
306        let mut resolved_targets = request.targets().to_vec();
307        for (idx, target) in resolved_targets.iter_mut().enumerate() {
308            resolve_pinned_linux_target(target, plan.target_plans[idx].resolved_backend, &paths);
309        }
310
311        let follow_out_backend = resolved_targets
312            .iter()
313            .enumerate()
314            .find(|(_, t)| {
315                t.kind() == TargetKind::DefaultOutput
316                    && t.default_device_mode() == DefaultDeviceMode::Follow
317            })
318            .map(|(idx, _)| plan.target_plans[idx].resolved_backend);
319        let follow_in_backend = resolved_targets
320            .iter()
321            .enumerate()
322            .find(|(_, t)| {
323                t.kind() == TargetKind::DefaultInput
324                    && t.default_device_mode() == DefaultDeviceMode::Follow
325            })
326            .map(|(idx, _)| plan.target_plans[idx].resolved_backend);
327
328        let initial_default_sink =
329            follow_out_backend.and_then(|b| query_linux_default_sink_now(b, &paths));
330        let initial_default_source =
331            follow_in_backend.and_then(|b| query_linux_default_source_now(b, &paths));
332
333        let budget = StorageBudget::new(
334            request.budgets().max_active_streams.max(2),
335            request.budgets().max_total_pcm_memory,
336        )
337        .map_err(|_| CapabilityError::CapacityExceeded)?;
338
339        let route_guard = RouteRollbackGuard::new(request.allow_reroute());
340        let fallback_pcm = fallback_working_format()?;
341        let final_request = request.with_targets(resolved_targets);
342
343        let engine = match plan.combine_resolution {
344            CombineResolution::PassThrough(b) => {
345                let target = &final_request.targets()[0];
346                match (b, target.kind()) {
347                    (BackendId::PipeWire, TargetKind::Device | TargetKind::DefaultOutput) => {
348                        let dev = clean_target_device_id(target)
349                            .or_else(|| query_linux_default_sink_now(BackendId::PipeWire, &paths));
350                        let stream = open_pipewire_point(
351                            &paths,
352                            dev.as_deref(),
353                            true,
354                            policy,
355                            timing,
356                            &budget,
357                            observed,
358                        )?;
359                        PlatformExecutionEngine::PassThrough {
360                            stream: Some(PlatformStream::PipeWire(stream)),
361                            topology: None,
362                        }
363                    }
364                    (BackendId::PipeWire, TargetKind::InputDevice | TargetKind::DefaultInput) => {
365                        let src = clean_target_device_id(target);
366                        let stream = open_pipewire_source_point(
367                            &paths,
368                            src.as_deref(),
369                            None,
370                            policy,
371                            timing,
372                            &budget,
373                            observed,
374                        )?;
375                        PlatformExecutionEngine::PassThrough {
376                            stream: Some(PlatformStream::PipeWire(stream)),
377                            topology: None,
378                        }
379                    }
380                    (BackendId::PipeWire, TargetKind::Process | TargetKind::Application) => {
381                        let topo = start_pipewire_topology_controller(
382                            &paths,
383                            final_request.targets().to_vec(),
384                            final_request.budgets().max_native_graph_links,
385                        )?;
386                        let stream = match open_pipewire_point(
387                            &paths,
388                            Some(topo.sink_name()),
389                            true,
390                            policy,
391                            timing,
392                            &budget,
393                            observed,
394                        ) {
395                            Ok(s) => s,
396                            Err(err) => {
397                                topo.shutdown();
398                                return Err(err);
399                            }
400                        };
401                        PlatformExecutionEngine::PassThrough {
402                            stream: Some(PlatformStream::PipeWire(stream)),
403                            topology: Some(topo),
404                        }
405                    }
406                    (BackendId::PulseAudio, TargetKind::Device | TargetKind::DefaultOutput) => {
407                        let dev = clean_target_device_id(target);
408                        let stream = open_pulse_point(
409                            &paths,
410                            dev.as_deref(),
411                            None,
412                            policy,
413                            timing,
414                            &budget,
415                            observed,
416                        )?;
417                        PlatformExecutionEngine::PassThrough {
418                            stream: Some(PlatformStream::Pulse(stream)),
419                            topology: None,
420                        }
421                    }
422                    (BackendId::PulseAudio, TargetKind::InputDevice | TargetKind::DefaultInput) => {
423                        let src = clean_target_device_id(target);
424                        let stream = open_pulse_source_point(
425                            &paths,
426                            src.as_deref(),
427                            None,
428                            policy,
429                            timing,
430                            &budget,
431                            observed,
432                        )?;
433                        PlatformExecutionEngine::PassThrough {
434                            stream: Some(PlatformStream::Pulse(stream)),
435                            topology: None,
436                        }
437                    }
438                    _ => return Err(CapabilityError::NotImplemented),
439                }
440            }
441            CombineResolution::SharedNativeGraphMix(BackendId::PipeWire) => {
442                let topo = start_pipewire_topology_controller(
443                    &paths,
444                    final_request.targets().to_vec(),
445                    final_request.budgets().max_native_graph_links,
446                )?;
447                let stream = match open_pipewire_point(
448                    &paths,
449                    Some(topo.sink_name()),
450                    true,
451                    policy,
452                    timing,
453                    &budget,
454                    observed,
455                ) {
456                    Ok(s) => s,
457                    Err(err) => {
458                        topo.shutdown();
459                        return Err(err);
460                    }
461                };
462                PlatformExecutionEngine::PassThrough {
463                    stream: Some(PlatformStream::PipeWire(stream)),
464                    topology: Some(topo),
465                }
466            }
467            CombineResolution::CspaMixer => {
468                let mut inputs: Vec<SoftwareMixInput> = Vec::new();
469                let mut sub_topologies: Vec<(usize, PlatformTopologyController)> = Vec::new();
470                let mut opened_sink_inputs: BTreeSet<(usize, u32)> = BTreeSet::new();
471                let mut per_input_formats: Vec<(BackendId, Arc<Format>)> =
472                    Vec::with_capacity(final_request.targets().len());
473                let mut target_initially_active = vec![false; final_request.targets().len()];
474
475                let need_pa_proc_scan =
476                    final_request.targets().iter().enumerate().any(|(idx, t)| {
477                        plan.target_plans[idx].resolved_backend == BackendId::PulseAudio
478                            && matches!(t.kind(), TargetKind::Process | TargetKind::Application)
479                    });
480                let (sink_inputs, proc_map) = if need_pa_proc_scan {
481                    let (_devs, _pids, si) = collect_pulse_state(&paths)?;
482                    let pm = collect_proc_stat_table(Path::new("/proc"))?;
483                    (si, pm)
484                } else {
485                    (Vec::new(), BTreeMap::new())
486                };
487
488                let open_outcome: Result<(), CapabilityError> = (|| {
489                    for (t_idx, target) in final_request.targets().iter().enumerate() {
490                        let t_backend = plan.target_plans[t_idx].resolved_backend;
491                        match (t_backend, target.kind()) {
492                            (
493                                BackendId::PipeWire,
494                                TargetKind::Device | TargetKind::DefaultOutput,
495                            ) => {
496                                let dev = clean_target_device_id(target).or_else(|| {
497                                    query_linux_default_sink_now(BackendId::PipeWire, &paths)
498                                });
499                                let stream = open_pipewire_point(
500                                    &paths,
501                                    dev.as_deref(),
502                                    true,
503                                    policy,
504                                    timing,
505                                    &budget,
506                                    observed,
507                                )?;
508                                per_input_formats.push((t_backend, stream.format().clone()));
509                                target_initially_active[t_idx] = true;
510                                inputs.push(SoftwareMixInput::new_direct(
511                                    t_idx,
512                                    t_backend,
513                                    PlatformStream::PipeWire(stream),
514                                ));
515                            }
516                            (
517                                BackendId::PipeWire,
518                                TargetKind::InputDevice | TargetKind::DefaultInput,
519                            ) => {
520                                let src = clean_target_device_id(target);
521                                let stream = open_pipewire_source_point(
522                                    &paths,
523                                    src.as_deref(),
524                                    None,
525                                    policy,
526                                    timing,
527                                    &budget,
528                                    observed,
529                                )?;
530                                per_input_formats.push((t_backend, stream.format().clone()));
531                                target_initially_active[t_idx] = true;
532                                inputs.push(SoftwareMixInput::new_direct(
533                                    t_idx,
534                                    t_backend,
535                                    PlatformStream::PipeWire(stream),
536                                ));
537                            }
538                            (
539                                BackendId::PipeWire,
540                                TargetKind::Process | TargetKind::Application,
541                            ) => {
542                                let single_topo = start_pipewire_topology_controller(
543                                    &paths,
544                                    vec![target.clone()],
545                                    final_request.budgets().max_native_graph_links,
546                                )?;
547                                let stream = match open_pipewire_point(
548                                    &paths,
549                                    Some(single_topo.sink_name()),
550                                    true,
551                                    policy,
552                                    timing,
553                                    &budget,
554                                    observed,
555                                ) {
556                                    Ok(s) => s,
557                                    Err(err) => {
558                                        single_topo.shutdown();
559                                        return Err(err);
560                                    }
561                                };
562                                per_input_formats.push((t_backend, stream.format().clone()));
563                                target_initially_active[t_idx] = true;
564                                sub_topologies.push((t_idx, single_topo));
565                                inputs.push(SoftwareMixInput::new_direct(
566                                    t_idx,
567                                    t_backend,
568                                    PlatformStream::PipeWire(stream),
569                                ));
570                            }
571                            (
572                                BackendId::PulseAudio,
573                                TargetKind::Device | TargetKind::DefaultOutput,
574                            ) => {
575                                let dev = clean_target_device_id(target);
576                                let stream = open_pulse_point(
577                                    &paths,
578                                    dev.as_deref(),
579                                    None,
580                                    policy,
581                                    timing,
582                                    &budget,
583                                    observed,
584                                )?;
585                                per_input_formats.push((t_backend, stream.format().clone()));
586                                target_initially_active[t_idx] = true;
587                                inputs.push(SoftwareMixInput::new_direct(
588                                    t_idx,
589                                    t_backend,
590                                    PlatformStream::Pulse(stream),
591                                ));
592                            }
593                            (
594                                BackendId::PulseAudio,
595                                TargetKind::InputDevice | TargetKind::DefaultInput,
596                            ) => {
597                                let src = clean_target_device_id(target);
598                                let stream = open_pulse_source_point(
599                                    &paths,
600                                    src.as_deref(),
601                                    None,
602                                    policy,
603                                    timing,
604                                    &budget,
605                                    observed,
606                                )?;
607                                per_input_formats.push((t_backend, stream.format().clone()));
608                                target_initially_active[t_idx] = true;
609                                inputs.push(SoftwareMixInput::new_direct(
610                                    t_idx,
611                                    t_backend,
612                                    PlatformStream::Pulse(stream),
613                                ));
614                            }
615                            (
616                                BackendId::PulseAudio,
617                                TargetKind::Process | TargetKind::Application,
618                            ) => {
619                                let root_pid =
620                                    target.pid().ok_or(CapabilityError::InvalidTarget)?;
621                                let root_id = ProcessIdentity {
622                                    pid: root_pid,
623                                    generation: target.process_start_time().unwrap_or(0),
624                                };
625                                let exact_only = target.scope() == ProcessScope::Exact;
626                                let mut matched_any = false;
627                                for si in &sink_inputs {
628                                    if let Some(si_pid) = si.pid
629                                        && pid_belongs_to_target(
630                                            &proc_map, root_id, exact_only, si_pid,
631                                        )?
632                                    {
633                                        let stream = open_pulse_point(
634                                            &paths,
635                                            None,
636                                            Some(si.index),
637                                            policy,
638                                            timing,
639                                            &budget,
640                                            observed,
641                                        )?;
642                                        opened_sink_inputs.insert((t_idx, si.index));
643                                        inputs.push(SoftwareMixInput::new_pulse_substream(
644                                            t_idx,
645                                            t_backend,
646                                            PlatformStream::Pulse(stream),
647                                        )?);
648                                        matched_any = true;
649                                    }
650                                }
651                                target_initially_active[t_idx] = matched_any;
652                                per_input_formats.push((t_backend, fallback_pcm.clone()));
653                            }
654                            _ => return Err(CapabilityError::InvalidBackend),
655                        }
656                    }
657                    Ok(())
658                })();
659
660                if let Err(err) = open_outcome {
661                    for (_, topo) in sub_topologies {
662                        topo.shutdown();
663                    }
664                    for inp in inputs {
665                        inp.stream.stop(Stop::Abort);
666                        let _ = inp.stream.wait_cleanup(cleanup_timeout);
667                    }
668                    return Err(err);
669                }
670
671                let (block_frames, multi) = match build_software_mix_multi(
672                    final_request.clone(),
673                    per_input_formats,
674                    &target_initially_active,
675                    budget.clone(),
676                ) {
677                    Ok(pair) => pair,
678                    Err(err) => {
679                        for (_, topo) in sub_topologies {
680                            topo.shutdown();
681                        }
682                        for inp in inputs {
683                            inp.stream.stop(Stop::Abort);
684                            let _ = inp.stream.wait_cleanup(cleanup_timeout);
685                        }
686                        return Err(err);
687                    }
688                };
689
690                let ready_now = Instant::now();
691                for inp in &mut inputs {
692                    inp.last_active = Some(ready_now);
693                }
694
695                let max_in_stride = inputs
696                    .iter()
697                    .map(|inp| inp.stream.format().bytes_per_frame())
698                    .max()
699                    .unwrap_or(8)
700                    .max(8);
701                let pa_sub_watch = need_pa_proc_scan.then(|| PaSubWatch::spawn(&paths));
702
703                PlatformExecutionEngine::SoftwareMix {
704                    block_frames,
705                    multi,
706                    inputs,
707                    sub_topologies,
708                    opened_sink_inputs,
709                    pa_sub_watch,
710                    last_sink_input_scan: Instant::now(),
711                    started_at: Instant::now(),
712                    in_bytes_scratch: vec![0u8; MAX_FRAMES_PER_SLOT * max_in_stride],
713                    pulse_sub_f32: vec![0.0_f32; MAX_FRAMES_PER_SLOT * 2],
714                    pulse_sum_f32: vec![0.0_f32; MAX_FRAMES_PER_SLOT * 2],
715                    pulse_sum_bytes: vec![0u8; MAX_FRAMES_PER_SLOT * 8],
716                    drained_blocks: 0,
717                }
718            }
719            _ => return Err(CapabilityError::NotImplemented),
720        };
721
722        let final_plan =
723            resolve_linux_plan_with_readiness(&final_request, timing, pw_ready, pa_ready)
724                .unwrap_or(plan);
725        let default_observer = follow_out_backend
726            .map(|b| PlatformDefaultOutputObserver::acquire_for_backend(Some(b), paths.clone()));
727        let default_source_observer = follow_in_backend
728            .map(|b| PlatformDefaultInputObserver::acquire_for_backend(Some(b), paths.clone()));
729
730        Ok(Self {
731            request: final_request,
732            paths,
733            plan: final_plan,
734            policy,
735            timing,
736            pulse_server_kind,
737            budget,
738            cleanup_timeout,
739            engine,
740            route_guard,
741            default_cancel: Cancellation::default(),
742            last_metadata: None,
743            pending_boundary: None,
744            opened_default_device: initial_default_sink,
745            default_observer,
746            opened_default_source: initial_default_source,
747            default_source_observer,
748            last_default_check: Instant::now(),
749            session_counter: 1,
750            segment_counter: 1,
751            stopped: false,
752            terminal_error: None,
753            read_lock: Mutex::new(()),
754        })
755    }
756
757    pub fn budget(&self) -> &StorageBudget {
758        &self.budget
759    }
760
761    pub fn topology_controller(&self) -> Option<&PlatformTopologyController> {
762        match &self.engine {
763            PlatformExecutionEngine::PassThrough { topology, .. } => topology.as_ref(),
764            PlatformExecutionEngine::SoftwareMix { .. } => None,
765        }
766    }
767
768    #[cfg(any(test, feature = "native-tests"))]
769    pub fn open_with_paths(
770        request: CaptureRequest,
771        paths: LinuxClientPaths,
772        observed: bool,
773    ) -> Result<Self, CapabilityError> {
774        Self::open_impl(
775            request,
776            paths,
777            Overflow::DropOldest,
778            TimingRequirement::Raw,
779            observed,
780        )
781    }
782
783    #[cfg(any(test, feature = "native-tests"))]
784    pub fn pulse_server_kind(&self) -> Option<PulseServerKind> {
785        self.pulse_server_kind
786    }
787
788    #[cfg(any(test, feature = "native-tests"))]
789    pub fn from_synthetic_streams(
790        request: CaptureRequest,
791        streams: Vec<(BackendId, PlatformStream)>,
792        shared_budget: StorageBudget,
793    ) -> Result<Self, CapabilityError> {
794        let plan =
795            resolve_linux_plan_with_readiness(&request, TimingRequirement::Raw, Ok(()), Ok(()))?;
796        let cleanup_timeout = Duration::from_nanos(request.budgets().cleanup_timeout_ns);
797        let route_guard = RouteRollbackGuard::new(request.allow_reroute());
798        let engine = if matches!(plan.combine_resolution, CombineResolution::PassThrough(_))
799            && streams.len() == 1
800        {
801            let (_b, st) = streams.into_iter().next().unwrap();
802            PlatformExecutionEngine::PassThrough {
803                stream: Some(st),
804                topology: None,
805            }
806        } else {
807            let per_input_formats: Vec<(BackendId, Arc<Format>)> = streams
808                .iter()
809                .map(|(b, s)| (*b, s.format().clone()))
810                .collect();
811            let active = vec![true; streams.len()];
812            let max_in_stride = streams
813                .iter()
814                .map(|(_, s)| s.format().bytes_per_frame())
815                .max()
816                .unwrap_or(8)
817                .max(8);
818            let inputs: Vec<SoftwareMixInput> = streams
819                .into_iter()
820                .enumerate()
821                .map(|(idx, (b, s))| SoftwareMixInput::new_direct(idx, b, s))
822                .collect();
823            let (block_frames, multi) = match build_software_mix_multi(
824                request.clone(),
825                per_input_formats,
826                &active,
827                shared_budget.clone(),
828            ) {
829                Ok(pair) => pair,
830                Err(err) => {
831                    for inp in inputs {
832                        inp.stream.stop(Stop::Abort);
833                        let _ = inp.stream.wait_cleanup(cleanup_timeout);
834                    }
835                    return Err(err);
836                }
837            };
838            PlatformExecutionEngine::SoftwareMix {
839                block_frames,
840                multi,
841                inputs,
842                sub_topologies: Vec::new(),
843                opened_sink_inputs: BTreeSet::new(),
844                pa_sub_watch: None,
845                last_sink_input_scan: Instant::now(),
846                started_at: Instant::now(),
847                in_bytes_scratch: vec![0u8; MAX_FRAMES_PER_SLOT * max_in_stride],
848                pulse_sub_f32: vec![0.0_f32; MAX_FRAMES_PER_SLOT * 2],
849                pulse_sum_f32: vec![0.0_f32; MAX_FRAMES_PER_SLOT * 2],
850                pulse_sum_bytes: vec![0u8; MAX_FRAMES_PER_SLOT * 8],
851                drained_blocks: 0,
852            }
853        };
854        Ok(Self {
855            request,
856            paths: LinuxClientPaths::default(),
857            plan,
858            policy: Overflow::Fail,
859            timing: TimingRequirement::Raw,
860            pulse_server_kind: None,
861            budget: shared_budget,
862            cleanup_timeout,
863            engine,
864            route_guard,
865            default_cancel: Cancellation::default(),
866            last_metadata: None,
867            pending_boundary: None,
868            opened_default_device: None,
869            default_observer: None,
870            opened_default_source: None,
871            default_source_observer: None,
872            last_default_check: Instant::now(),
873            session_counter: 1,
874            segment_counter: 1,
875            stopped: false,
876            terminal_error: None,
877            read_lock: Mutex::new(()),
878        })
879    }
880
881    #[cfg(test)]
882    fn apply_opened_default_stream_for_test(
883        &mut self,
884        expected_kind: TargetKind,
885        next_stream: PlatformStream,
886    ) -> Result<bool, CapabilityError> {
887        if self.stopped || self.terminal_error.is_some() {
888            return Err(CapabilityError::Stopped);
889        }
890        match &mut self.engine {
891            PlatformExecutionEngine::PassThrough { stream, .. } => {
892                let target = self
893                    .request
894                    .targets()
895                    .first()
896                    .ok_or(CapabilityError::InvalidTarget)?;
897                if target.kind() != expected_kind
898                    || target.default_device_mode() != DefaultDeviceMode::Follow
899                {
900                    return Err(CapabilityError::InvalidTarget);
901                }
902                let old_pcm = stream.as_ref().map(|s| s.format().clone());
903                if let Some(old) = stream.take() {
904                    old.stop(Stop::Drain);
905                    let _ = old.wait_cleanup(self.cleanup_timeout);
906                }
907                if old_pcm
908                    .as_ref()
909                    .is_some_and(|prev| prev != next_stream.format())
910                    && self.request.on_format_change() == OnFormatChange::Fail
911                {
912                    next_stream.stop(Stop::Abort);
913                    let _ = next_stream.wait_cleanup(self.cleanup_timeout);
914                    self.terminal_error = Some(ManagerError::Unsupported);
915                    return Err(CapabilityError::FormatChangeRejected);
916                }
917                let next_fmt = next_stream.format().clone();
918                *stream = Some(next_stream);
919                self.session_counter = self.session_counter.saturating_add(1);
920                self.segment_counter = self.segment_counter.saturating_add(1);
921                self.pending_boundary = Some(SessionBoundary {
922                    session: self.session_counter,
923                    segment: self.segment_counter,
924                    kind: BoundaryKind::DeviceChanged,
925                    format: next_fmt,
926                    device_id: Some("synth-switched".into()),
927                    identity: None,
928                });
929                Ok(true)
930            }
931            PlatformExecutionEngine::SoftwareMix {
932                block_frames,
933                multi,
934                inputs,
935                in_bytes_scratch,
936                ..
937            } => {
938                let idx = self
939                    .request
940                    .targets()
941                    .iter()
942                    .position(|t| {
943                        t.kind() == expected_kind
944                            && t.default_device_mode() == DefaultDeviceMode::Follow
945                    })
946                    .ok_or(CapabilityError::InvalidTarget)?;
947                let old_pcm = inputs
948                    .iter()
949                    .find(|inp| inp.target_idx == idx)
950                    .map(|inp| inp.stream.format().clone())
951                    .or_else(|| {
952                        multi
953                            .input_handles()
954                            .get(idx)
955                            .map(|h| h.native_format().clone())
956                    });
957                if old_pcm
958                    .as_ref()
959                    .is_some_and(|prev| prev != next_stream.format())
960                    && self.request.on_format_change() == OnFormatChange::Fail
961                {
962                    next_stream.stop(Stop::Abort);
963                    let _ = next_stream.wait_cleanup(self.cleanup_timeout);
964                    self.terminal_error = Some(ManagerError::Unsupported);
965                    return Err(CapabilityError::FormatChangeRejected);
966                }
967                let stride = next_stream.format().bytes_per_frame();
968                if in_bytes_scratch.len() < MAX_FRAMES_PER_SLOT * stride {
969                    in_bytes_scratch.resize(MAX_FRAMES_PER_SLOT * stride, 0);
970                }
971                if let Some(inp) = inputs.iter_mut().find(|inp| inp.target_idx == idx) {
972                    inp.stream.stop(Stop::Drain);
973                    let _ = inp.stream.wait_cleanup(self.cleanup_timeout);
974                    inp.stream = next_stream;
975                    inp.last_active = Some(Instant::now());
976                    inp.eof = false;
977                }
978                let _ = multi.set_input_state(idx, ParticipationState::Active);
979                let fallback_fmt = multi.working_format().clone();
980                let per_input: Vec<(BackendId, Arc<Format>)> = (0..self.request.targets().len())
981                    .map(|t_idx| {
982                        let b = self.plan.target_plans[t_idx].resolved_backend;
983                        let fmt = inputs
984                            .iter()
985                            .find(|inp| inp.target_idx == t_idx)
986                            .map(|inp| inp.stream.format().clone())
987                            .unwrap_or_else(|| fallback_fmt.clone());
988                        (b, fmt)
989                    })
990                    .collect();
991                match multi.reconfigure_targets_with_formats(
992                    self.request.targets().to_vec(),
993                    per_input.clone(),
994                ) {
995                    Ok(_) => {}
996                    Err(ManagerError::WorkingFormatChanged) => {
997                        let active: Vec<bool> = (0..self.request.targets().len())
998                            .map(|t_idx| {
999                                inputs.iter().any(|inp| inp.target_idx == t_idx && !inp.eof)
1000                            })
1001                            .collect();
1002                        let (new_bf, new_multi) = build_software_mix_multi(
1003                            self.request.clone(),
1004                            per_input,
1005                            &active,
1006                            self.budget.clone(),
1007                        )?;
1008                        *block_frames = new_bf;
1009                        *multi = new_multi;
1010                    }
1011                    Err(err) => {
1012                        self.terminal_error = Some(err);
1013                        return Err(CapabilityError::from(err));
1014                    }
1015                }
1016                self.segment_counter = self.segment_counter.saturating_add(1);
1017                Ok(true)
1018            }
1019        }
1020    }
1021
1022    fn refresh_default_observers(&mut self) {
1023        let follow_out = self
1024            .request
1025            .targets()
1026            .iter()
1027            .enumerate()
1028            .find(|(_, t)| {
1029                t.kind() == TargetKind::DefaultOutput
1030                    && t.default_device_mode() == DefaultDeviceMode::Follow
1031            })
1032            .map(|(idx, _)| self.plan.target_plans[idx].resolved_backend);
1033        if let Some(b) = follow_out {
1034            if self.default_observer.is_none() {
1035                self.default_observer = Some(PlatformDefaultOutputObserver::acquire_for_backend(
1036                    Some(b),
1037                    self.paths.clone(),
1038                ));
1039            }
1040        } else {
1041            self.default_observer = None;
1042        }
1043
1044        let follow_in = self
1045            .request
1046            .targets()
1047            .iter()
1048            .enumerate()
1049            .find(|(_, t)| {
1050                t.kind() == TargetKind::DefaultInput
1051                    && t.default_device_mode() == DefaultDeviceMode::Follow
1052            })
1053            .map(|(idx, _)| self.plan.target_plans[idx].resolved_backend);
1054        if let Some(b) = follow_in {
1055            if self.default_source_observer.is_none() {
1056                self.default_source_observer = Some(
1057                    PlatformDefaultInputObserver::acquire_for_backend(Some(b), self.paths.clone()),
1058                );
1059            }
1060        } else {
1061            self.default_source_observer = None;
1062        }
1063    }
1064
1065    fn update_targets_impl(
1066        &mut self,
1067        mut new_targets: Vec<CaptureTarget>,
1068    ) -> Result<u64, CapabilityError> {
1069        if self.stopped || self.terminal_error.is_some() {
1070            return Err(CapabilityError::Stopped);
1071        }
1072        validate_linux_process_targets(&new_targets)?;
1073
1074        let pw_ready = probe_pipewire_server(&self.paths).map(|_| ());
1075        let pa_probe = probe_pulse_server(&self.paths);
1076        let pa_ready = pa_probe.as_ref().map(|_| ()).map_err(Clone::clone);
1077        let candidate_req = self.request.clone().with_targets(new_targets.clone());
1078        let new_plan = resolve_linux_plan_with_readiness(
1079            &candidate_req,
1080            self.timing,
1081            pw_ready.clone(),
1082            pa_ready.clone(),
1083        )?;
1084
1085        if let PlatformExecutionEngine::PassThrough {
1086            topology: Some(topo),
1087            ..
1088        } = &mut self.engine
1089            && matches!(
1090                new_plan.combine_resolution,
1091                CombineResolution::SharedNativeGraphMix(BackendId::PipeWire)
1092                    | CombineResolution::PassThrough(BackendId::PipeWire)
1093            )
1094            && new_targets
1095                .iter()
1096                .all(|t| matches!(t.kind(), TargetKind::Process | TargetKind::Application))
1097            && self.request.output_converter().is_none()
1098        {
1099            topo.update_targets(new_targets.clone())?;
1100            self.request = self.request.clone().with_targets(new_targets);
1101            self.plan = new_plan;
1102            self.segment_counter = self.segment_counter.saturating_add(1);
1103            return Ok(self.segment_counter);
1104        }
1105
1106        if let PlatformExecutionEngine::SoftwareMix {
1107            block_frames,
1108            multi,
1109            inputs,
1110            sub_topologies,
1111            opened_sink_inputs,
1112            pa_sub_watch,
1113            in_bytes_scratch,
1114            ..
1115        } = &mut self.engine
1116            && new_plan.combine_resolution == CombineResolution::CspaMixer
1117        {
1118            for (idx, t) in new_targets.iter_mut().enumerate() {
1119                resolve_pinned_linux_target(
1120                    t,
1121                    new_plan.target_plans[idx].resolved_backend,
1122                    &self.paths,
1123                );
1124            }
1125
1126            let old_targets = self.request.targets();
1127            let old_handles = multi.input_handles();
1128            let mut old_used = vec![false; old_targets.len()];
1129            let mut planned_old_slot: Vec<Option<usize>> = Vec::with_capacity(new_targets.len());
1130            for (new_idx, t) in new_targets.iter().enumerate() {
1131                let want_backend = new_plan.target_plans[new_idx].resolved_backend;
1132                let mut found = None;
1133                for (old_idx, old_t) in old_targets.iter().enumerate() {
1134                    let old_alive = old_handles
1135                        .get(old_idx)
1136                        .and_then(InputStatusHandle::snapshot)
1137                        .is_none_or(|s| {
1138                            !matches!(
1139                                s.participation_state,
1140                                ParticipationState::Exited | ParticipationState::Failed(_)
1141                            )
1142                        });
1143                    if !old_used[old_idx]
1144                        && old_alive
1145                        && old_t.id() == t.id()
1146                        && old_t.scope() == t.scope()
1147                        && self.plan.target_plans[old_idx].resolved_backend == want_backend
1148                    {
1149                        old_used[old_idx] = true;
1150                        found = Some(old_idx);
1151                        break;
1152                    }
1153                }
1154                planned_old_slot.push(found);
1155            }
1156
1157            let fallback_fmt = multi.working_format().clone();
1158            let any_new_pa_proc = new_targets.iter().enumerate().any(|(idx, t)| {
1159                new_plan.target_plans[idx].resolved_backend == BackendId::PulseAudio
1160                    && matches!(t.kind(), TargetKind::Process | TargetKind::Application)
1161            });
1162            let need_pa_proc_scan = new_targets.iter().enumerate().any(|(idx, t)| {
1163                planned_old_slot[idx].is_none()
1164                    && new_plan.target_plans[idx].resolved_backend == BackendId::PulseAudio
1165                    && matches!(t.kind(), TargetKind::Process | TargetKind::Application)
1166            });
1167            let (sink_inputs, proc_map) = if need_pa_proc_scan {
1168                let (_devs, _pids, si) = collect_pulse_state(&self.paths)?;
1169                let pm = collect_proc_stat_table(Path::new("/proc"))?;
1170                (si, pm)
1171            } else {
1172                (Vec::new(), BTreeMap::new())
1173            };
1174
1175            let mut newly_opened_inputs: Vec<SoftwareMixInput> = Vec::new();
1176            let mut newly_opened_topos: Vec<(usize, PlatformTopologyController)> = Vec::new();
1177            let mut newly_opened_si: BTreeSet<(usize, u32)> = BTreeSet::new();
1178            let mut new_per_input_formats: Vec<(BackendId, Arc<Format>)> =
1179                Vec::with_capacity(new_targets.len());
1180            let mut new_slot_active: Vec<bool> = vec![false; new_targets.len()];
1181
1182            for (new_idx, target) in new_targets.iter().enumerate() {
1183                let t_backend = new_plan.target_plans[new_idx].resolved_backend;
1184                if let Some(old_idx) = planned_old_slot[new_idx] {
1185                    let old_fmt = inputs
1186                        .iter()
1187                        .find(|inp| inp.target_idx == old_idx)
1188                        .map(|inp| inp.stream.format().clone())
1189                        .or_else(|| {
1190                            multi
1191                                .input_handles()
1192                                .get(old_idx)
1193                                .map(|h| h.native_format().clone())
1194                        })
1195                        .unwrap_or_else(|| fallback_fmt.clone());
1196                    new_per_input_formats.push((t_backend, old_fmt));
1197                    new_slot_active[new_idx] = inputs
1198                        .iter()
1199                        .any(|inp| inp.target_idx == old_idx && !inp.eof);
1200                    continue;
1201                }
1202
1203                let open_res: Result<Arc<Format>, CapabilityError> = (|| {
1204                    let _ticket = multi
1205                        .acquire_pending_open()
1206                        .map_err(CapabilityError::from)?;
1207                    match (t_backend, target.kind()) {
1208                        (BackendId::PipeWire, TargetKind::Device | TargetKind::DefaultOutput) => {
1209                            let dev = clean_target_device_id(target).or_else(|| {
1210                                query_linux_default_sink_now(BackendId::PipeWire, &self.paths)
1211                            });
1212                            let stream = open_pipewire_point(
1213                                &self.paths,
1214                                dev.as_deref(),
1215                                true,
1216                                self.policy,
1217                                self.timing,
1218                                multi.storage_budget(),
1219                                false,
1220                            )?;
1221                            let fmt = stream.format().clone();
1222                            new_slot_active[new_idx] = true;
1223                            newly_opened_inputs.push(SoftwareMixInput::new_direct(
1224                                new_idx,
1225                                t_backend,
1226                                PlatformStream::PipeWire(stream),
1227                            ));
1228                            Ok(fmt)
1229                        }
1230                        (
1231                            BackendId::PipeWire,
1232                            TargetKind::InputDevice | TargetKind::DefaultInput,
1233                        ) => {
1234                            let src = clean_target_device_id(target);
1235                            let stream = open_pipewire_source_point(
1236                                &self.paths,
1237                                src.as_deref(),
1238                                None,
1239                                self.policy,
1240                                self.timing,
1241                                multi.storage_budget(),
1242                                false,
1243                            )?;
1244                            let fmt = stream.format().clone();
1245                            new_slot_active[new_idx] = true;
1246                            newly_opened_inputs.push(SoftwareMixInput::new_direct(
1247                                new_idx,
1248                                t_backend,
1249                                PlatformStream::PipeWire(stream),
1250                            ));
1251                            Ok(fmt)
1252                        }
1253                        (BackendId::PipeWire, TargetKind::Process | TargetKind::Application) => {
1254                            let single_topo = start_pipewire_topology_controller(
1255                                &self.paths,
1256                                vec![target.clone()],
1257                                self.request.budgets().max_native_graph_links,
1258                            )?;
1259                            let stream = match open_pipewire_point(
1260                                &self.paths,
1261                                Some(single_topo.sink_name()),
1262                                true,
1263                                self.policy,
1264                                self.timing,
1265                                multi.storage_budget(),
1266                                false,
1267                            ) {
1268                                Ok(s) => s,
1269                                Err(err) => {
1270                                    single_topo.shutdown();
1271                                    return Err(err);
1272                                }
1273                            };
1274                            let fmt = stream.format().clone();
1275                            new_slot_active[new_idx] = true;
1276                            newly_opened_topos.push((new_idx, single_topo));
1277                            newly_opened_inputs.push(SoftwareMixInput::new_direct(
1278                                new_idx,
1279                                t_backend,
1280                                PlatformStream::PipeWire(stream),
1281                            ));
1282                            Ok(fmt)
1283                        }
1284                        (BackendId::PulseAudio, TargetKind::Device | TargetKind::DefaultOutput) => {
1285                            let dev = clean_target_device_id(target);
1286                            let stream = open_pulse_point(
1287                                &self.paths,
1288                                dev.as_deref(),
1289                                None,
1290                                self.policy,
1291                                self.timing,
1292                                multi.storage_budget(),
1293                                false,
1294                            )?;
1295                            let fmt = stream.format().clone();
1296                            new_slot_active[new_idx] = true;
1297                            newly_opened_inputs.push(SoftwareMixInput::new_direct(
1298                                new_idx,
1299                                t_backend,
1300                                PlatformStream::Pulse(stream),
1301                            ));
1302                            Ok(fmt)
1303                        }
1304                        (
1305                            BackendId::PulseAudio,
1306                            TargetKind::InputDevice | TargetKind::DefaultInput,
1307                        ) => {
1308                            let src = clean_target_device_id(target);
1309                            let stream = open_pulse_source_point(
1310                                &self.paths,
1311                                src.as_deref(),
1312                                None,
1313                                self.policy,
1314                                self.timing,
1315                                multi.storage_budget(),
1316                                false,
1317                            )?;
1318                            let fmt = stream.format().clone();
1319                            new_slot_active[new_idx] = true;
1320                            newly_opened_inputs.push(SoftwareMixInput::new_direct(
1321                                new_idx,
1322                                t_backend,
1323                                PlatformStream::Pulse(stream),
1324                            ));
1325                            Ok(fmt)
1326                        }
1327                        (BackendId::PulseAudio, TargetKind::Process | TargetKind::Application) => {
1328                            let root_pid = target.pid().ok_or(CapabilityError::InvalidTarget)?;
1329                            let root_id = ProcessIdentity {
1330                                pid: root_pid,
1331                                generation: target.process_start_time().unwrap_or(0),
1332                            };
1333                            let exact_only = target.scope() == ProcessScope::Exact;
1334                            let mut matched_any = false;
1335                            for si in &sink_inputs {
1336                                if let Some(si_pid) = si.pid
1337                                    && pid_belongs_to_target(
1338                                        &proc_map, root_id, exact_only, si_pid,
1339                                    )?
1340                                {
1341                                    let stream = open_pulse_point(
1342                                        &self.paths,
1343                                        None,
1344                                        Some(si.index),
1345                                        self.policy,
1346                                        self.timing,
1347                                        multi.storage_budget(),
1348                                        false,
1349                                    )?;
1350                                    newly_opened_si.insert((new_idx, si.index));
1351                                    newly_opened_inputs.push(
1352                                        SoftwareMixInput::new_pulse_substream(
1353                                            new_idx,
1354                                            t_backend,
1355                                            PlatformStream::Pulse(stream),
1356                                        )?,
1357                                    );
1358                                    matched_any = true;
1359                                }
1360                            }
1361                            new_slot_active[new_idx] = matched_any;
1362                            Ok(fallback_fmt.clone())
1363                        }
1364                        _ => Err(CapabilityError::InvalidBackend),
1365                    }
1366                })();
1367
1368                match open_res {
1369                    Ok(fmt) => new_per_input_formats.push((t_backend, fmt)),
1370                    Err(err) => {
1371                        for (_, topo) in newly_opened_topos {
1372                            topo.shutdown();
1373                        }
1374                        for inp in newly_opened_inputs {
1375                            inp.stream.stop(Stop::Abort);
1376                            let _ = inp.stream.wait_cleanup(self.cleanup_timeout);
1377                        }
1378                        return Err(err);
1379                    }
1380                }
1381            }
1382
1383            let mut format_promoted = false;
1384            let resolved_slot_map = match multi.reconfigure_targets_with_formats(
1385                new_targets.clone(),
1386                new_per_input_formats.clone(),
1387            ) {
1388                Ok(mapping) => mapping,
1389                Err(ManagerError::WorkingFormatChanged) => {
1390                    if self.request.on_format_change() == OnFormatChange::Fail {
1391                        for (_, topo) in newly_opened_topos {
1392                            topo.shutdown();
1393                        }
1394                        for inp in newly_opened_inputs {
1395                            inp.stream.stop(Stop::Abort);
1396                            let _ = inp.stream.wait_cleanup(self.cleanup_timeout);
1397                        }
1398                        return Err(CapabilityError::FormatChangeRejected);
1399                    }
1400                    let rebuilt_req = self.request.clone().with_targets(new_targets.clone());
1401                    match build_software_mix_multi(
1402                        rebuilt_req,
1403                        new_per_input_formats,
1404                        &new_slot_active,
1405                        self.budget.clone(),
1406                    ) {
1407                        Ok((new_bf, new_multi)) => {
1408                            *block_frames = new_bf;
1409                            *multi = new_multi;
1410                            self.session_counter = self.session_counter.saturating_add(1);
1411                            format_promoted = true;
1412                            planned_old_slot
1413                        }
1414                        Err(err) => {
1415                            for (_, topo) in newly_opened_topos {
1416                                topo.shutdown();
1417                            }
1418                            for inp in newly_opened_inputs {
1419                                inp.stream.stop(Stop::Abort);
1420                                let _ = inp.stream.wait_cleanup(self.cleanup_timeout);
1421                            }
1422                            return Err(err);
1423                        }
1424                    }
1425                }
1426                Err(err) => {
1427                    for (_, topo) in newly_opened_topos {
1428                        topo.shutdown();
1429                    }
1430                    for inp in newly_opened_inputs {
1431                        inp.stream.stop(Stop::Abort);
1432                        let _ = inp.stream.wait_cleanup(self.cleanup_timeout);
1433                    }
1434                    return Err(CapabilityError::from(err));
1435                }
1436            };
1437
1438            let mut old_to_new: BTreeMap<usize, usize> = BTreeMap::new();
1439            for (new_idx, mapped_old) in resolved_slot_map.iter().enumerate() {
1440                if let Some(old_idx) = *mapped_old {
1441                    old_to_new.insert(old_idx, new_idx);
1442                }
1443            }
1444
1445            let mut next_inputs = Vec::new();
1446            for mut inp in inputs.drain(..) {
1447                if let Some(&new_idx) = old_to_new.get(&inp.target_idx) {
1448                    inp.target_idx = new_idx;
1449                    next_inputs.push(inp);
1450                } else {
1451                    inp.stream.stop(Stop::Drain);
1452                    let _ = inp.stream.wait_cleanup(self.cleanup_timeout);
1453                }
1454            }
1455            let ready_now = Instant::now();
1456            for inp in &mut newly_opened_inputs {
1457                inp.last_active = Some(ready_now);
1458            }
1459            next_inputs.extend(newly_opened_inputs);
1460            let max_in_stride = next_inputs
1461                .iter()
1462                .map(|inp| inp.stream.format().bytes_per_frame())
1463                .max()
1464                .unwrap_or(8)
1465                .max(8);
1466            if in_bytes_scratch.len() < MAX_FRAMES_PER_SLOT * max_in_stride {
1467                in_bytes_scratch.resize(MAX_FRAMES_PER_SLOT * max_in_stride, 0);
1468            }
1469            *inputs = next_inputs;
1470
1471            if any_new_pa_proc {
1472                if pa_sub_watch.is_none() {
1473                    *pa_sub_watch = Some(PaSubWatch::spawn(&self.paths));
1474                }
1475            } else if let Some(mut watch) = pa_sub_watch.take() {
1476                watch.stop_and_join();
1477            }
1478
1479            let mut next_topos = Vec::new();
1480            for (old_idx, topo) in sub_topologies.drain(..) {
1481                if let Some(&new_idx) = old_to_new.get(&old_idx) {
1482                    next_topos.push((new_idx, topo));
1483                } else {
1484                    topo.shutdown();
1485                }
1486            }
1487            next_topos.extend(newly_opened_topos);
1488            *sub_topologies = next_topos;
1489
1490            let mut next_sink_inputs = BTreeSet::new();
1491            for &(old_idx, si_idx) in opened_sink_inputs.iter() {
1492                if let Some(&new_idx) = old_to_new.get(&old_idx) {
1493                    next_sink_inputs.insert((new_idx, si_idx));
1494                }
1495            }
1496            next_sink_inputs.extend(newly_opened_si);
1497            *opened_sink_inputs = next_sink_inputs;
1498
1499            for (new_idx, &is_act) in new_slot_active.iter().enumerate() {
1500                let st = if is_act {
1501                    ParticipationState::Active
1502                } else {
1503                    ParticipationState::Idle
1504                };
1505                let _ = multi.set_input_state(new_idx, st);
1506            }
1507
1508            let next_out_fmt = multi.output_format().clone();
1509            let next_req = self.request.clone().with_targets(new_targets);
1510            self.plan =
1511                resolve_linux_plan_with_readiness(&next_req, self.timing, pw_ready, pa_ready)
1512                    .unwrap_or(new_plan);
1513            self.request = next_req;
1514            self.refresh_default_observers();
1515            self.segment_counter = self.segment_counter.saturating_add(1);
1516            if format_promoted {
1517                self.pending_boundary = Some(SessionBoundary {
1518                    session: self.session_counter,
1519                    segment: self.segment_counter,
1520                    kind: BoundaryKind::FormatChanged,
1521                    format: next_out_fmt,
1522                    device_id: None,
1523                    identity: None,
1524                });
1525            }
1526            return Ok(self.segment_counter);
1527        }
1528
1529        let candidate_req = self.request.clone().with_targets(new_targets);
1530        let mut replacement = Self::open_impl(
1531            candidate_req,
1532            self.paths.clone(),
1533            self.policy,
1534            self.timing,
1535            false,
1536        )?;
1537        std::mem::swap(&mut self.engine, &mut replacement.engine);
1538        replacement.stop(Stop::Drain);
1539        let _ = replacement.wait_cleanup(self.cleanup_timeout);
1540        self.request = replacement.request.clone();
1541        self.plan = replacement.plan.clone();
1542        self.pulse_server_kind = replacement.pulse_server_kind;
1543        self.default_observer = replacement.default_observer.take();
1544        self.opened_default_device = replacement.opened_default_device.take();
1545        self.default_source_observer = replacement.default_source_observer.take();
1546        self.opened_default_source = replacement.opened_default_source.take();
1547        self.session_counter = self.session_counter.saturating_add(1);
1548        self.segment_counter = self.segment_counter.saturating_add(1);
1549        if let PlatformExecutionEngine::PassThrough {
1550            stream: Some(st), ..
1551        } = &self.engine
1552        {
1553            self.pending_boundary = Some(SessionBoundary {
1554                session: self.session_counter,
1555                segment: self.segment_counter,
1556                kind: BoundaryKind::ConfigurationChanged,
1557                format: st.format().clone(),
1558                device_id: self
1559                    .request
1560                    .targets()
1561                    .first()
1562                    .and_then(|t| t.device_id().cloned()),
1563                identity: self
1564                    .request
1565                    .targets()
1566                    .first()
1567                    .and_then(CaptureTarget::process_identity),
1568            });
1569        }
1570        Ok(self.segment_counter)
1571    }
1572
1573    fn notify_default_flow_changed(
1574        &mut self,
1575        expected_kind: TargetKind,
1576        new_device_id: Option<&str>,
1577    ) -> Result<bool, CapabilityError> {
1578        if self.stopped || self.terminal_error.is_some() {
1579            return Err(CapabilityError::Stopped);
1580        }
1581        let is_input = expected_kind == TargetKind::DefaultInput;
1582        let follow_idx = self
1583            .request
1584            .targets()
1585            .iter()
1586            .position(|t| {
1587                t.kind() == expected_kind && t.default_device_mode() == DefaultDeviceMode::Follow
1588            })
1589            .ok_or(CapabilityError::InvalidTarget)?;
1590        let primary_backend = self.plan.target_plans[follow_idx].resolved_backend;
1591
1592        let resolved_id = match new_device_id {
1593            Some(id) => id.to_owned(),
1594            None if is_input => query_linux_default_source_now(primary_backend, &self.paths)
1595                .ok_or(CapabilityError::ServerUnavailable)?,
1596            None => query_linux_default_sink_now(primary_backend, &self.paths)
1597                .ok_or(CapabilityError::ServerUnavailable)?,
1598        };
1599
1600        match &mut self.engine {
1601            PlatformExecutionEngine::PassThrough { stream, .. } => {
1602                if self.request.targets().len() != 1
1603                    || self.request.targets()[0].kind() != expected_kind
1604                {
1605                    return Err(CapabilityError::InvalidTarget);
1606                }
1607                let t_backend = self.plan.target_plans[0].resolved_backend;
1608                let old_pcm = stream.as_ref().map(|s| s.format().clone());
1609                if let Some(old) = stream.take() {
1610                    old.stop(Stop::Drain);
1611                    let _ = old.wait_cleanup(self.cleanup_timeout);
1612                }
1613
1614                let next_stream = match (t_backend, is_input) {
1615                    (BackendId::PipeWire, false) => PlatformStream::PipeWire(open_pipewire_point(
1616                        &self.paths,
1617                        Some(&resolved_id),
1618                        true,
1619                        self.policy,
1620                        self.timing,
1621                        &self.budget,
1622                        false,
1623                    )?),
1624                    (BackendId::PipeWire, true) => {
1625                        PlatformStream::PipeWire(open_pipewire_source_point(
1626                            &self.paths,
1627                            Some(&resolved_id),
1628                            None,
1629                            self.policy,
1630                            self.timing,
1631                            &self.budget,
1632                            false,
1633                        )?)
1634                    }
1635                    (BackendId::PulseAudio, false) => PlatformStream::Pulse(open_pulse_point(
1636                        &self.paths,
1637                        Some(&resolved_id),
1638                        None,
1639                        self.policy,
1640                        self.timing,
1641                        &self.budget,
1642                        false,
1643                    )?),
1644                    (BackendId::PulseAudio, true) => {
1645                        PlatformStream::Pulse(open_pulse_source_point(
1646                            &self.paths,
1647                            Some(&resolved_id),
1648                            None,
1649                            self.policy,
1650                            self.timing,
1651                            &self.budget,
1652                            false,
1653                        )?)
1654                    }
1655                    _ => return Err(CapabilityError::InvalidBackend),
1656                };
1657
1658                if old_pcm
1659                    .as_ref()
1660                    .is_some_and(|prev| prev != next_stream.format())
1661                    && self.request.on_format_change() == OnFormatChange::Fail
1662                {
1663                    next_stream.stop(Stop::Abort);
1664                    let _ = next_stream.wait_cleanup(self.cleanup_timeout);
1665                    self.terminal_error = Some(ManagerError::Unsupported);
1666                    return Err(CapabilityError::FormatChangeRejected);
1667                }
1668
1669                let next_fmt = next_stream.format().clone();
1670                *stream = Some(next_stream);
1671                if is_input {
1672                    self.opened_default_source = Some(resolved_id.clone());
1673                } else {
1674                    self.opened_default_device = Some(resolved_id.clone());
1675                }
1676                self.session_counter = self.session_counter.saturating_add(1);
1677                self.segment_counter = self.segment_counter.saturating_add(1);
1678                self.pending_boundary = Some(SessionBoundary {
1679                    session: self.session_counter,
1680                    segment: self.segment_counter,
1681                    kind: BoundaryKind::DeviceChanged,
1682                    format: next_fmt,
1683                    device_id: Some(resolved_id.into()),
1684                    identity: None,
1685                });
1686                Ok(true)
1687            }
1688            PlatformExecutionEngine::SoftwareMix {
1689                block_frames,
1690                multi,
1691                inputs,
1692                in_bytes_scratch,
1693                ..
1694            } => {
1695                let mut switched = false;
1696                for inp in inputs.iter_mut() {
1697                    let Some(target) = self.request.targets().get(inp.target_idx) else {
1698                        continue;
1699                    };
1700                    if target.kind() != expected_kind
1701                        || target.default_device_mode() != DefaultDeviceMode::Follow
1702                    {
1703                        continue;
1704                    }
1705                    let old_pcm = inp.stream.format().clone();
1706                    inp.stream.stop(Stop::Drain);
1707                    let _ = inp.stream.wait_cleanup(self.cleanup_timeout);
1708                    let _ticket = multi
1709                        .acquire_pending_open()
1710                        .map_err(CapabilityError::from)?;
1711                    let next_stream = match (inp.backend, is_input) {
1712                        (BackendId::PipeWire, false) => {
1713                            PlatformStream::PipeWire(open_pipewire_point(
1714                                &self.paths,
1715                                Some(&resolved_id),
1716                                true,
1717                                self.policy,
1718                                self.timing,
1719                                multi.storage_budget(),
1720                                false,
1721                            )?)
1722                        }
1723                        (BackendId::PipeWire, true) => {
1724                            PlatformStream::PipeWire(open_pipewire_source_point(
1725                                &self.paths,
1726                                Some(&resolved_id),
1727                                None,
1728                                self.policy,
1729                                self.timing,
1730                                multi.storage_budget(),
1731                                false,
1732                            )?)
1733                        }
1734                        (BackendId::PulseAudio, false) => PlatformStream::Pulse(open_pulse_point(
1735                            &self.paths,
1736                            Some(&resolved_id),
1737                            None,
1738                            self.policy,
1739                            self.timing,
1740                            multi.storage_budget(),
1741                            false,
1742                        )?),
1743                        (BackendId::PulseAudio, true) => {
1744                            PlatformStream::Pulse(open_pulse_source_point(
1745                                &self.paths,
1746                                Some(&resolved_id),
1747                                None,
1748                                self.policy,
1749                                self.timing,
1750                                multi.storage_budget(),
1751                                false,
1752                            )?)
1753                        }
1754                        _ => return Err(CapabilityError::InvalidBackend),
1755                    };
1756                    if &old_pcm != next_stream.format()
1757                        && self.request.on_format_change() == OnFormatChange::Fail
1758                    {
1759                        next_stream.stop(Stop::Abort);
1760                        let _ = next_stream.wait_cleanup(self.cleanup_timeout);
1761                        self.terminal_error = Some(ManagerError::Unsupported);
1762                        return Err(CapabilityError::FormatChangeRejected);
1763                    }
1764                    let stride = next_stream.format().bytes_per_frame();
1765                    if in_bytes_scratch.len() < MAX_FRAMES_PER_SLOT * stride {
1766                        in_bytes_scratch.resize(MAX_FRAMES_PER_SLOT * stride, 0);
1767                    }
1768                    inp.stream = next_stream;
1769                    inp.last_active = Some(Instant::now());
1770                    inp.eof = false;
1771                    let _ = multi.set_input_state(inp.target_idx, ParticipationState::Active);
1772                    switched = true;
1773                }
1774                if switched {
1775                    let fallback_fmt = multi.working_format().clone();
1776                    let per_input: Vec<(BackendId, Arc<Format>)> =
1777                        (0..self.request.targets().len())
1778                            .map(|idx| {
1779                                let b = self.plan.target_plans[idx].resolved_backend;
1780                                let fmt = inputs
1781                                    .iter()
1782                                    .find(|inp| inp.target_idx == idx)
1783                                    .map(|inp| inp.stream.format().clone())
1784                                    .unwrap_or_else(|| fallback_fmt.clone());
1785                                (b, fmt)
1786                            })
1787                            .collect();
1788                    match multi.reconfigure_targets_with_formats(
1789                        self.request.targets().to_vec(),
1790                        per_input.clone(),
1791                    ) {
1792                        Ok(_) => {}
1793                        Err(ManagerError::WorkingFormatChanged) => {
1794                            let active: Vec<bool> = (0..self.request.targets().len())
1795                                .map(|idx| {
1796                                    inputs.iter().any(|inp| inp.target_idx == idx && !inp.eof)
1797                                })
1798                                .collect();
1799                            let (new_bf, new_multi) = build_software_mix_multi(
1800                                self.request.clone(),
1801                                per_input,
1802                                &active,
1803                                self.budget.clone(),
1804                            )?;
1805                            *block_frames = new_bf;
1806                            *multi = new_multi;
1807                        }
1808                        Err(err) => {
1809                            self.terminal_error = Some(err);
1810                            return Err(CapabilityError::from(err));
1811                        }
1812                    }
1813                    if is_input {
1814                        self.opened_default_source = Some(resolved_id);
1815                    } else {
1816                        self.opened_default_device = Some(resolved_id);
1817                    }
1818                    self.segment_counter = self.segment_counter.saturating_add(1);
1819                }
1820                Ok(switched)
1821            }
1822        }
1823    }
1824
1825    fn reopen_relaunched_target_impl(
1826        &mut self,
1827        target_index: usize,
1828        new_pid: u32,
1829    ) -> Result<(), CapabilityError> {
1830        if self.stopped || self.terminal_error.is_some() {
1831            return Err(CapabilityError::Stopped);
1832        }
1833        let target = self
1834            .request
1835            .targets()
1836            .get(target_index)
1837            .cloned()
1838            .ok_or(CapabilityError::InvalidTarget)?;
1839        let OnRootExit::Wait { .. } = target.on_root_exit() else {
1840            return Err(CapabilityError::InvalidTarget);
1841        };
1842        let old_id = target
1843            .process_identity()
1844            .ok_or(CapabilityError::InvalidTarget)?;
1845        let (cand_id, cand_exe) = inspect_process_executable(new_pid)?;
1846        if cand_id == old_id || cand_id.generation <= old_id.generation {
1847            return Err(CapabilityError::PidReused);
1848        }
1849        if let Some(expected_exe) = target.executable_path()
1850            && expected_exe.as_ref() != cand_exe.as_str()
1851        {
1852            return Err(CapabilityError::InvalidTarget);
1853        }
1854        let updated_target = target.with_process_identity(cand_id)?;
1855        let mut next_targets = self.request.targets().to_vec();
1856        next_targets[target_index] = updated_target;
1857        let _ = self.update_targets_impl(next_targets)?;
1858        Ok(())
1859    }
1860
1861    fn poll_default_device_follow(&mut self) {
1862        if self.stopped
1863            || self.terminal_error.is_some()
1864            || self.pending_boundary.is_some()
1865            || self.last_default_check.elapsed() < Duration::from_millis(200)
1866        {
1867            return;
1868        }
1869        self.last_default_check = Instant::now();
1870        let next_sink = self
1871            .default_observer
1872            .as_ref()
1873            .and_then(|obs| obs.changed_from(self.opened_default_device.as_deref()));
1874        if let Some(current_default) = next_sink {
1875            let _ =
1876                self.notify_default_flow_changed(TargetKind::DefaultOutput, Some(&current_default));
1877        }
1878        let next_src = self
1879            .default_source_observer
1880            .as_ref()
1881            .and_then(|obs| obs.changed_from(self.opened_default_source.as_deref()));
1882        if let Some(current_src) = next_src {
1883            let _ = self.notify_default_flow_changed(TargetKind::DefaultInput, Some(&current_src));
1884        }
1885    }
1886
1887    fn drain_software_mix_inputs(&mut self, timeout: Duration, cancel: &Cancellation) -> u64 {
1888        let req_ref = &self.request;
1889        let plan_ref = &self.plan;
1890        let paths_ref = &self.paths;
1891        let policy = self.policy;
1892        let timing = self.timing;
1893        let PlatformExecutionEngine::SoftwareMix {
1894            block_frames,
1895            multi,
1896            inputs,
1897            opened_sink_inputs,
1898            pa_sub_watch,
1899            last_sink_input_scan,
1900            started_at,
1901            in_bytes_scratch,
1902            pulse_sub_f32,
1903            pulse_sum_f32,
1904            pulse_sum_bytes,
1905            drained_blocks,
1906            ..
1907        } = &mut self.engine
1908        else {
1909            return 0;
1910        };
1911
1912        for inp in inputs.iter() {
1913            inp.stream.arm();
1914        }
1915
1916        let should_scan_pa = match pa_sub_watch.as_ref() {
1917            Some(watch) if watch.join.is_some() => watch.dirty.swap(false, SeqCst),
1918            Some(_) => last_sink_input_scan.elapsed() >= Duration::from_millis(150),
1919            None => false,
1920        };
1921        if should_scan_pa {
1922            *last_sink_input_scan = Instant::now();
1923            if let Ok((_devs, _pids, sink_inputs)) = collect_pulse_state(paths_ref)
1924                && let Ok(proc_map) = collect_proc_stat_table(Path::new("/proc"))
1925            {
1926                for (t_idx, target) in req_ref.targets().iter().enumerate() {
1927                    if plan_ref.target_plans[t_idx].resolved_backend == BackendId::PulseAudio
1928                        && matches!(target.kind(), TargetKind::Process | TargetKind::Application)
1929                        && let Some(root_pid) = target.pid()
1930                    {
1931                        let root_id = ProcessIdentity {
1932                            pid: root_pid,
1933                            generation: target.process_start_time().unwrap_or(0),
1934                        };
1935                        let exact_only = target.scope() == ProcessScope::Exact;
1936                        for si in &sink_inputs {
1937                            if !opened_sink_inputs.contains(&(t_idx, si.index))
1938                                && let Some(si_pid) = si.pid
1939                                && pid_belongs_to_target(&proc_map, root_id, exact_only, si_pid)
1940                                    == Ok(true)
1941                                && let Ok(stream) = open_pulse_point(
1942                                    paths_ref,
1943                                    None,
1944                                    Some(si.index),
1945                                    policy,
1946                                    timing,
1947                                    multi.storage_budget(),
1948                                    false,
1949                                )
1950                                && let Ok(inp) = SoftwareMixInput::new_pulse_substream(
1951                                    t_idx,
1952                                    BackendId::PulseAudio,
1953                                    PlatformStream::Pulse(stream),
1954                                )
1955                            {
1956                                opened_sink_inputs.insert((t_idx, si.index));
1957                                let _ = multi.set_input_state(t_idx, ParticipationState::Active);
1958                                inputs.push(inp);
1959                            }
1960                        }
1961                    }
1962                }
1963            }
1964        }
1965
1966        let working_rate = u64::from(multi.working_format().rate().max(1));
1967        let mix_quantum = *block_frames;
1968        let align_wait = Duration::from_nanos(req_ref.mixer_config().alignment_window_ns)
1969            .min(Duration::from_millis(20));
1970        let call_started = Instant::now();
1971
1972        loop {
1973            let any_recently_active = inputs.iter().any(|inp| {
1974                !inp.eof
1975                    && inp
1976                        .last_active
1977                        .is_some_and(|t| t.elapsed() < Duration::from_millis(250))
1978            });
1979            let mut waited_on_idle_leader = false;
1980            let mut pushed_any = false;
1981
1982            for (t_idx, target) in req_ref.targets().iter().enumerate() {
1983                let already_queued = multi
1984                    .input_handles()
1985                    .get(t_idx)
1986                    .and_then(|h| h.snapshot())
1987                    .map_or(0, |s| s.queued_packets);
1988                if already_queued > 0 {
1989                    pushed_any = true;
1990                    continue;
1991                }
1992
1993                let is_pa_proc_target = plan_ref.target_plans[t_idx].resolved_backend
1994                    == BackendId::PulseAudio
1995                    && matches!(target.kind(), TargetKind::Process | TargetKind::Application);
1996
1997                if !is_pa_proc_target {
1998                    let Some(inp) = inputs
1999                        .iter_mut()
2000                        .find(|inp| inp.target_idx == t_idx && !inp.eof)
2001                    else {
2002                        let _ = multi.set_input_state(t_idx, ParticipationState::Idle);
2003                        continue;
2004                    };
2005                    let bpf = inp.stream.format().bytes_per_frame();
2006                    let stream_rate = u64::from(inp.stream.format().rate().max(1));
2007                    let is_resampled = stream_rate != working_rate;
2008                    let in_quantum = ((stream_rate * mix_quantum as u64).div_ceil(working_rate)
2009                        as usize)
2010                        .clamp(1, MAX_FRAMES_PER_SLOT);
2011                    let dst_bytes = in_quantum * bpf;
2012                    if in_bytes_scratch.len() < dst_bytes {
2013                        in_bytes_scratch.resize(dst_bytes, 0);
2014                    }
2015                    let max_passes = if is_resampled { 3 } else { 2 };
2016
2017                    for pass in 0..max_passes {
2018                        let is_this_active = inp
2019                            .last_active
2020                            .is_some_and(|t| t.elapsed() < Duration::from_millis(250));
2021                        let stream_timeout = if pass > 0 {
2022                            timeout.min(Duration::from_millis(12))
2023                        } else if is_this_active {
2024                            timeout.min(Duration::from_millis(25))
2025                        } else if !any_recently_active && !pushed_any && !waited_on_idle_leader {
2026                            waited_on_idle_leader = true;
2027                            timeout.min(Duration::from_millis(10))
2028                        } else {
2029                            Duration::ZERO
2030                        };
2031
2032                        let mut got_res = None;
2033                        for _attempt in 0..16 {
2034                            if let Ok(res) = inp.stream.read_into_with_cancel(
2035                                &mut in_bytes_scratch[..dst_bytes],
2036                                in_quantum,
2037                                stream_timeout,
2038                                cancel.clone(),
2039                            ) {
2040                                if res.frames > 0 || res.reason != PartialReason::Boundary {
2041                                    got_res = Some(res);
2042                                    break;
2043                                }
2044                            } else {
2045                                break;
2046                            }
2047                        }
2048                        if let Some(res) = got_res {
2049                            if res.frames > 0 {
2050                                inp.last_active = Some(Instant::now());
2051                                let now_ns = started_at.elapsed().as_nanos() as u64;
2052                                let stamp = res.first_packet.and_then(|a| a.header.timestamp);
2053                                let _ = multi.push_raw_input_bytes(
2054                                    t_idx,
2055                                    &in_bytes_scratch[..res.frames * bpf],
2056                                    stamp,
2057                                    now_ns,
2058                                );
2059                                if res.reason == PartialReason::Eof {
2060                                    inp.eof = true;
2061                                }
2062                                let now_queued = multi
2063                                    .input_handles()
2064                                    .get(t_idx)
2065                                    .and_then(|h| h.snapshot())
2066                                    .map_or(0, |s| s.queued_packets);
2067                                if now_queued > 0 {
2068                                    pushed_any = true;
2069                                    break;
2070                                }
2071                            } else {
2072                                if res.reason == PartialReason::Eof {
2073                                    inp.eof = true;
2074                                }
2075                                if pass == 0
2076                                    && (inp.eof
2077                                        || inp.last_active.is_none_or(|t| {
2078                                            t.elapsed() >= Duration::from_millis(500)
2079                                        }))
2080                                {
2081                                    let _ = multi.set_input_state(t_idx, ParticipationState::Idle);
2082                                }
2083                                break;
2084                            }
2085                        } else {
2086                            break;
2087                        }
2088                    }
2089                } else {
2090                    let live_count = inputs
2091                        .iter()
2092                        .filter(|inp| {
2093                            inp.target_idx == t_idx
2094                                && (!inp.eof
2095                                    || inp
2096                                        .sub_reblocker
2097                                        .as_ref()
2098                                        .is_some_and(|r| r.buffered_frames() > 0))
2099                        })
2100                        .count();
2101                    if live_count == 0 {
2102                        let _ = multi.set_input_state(t_idx, ParticipationState::Idle);
2103                        continue;
2104                    }
2105
2106                    for inp in inputs.iter_mut() {
2107                        if inp.target_idx != t_idx || inp.eof {
2108                            continue;
2109                        }
2110                        let buffered = inp
2111                            .sub_reblocker
2112                            .as_ref()
2113                            .map_or(0, FrameReblocker::buffered_frames);
2114                        if buffered >= PA_PROC_QUANTUM_FRAMES {
2115                            continue;
2116                        }
2117                        let is_this_active = inp
2118                            .last_active
2119                            .is_some_and(|t| t.elapsed() < Duration::from_millis(250));
2120                        let mut rem_wait = if is_this_active {
2121                            timeout.min(Duration::from_millis(25))
2122                        } else if !any_recently_active && !pushed_any && !waited_on_idle_leader {
2123                            waited_on_idle_leader = true;
2124                            timeout.min(Duration::from_millis(10))
2125                        } else {
2126                            Duration::ZERO
2127                        };
2128
2129                        while !inp.eof {
2130                            let cur_buf = inp
2131                                .sub_reblocker
2132                                .as_ref()
2133                                .map_or(0, FrameReblocker::buffered_frames);
2134                            if cur_buf >= PA_PROC_QUANTUM_FRAMES {
2135                                break;
2136                            }
2137                            let need = PA_PROC_QUANTUM_FRAMES - cur_buf;
2138                            let step_start = Instant::now();
2139                            let mut got_res = None;
2140                            for _attempt in 0..16 {
2141                                if let Ok(res) = inp.stream.read_into_with_cancel(
2142                                    &mut in_bytes_scratch[..need * 8],
2143                                    need,
2144                                    rem_wait,
2145                                    cancel.clone(),
2146                                ) {
2147                                    if res.frames > 0 || res.reason != PartialReason::Boundary {
2148                                        got_res = Some(res);
2149                                        break;
2150                                    }
2151                                } else {
2152                                    break;
2153                                }
2154                            }
2155                            rem_wait = rem_wait.saturating_sub(step_start.elapsed());
2156                            if let Some(res) = got_res {
2157                                if res.frames > 0 {
2158                                    inp.last_active = Some(Instant::now());
2159                                    if let Some(ts) =
2160                                        res.first_packet.and_then(|a| a.header.timestamp)
2161                                    {
2162                                        inp.last_stamp = Some(ts);
2163                                    }
2164                                    let samp_cnt = res.frames * 2;
2165                                    for (k, b) in in_bytes_scratch[..res.frames * 8]
2166                                        .as_chunks::<4>()
2167                                        .0
2168                                        .iter()
2169                                        .enumerate()
2170                                    {
2171                                        pulse_sub_f32[k] =
2172                                            f32::from_le_bytes([b[0], b[1], b[2], b[3]]);
2173                                    }
2174                                    if let Some(reblocker) = inp.sub_reblocker.as_mut() {
2175                                        let _ = reblocker.push_samples(&pulse_sub_f32[..samp_cnt]);
2176                                    }
2177                                    if res.reason == PartialReason::Eof {
2178                                        inp.eof = true;
2179                                        break;
2180                                    }
2181                                    if rem_wait.is_zero() {
2182                                        break;
2183                                    }
2184                                } else {
2185                                    if res.reason == PartialReason::Eof {
2186                                        inp.eof = true;
2187                                    }
2188                                    break;
2189                                }
2190                            } else {
2191                                break;
2192                            }
2193                        }
2194                    }
2195
2196                    // Bound peer alignment when a substream has a full quantum.
2197                    let any_ready = inputs.iter().any(|inp| {
2198                        inp.target_idx == t_idx
2199                            && inp
2200                                .sub_reblocker
2201                                .as_ref()
2202                                .is_some_and(|r| r.buffered_frames() >= PA_PROC_QUANTUM_FRAMES)
2203                    });
2204                    if any_ready && live_count > 1 {
2205                        let align_started = Instant::now();
2206                        for inp in inputs.iter_mut() {
2207                            if inp.target_idx != t_idx || inp.eof {
2208                                continue;
2209                            }
2210                            let allow_bounded_wait = *drained_blocks == 0
2211                                || inp
2212                                    .last_active
2213                                    .is_none_or(|t| t.elapsed() < Duration::from_millis(500));
2214                            while !inp.eof {
2215                                let cur_buf = inp
2216                                    .sub_reblocker
2217                                    .as_ref()
2218                                    .map_or(0, FrameReblocker::buffered_frames);
2219                                if cur_buf >= PA_PROC_QUANTUM_FRAMES {
2220                                    break;
2221                                }
2222                                let rem = if allow_bounded_wait {
2223                                    align_wait.saturating_sub(align_started.elapsed())
2224                                } else {
2225                                    Duration::ZERO
2226                                };
2227                                let need = PA_PROC_QUANTUM_FRAMES - cur_buf;
2228                                let mut got_res = None;
2229                                for _attempt in 0..16 {
2230                                    if let Ok(res) = inp.stream.read_into_with_cancel(
2231                                        &mut in_bytes_scratch[..need * 8],
2232                                        need,
2233                                        rem,
2234                                        cancel.clone(),
2235                                    ) {
2236                                        if res.frames > 0 || res.reason != PartialReason::Boundary {
2237                                            got_res = Some(res);
2238                                            break;
2239                                        }
2240                                    } else {
2241                                        break;
2242                                    }
2243                                }
2244                                if let Some(res) = got_res {
2245                                    if res.frames > 0 {
2246                                        inp.last_active = Some(Instant::now());
2247                                        if let Some(ts) =
2248                                            res.first_packet.and_then(|a| a.header.timestamp)
2249                                        {
2250                                            inp.last_stamp = Some(ts);
2251                                        }
2252                                        let samp_cnt = res.frames * 2;
2253                                        for (k, b) in in_bytes_scratch[..res.frames * 8]
2254                                            .as_chunks::<4>()
2255                                            .0
2256                                            .iter()
2257                                            .enumerate()
2258                                        {
2259                                            pulse_sub_f32[k] =
2260                                                f32::from_le_bytes([b[0], b[1], b[2], b[3]]);
2261                                        }
2262                                        if let Some(reblocker) = inp.sub_reblocker.as_mut() {
2263                                            let _ =
2264                                                reblocker.push_samples(&pulse_sub_f32[..samp_cnt]);
2265                                        }
2266                                        if res.reason == PartialReason::Eof {
2267                                            inp.eof = true;
2268                                            break;
2269                                        }
2270                                        if rem.is_zero() {
2271                                            break;
2272                                        }
2273                                    } else {
2274                                        if res.reason == PartialReason::Eof {
2275                                            inp.eof = true;
2276                                        }
2277                                        break;
2278                                    }
2279                                } else {
2280                                    break;
2281                                }
2282                            }
2283                        }
2284                    }
2285
2286                    let any_quantum_ready = inputs.iter().any(|inp| {
2287                        inp.target_idx == t_idx
2288                            && inp
2289                                .sub_reblocker
2290                                .as_ref()
2291                                .is_some_and(|r| r.buffered_frames() >= PA_PROC_QUANTUM_FRAMES)
2292                    });
2293                    let max_eof_tail = if !any_quantum_ready {
2294                        inputs
2295                            .iter()
2296                            .filter(|inp| inp.target_idx == t_idx && inp.eof)
2297                            .filter_map(|inp| {
2298                                inp.sub_reblocker.as_ref().map(|r| r.buffered_frames())
2299                            })
2300                            .max()
2301                            .unwrap_or(0)
2302                    } else {
2303                        0
2304                    };
2305                    let emit_frames = if any_quantum_ready {
2306                        PA_PROC_QUANTUM_FRAMES
2307                    } else {
2308                        max_eof_tail
2309                    };
2310
2311                    if emit_frames > 0 {
2312                        let emit_samples = emit_frames * 2;
2313                        pulse_sum_f32[..emit_samples].fill(0.0);
2314                        let mut group_stamp = None;
2315                        for inp in inputs.iter_mut() {
2316                            if inp.target_idx != t_idx {
2317                                continue;
2318                            }
2319                            let Some(reblocker) = inp.sub_reblocker.as_mut() else {
2320                                continue;
2321                            };
2322                            if any_quantum_ready
2323                                && reblocker.buffered_frames() >= PA_PROC_QUANTUM_FRAMES
2324                            {
2325                                if reblocker
2326                                    .pop_block_into(&mut pulse_sub_f32[..emit_samples])
2327                                    .unwrap_or(false)
2328                                {
2329                                    if group_stamp.is_none() {
2330                                        group_stamp = inp.last_stamp;
2331                                    }
2332                                    for k in 0..emit_samples {
2333                                        let val = pulse_sub_f32[k];
2334                                        if val.is_finite() {
2335                                            pulse_sum_f32[k] += val;
2336                                        } else {
2337                                            pulse_sum_f32[k] = f32::NAN;
2338                                        }
2339                                    }
2340                                }
2341                            } else if inp.eof && reblocker.buffered_frames() > 0 {
2342                                let tail_frames = reblocker.buffered_frames().min(emit_frames);
2343                                let tail_samples = tail_frames * 2;
2344                                if reblocker
2345                                    .peek_into(0, &mut pulse_sub_f32[..tail_samples])
2346                                    .unwrap_or(false)
2347                                {
2348                                    reblocker.clear();
2349                                    if group_stamp.is_none() {
2350                                        group_stamp = inp.last_stamp;
2351                                    }
2352                                    for k in 0..tail_samples {
2353                                        let val = pulse_sub_f32[k];
2354                                        if val.is_finite() {
2355                                            pulse_sum_f32[k] += val;
2356                                        } else {
2357                                            pulse_sum_f32[k] = f32::NAN;
2358                                        }
2359                                    }
2360                                }
2361                            }
2362                        }
2363
2364                        for (k, &s) in pulse_sum_f32[..emit_samples].iter().enumerate() {
2365                            pulse_sum_bytes[k * 4..k * 4 + 4].copy_from_slice(&s.to_le_bytes());
2366                        }
2367                        let now_ns = started_at.elapsed().as_nanos() as u64;
2368                        let _ = multi.push_raw_input_bytes(
2369                            t_idx,
2370                            &pulse_sum_bytes[..emit_samples * 4],
2371                            group_stamp,
2372                            now_ns,
2373                        );
2374                        *drained_blocks = drained_blocks.saturating_add(1);
2375                        pushed_any = true;
2376                    } else {
2377                        let all_idle =
2378                            inputs
2379                                .iter()
2380                                .filter(|inp| inp.target_idx == t_idx)
2381                                .all(|inp| {
2382                                    inp.eof
2383                                        || inp.last_active.is_none_or(|t| {
2384                                            t.elapsed() >= Duration::from_millis(500)
2385                                        })
2386                                });
2387                        if all_idle {
2388                            let _ = multi.set_input_state(t_idx, ParticipationState::Idle);
2389                        }
2390                    }
2391                }
2392            }
2393
2394            if pushed_any
2395                || req_ref.mixer_config().silence_on_idle
2396                || timeout.is_zero()
2397                || call_started.elapsed() >= timeout
2398                || cancel.is_cancelled()
2399            {
2400                break;
2401            }
2402            thread::park_timeout(
2403                Duration::from_millis(5).min(timeout.saturating_sub(call_started.elapsed())),
2404            );
2405        }
2406
2407        started_at.elapsed().as_nanos() as u64
2408    }
2409}
2410
2411impl CaptureManagerBackend for PlatformManager {
2412    fn open_with_options(
2413        request: CaptureRequest,
2414        overflow: Overflow,
2415        timing: TimingRequirement,
2416    ) -> Result<Self, CapabilityError> {
2417        Self::open_impl(
2418            request,
2419            LinuxClientPaths::default(),
2420            overflow,
2421            timing,
2422            false,
2423        )
2424    }
2425
2426    #[inline]
2427    fn plan(&self) -> &CapturePlanReport {
2428        &self.plan
2429    }
2430
2431    fn selected_backend(&self) -> BackendId {
2432        self.plan.selected_backend.unwrap_or_else(|| {
2433            self.plan
2434                .target_plans
2435                .first()
2436                .map_or(BackendId::PipeWire, |p| p.resolved_backend)
2437        })
2438    }
2439
2440    #[inline]
2441    fn is_software_mix(&self) -> bool {
2442        matches!(self.engine, PlatformExecutionEngine::SoftwareMix { .. })
2443    }
2444
2445    fn working_format(&self) -> Option<&Arc<Format>> {
2446        match &self.engine {
2447            PlatformExecutionEngine::PassThrough { stream, .. } => {
2448                stream.as_ref().map(AudioStreamBackend::format)
2449            }
2450            PlatformExecutionEngine::SoftwareMix { multi, .. } => Some(multi.working_format()),
2451        }
2452    }
2453
2454    fn output_format(&self) -> Option<&Arc<Format>> {
2455        match &self.engine {
2456            PlatformExecutionEngine::PassThrough { stream, .. } => {
2457                stream.as_ref().map(AudioStreamBackend::format)
2458            }
2459            PlatformExecutionEngine::SoftwareMix { multi, .. } => Some(multi.output_format()),
2460        }
2461    }
2462
2463    #[inline]
2464    fn targets(&self) -> &[CaptureTarget] {
2465        self.request.targets()
2466    }
2467
2468    fn input_handles(&self) -> &[InputStatusHandle] {
2469        match &self.engine {
2470            PlatformExecutionEngine::SoftwareMix { multi, .. } => multi.input_handles(),
2471            PlatformExecutionEngine::PassThrough { .. } => &[],
2472        }
2473    }
2474
2475    fn membership_descriptor(&self) -> Option<MembershipDescriptor> {
2476        match &self.engine {
2477            PlatformExecutionEngine::SoftwareMix { multi, .. } => {
2478                Some(multi.membership_descriptor())
2479            }
2480            PlatformExecutionEngine::PassThrough { .. } => None,
2481        }
2482    }
2483
2484    #[inline]
2485    fn last_block_metadata(&self) -> Option<MixedBlockMetadata> {
2486        self.last_metadata
2487    }
2488
2489    #[inline]
2490    fn session_id(&self) -> u64 {
2491        self.session_counter
2492    }
2493
2494    #[inline]
2495    fn segment_id(&self) -> u64 {
2496        self.segment_counter
2497    }
2498
2499    #[inline]
2500    fn on_format_change(&self) -> OnFormatChange {
2501        self.request.on_format_change()
2502    }
2503
2504    #[inline]
2505    fn route_guard(&self) -> Option<&RouteRollbackGuard> {
2506        Some(&self.route_guard)
2507    }
2508
2509    fn update_targets(&mut self, new_targets: Vec<CaptureTarget>) -> Result<u64, CapabilityError> {
2510        self.update_targets_impl(new_targets)
2511    }
2512
2513    fn notify_default_device_changed(
2514        &mut self,
2515        new_device_id: Option<&str>,
2516    ) -> Result<bool, CapabilityError> {
2517        self.notify_default_flow_changed(TargetKind::DefaultOutput, new_device_id)
2518    }
2519
2520    fn notify_default_input_changed(
2521        &mut self,
2522        new_device_id: Option<&str>,
2523    ) -> Result<bool, CapabilityError> {
2524        self.notify_default_flow_changed(TargetKind::DefaultInput, new_device_id)
2525    }
2526
2527    fn reopen_relaunched_target(
2528        &mut self,
2529        target_index: usize,
2530        new_pid: u32,
2531    ) -> Result<(), CapabilityError> {
2532        self.reopen_relaunched_target_impl(target_index, new_pid)
2533    }
2534
2535    #[inline]
2536    fn default_cancel(&self) -> Cancellation {
2537        self.default_cancel.clone()
2538    }
2539
2540    fn read_with_cancel(
2541        &mut self,
2542        frames: usize,
2543        timeout: Duration,
2544        cancel: Cancellation,
2545    ) -> Result<ReadResult, ReadError> {
2546        if frames == 0 {
2547            return Err(ReadError::InvalidRequest);
2548        }
2549        self.poll_default_device_follow();
2550        let _guard = self.read_lock.try_lock().map_err(|err| match err {
2551            TryLockError::WouldBlock => ReadError::AlreadyPending,
2552            TryLockError::Poisoned(_) => ReadError::Poisoned,
2553        })?;
2554
2555        if let Some(boundary) = self.pending_boundary.take() {
2556            return Ok(ReadResult {
2557                frames: 0,
2558                chunks: Vec::new(),
2559                first_packet: None,
2560                last_packet: None,
2561                reason: PartialReason::Boundary,
2562                control: Some(ordering::Control {
2563                    sequence: 0,
2564                    generation: boundary.session,
2565                    segment: boundary.segment,
2566                    format: boundary.format,
2567                    kind: ordering::ControlKind::Recovered,
2568                    losses: ordering::Losses::default(),
2569                    records: 1,
2570                }),
2571                copies: Default::default(),
2572            });
2573        }
2574        if self.stopped {
2575            return Ok(ReadResult {
2576                frames: 0,
2577                chunks: Vec::new(),
2578                first_packet: None,
2579                last_packet: None,
2580                reason: PartialReason::Eof,
2581                control: None,
2582                copies: Default::default(),
2583            });
2584        }
2585        if self.terminal_error.is_some() {
2586            return Ok(ReadResult {
2587                frames: 0,
2588                chunks: Vec::new(),
2589                first_packet: None,
2590                last_packet: None,
2591                reason: PartialReason::Failure(Failure::Backend),
2592                control: None,
2593                copies: Default::default(),
2594            });
2595        }
2596        if cancel.is_cancelled() {
2597            return Ok(ReadResult {
2598                frames: 0,
2599                chunks: Vec::new(),
2600                first_packet: None,
2601                last_packet: None,
2602                reason: PartialReason::Cancelled,
2603                control: None,
2604                copies: Default::default(),
2605            });
2606        }
2607        drop(_guard);
2608
2609        match &mut self.engine {
2610            PlatformExecutionEngine::PassThrough { stream, .. } => {
2611                let Some(active) = stream.as_mut() else {
2612                    return Ok(ReadResult {
2613                        frames: 0,
2614                        chunks: Vec::new(),
2615                        first_packet: None,
2616                        last_packet: None,
2617                        reason: PartialReason::Eof,
2618                        control: None,
2619                        copies: Default::default(),
2620                    });
2621                };
2622                let res = active.read_with_cancel(frames, timeout, cancel)?;
2623                if res.frames > 0 {
2624                    self.last_metadata = Some(MixedBlockMetadata {
2625                        membership_version: self.segment_counter,
2626                        contributing_mask: 1,
2627                        late_inputs: 0,
2628                        failed_inputs: 0,
2629                        nonfinite_inputs: 0,
2630                        synthesized_silence: false,
2631                        clipped_samples: 0,
2632                        nonfinite_samples: 0,
2633                        drift_slips: 0,
2634                        skew_estimate_ns: Some(0),
2635                        skew_uncertainty_ns: Some(0),
2636                    });
2637                }
2638                Ok(res)
2639            }
2640            PlatformExecutionEngine::SoftwareMix { multi, .. } => {
2641                if let Some((res, meta)) = multi.try_pop_pending_owned(frames)? {
2642                    self.last_metadata = Some(meta);
2643                    return Ok(res);
2644                }
2645                let now_ns = self.drain_software_mix_inputs(timeout, &cancel);
2646                if cancel.is_cancelled() {
2647                    return Ok(ReadResult {
2648                        frames: 0,
2649                        chunks: Vec::new(),
2650                        first_packet: None,
2651                        last_packet: None,
2652                        reason: PartialReason::Cancelled,
2653                        control: None,
2654                        copies: Default::default(),
2655                    });
2656                }
2657                let align_ns = self.request.mixer_config().alignment_window_ns;
2658                let PlatformExecutionEngine::SoftwareMix { multi, .. } = &self.engine else {
2659                    unreachable!()
2660                };
2661                let (res, meta) = multi.read_mixed_owned(frames, now_ns, align_ns)?;
2662                self.last_metadata = Some(meta);
2663                Ok(res)
2664            }
2665        }
2666    }
2667
2668    fn read_into_with_cancel(
2669        &mut self,
2670        destination: &mut [u8],
2671        frames: usize,
2672        timeout: Duration,
2673        cancel: Cancellation,
2674    ) -> Result<ReadResult, ReadError> {
2675        if frames == 0 {
2676            return Err(ReadError::InvalidRequest);
2677        }
2678        self.poll_default_device_follow();
2679        let _guard = self.read_lock.try_lock().map_err(|err| match err {
2680            TryLockError::WouldBlock => ReadError::AlreadyPending,
2681            TryLockError::Poisoned(_) => ReadError::Poisoned,
2682        })?;
2683
2684        if let Some(boundary) = self.pending_boundary.take() {
2685            return Ok(ReadResult {
2686                frames: 0,
2687                chunks: Vec::new(),
2688                first_packet: None,
2689                last_packet: None,
2690                reason: PartialReason::Boundary,
2691                control: Some(ordering::Control {
2692                    sequence: 0,
2693                    generation: boundary.session,
2694                    segment: boundary.segment,
2695                    format: boundary.format,
2696                    kind: ordering::ControlKind::Recovered,
2697                    losses: ordering::Losses::default(),
2698                    records: 1,
2699                }),
2700                copies: Default::default(),
2701            });
2702        }
2703        if self.stopped {
2704            return Ok(ReadResult {
2705                frames: 0,
2706                chunks: Vec::new(),
2707                first_packet: None,
2708                last_packet: None,
2709                reason: PartialReason::Eof,
2710                control: None,
2711                copies: Default::default(),
2712            });
2713        }
2714        if self.terminal_error.is_some() {
2715            return Ok(ReadResult {
2716                frames: 0,
2717                chunks: Vec::new(),
2718                first_packet: None,
2719                last_packet: None,
2720                reason: PartialReason::Failure(Failure::Backend),
2721                control: None,
2722                copies: Default::default(),
2723            });
2724        }
2725        if cancel.is_cancelled() {
2726            return Ok(ReadResult {
2727                frames: 0,
2728                chunks: Vec::new(),
2729                first_packet: None,
2730                last_packet: None,
2731                reason: PartialReason::Cancelled,
2732                control: None,
2733                copies: Default::default(),
2734            });
2735        }
2736        drop(_guard);
2737
2738        match &mut self.engine {
2739            PlatformExecutionEngine::PassThrough { stream, .. } => {
2740                let Some(active) = stream.as_mut() else {
2741                    return Ok(ReadResult {
2742                        frames: 0,
2743                        chunks: Vec::new(),
2744                        first_packet: None,
2745                        last_packet: None,
2746                        reason: PartialReason::Eof,
2747                        control: None,
2748                        copies: Default::default(),
2749                    });
2750                };
2751                let res = active.read_into_with_cancel(destination, frames, timeout, cancel)?;
2752                if res.frames > 0 {
2753                    self.last_metadata = Some(MixedBlockMetadata {
2754                        membership_version: self.segment_counter,
2755                        contributing_mask: 1,
2756                        late_inputs: 0,
2757                        failed_inputs: 0,
2758                        nonfinite_inputs: 0,
2759                        synthesized_silence: false,
2760                        clipped_samples: 0,
2761                        nonfinite_samples: 0,
2762                        drift_slips: 0,
2763                        skew_estimate_ns: Some(0),
2764                        skew_uncertainty_ns: Some(0),
2765                    });
2766                }
2767                Ok(res)
2768            }
2769            PlatformExecutionEngine::SoftwareMix { multi, .. } => {
2770                let out_stride = multi.output_format().bytes_per_frame();
2771                if destination.len() < frames.saturating_mul(out_stride) {
2772                    return Err(ReadError::InvalidDestination);
2773                }
2774                if let Some((res, meta)) = multi.try_pop_pending_into(destination, frames)? {
2775                    self.last_metadata = Some(meta);
2776                    return Ok(res);
2777                }
2778                let now_ns = self.drain_software_mix_inputs(timeout, &cancel);
2779                if cancel.is_cancelled() {
2780                    return Ok(ReadResult {
2781                        frames: 0,
2782                        chunks: Vec::new(),
2783                        first_packet: None,
2784                        last_packet: None,
2785                        reason: PartialReason::Cancelled,
2786                        control: None,
2787                        copies: Default::default(),
2788                    });
2789                }
2790                let align_ns = self.request.mixer_config().alignment_window_ns;
2791                let PlatformExecutionEngine::SoftwareMix { multi, .. } = &self.engine else {
2792                    unreachable!()
2793                };
2794                let (res, meta) = multi.read_mixed_into(destination, frames, now_ns, align_ns)?;
2795                self.last_metadata = Some(meta);
2796                Ok(res)
2797            }
2798        }
2799    }
2800
2801    fn stop(&mut self, mode: Stop) {
2802        self.stopped = true;
2803        self.default_observer = None;
2804        self.default_source_observer = None;
2805        if mode == Stop::Abort {
2806            self.pending_boundary = None;
2807        }
2808        match &mut self.engine {
2809            PlatformExecutionEngine::PassThrough { stream, topology } => {
2810                if let Some(active) = stream.as_ref() {
2811                    active.stop(mode);
2812                }
2813                if let Some(topo) = topology {
2814                    topo.shutdown();
2815                }
2816            }
2817            PlatformExecutionEngine::SoftwareMix {
2818                multi,
2819                inputs,
2820                sub_topologies,
2821                pa_sub_watch,
2822                ..
2823            } => {
2824                if mode == Stop::Abort {
2825                    multi.clear_pending_output();
2826                }
2827                if let Some(mut watch) = pa_sub_watch.take() {
2828                    watch.stop_and_join();
2829                }
2830                for inp in inputs {
2831                    inp.stream.stop(mode);
2832                }
2833                for (_, topo) in sub_topologies {
2834                    topo.shutdown();
2835                }
2836            }
2837        }
2838    }
2839
2840    fn wait_cleanup(&mut self, timeout: Duration) -> bool {
2841        let started = Instant::now();
2842        match &mut self.engine {
2843            PlatformExecutionEngine::PassThrough { stream, topology } => {
2844                if let Some(topo) = topology {
2845                    topo.shutdown();
2846                }
2847                if let Some(active) = stream.as_ref() {
2848                    let rem = timeout.saturating_sub(started.elapsed());
2849                    let _ = active.wait_cleanup(rem);
2850                }
2851            }
2852            PlatformExecutionEngine::SoftwareMix {
2853                inputs,
2854                sub_topologies,
2855                pa_sub_watch,
2856                ..
2857            } => {
2858                if let Some(mut watch) = pa_sub_watch.take() {
2859                    watch.stop_and_join();
2860                }
2861                for (_, topo) in sub_topologies {
2862                    topo.shutdown();
2863                }
2864                for inp in inputs {
2865                    let rem = timeout.saturating_sub(started.elapsed());
2866                    let _ = inp.stream.wait_cleanup(rem);
2867                }
2868            }
2869        }
2870        self.resources_done()
2871    }
2872
2873    fn resources_done(&self) -> bool {
2874        match &self.engine {
2875            PlatformExecutionEngine::PassThrough { stream, topology } => {
2876                stream
2877                    .as_ref()
2878                    .is_none_or(AudioStreamBackend::resources_done)
2879                    && topology
2880                        .as_ref()
2881                        .is_none_or(PlatformTopologyController::is_finished)
2882            }
2883            PlatformExecutionEngine::SoftwareMix {
2884                inputs,
2885                sub_topologies,
2886                pa_sub_watch,
2887                ..
2888            } => {
2889                pa_sub_watch.is_none()
2890                    && inputs
2891                        .iter()
2892                        .all(|inp| AudioStreamBackend::resources_done(&inp.stream))
2893                    && sub_topologies.iter().all(|(_, topo)| topo.is_finished())
2894            }
2895        }
2896    }
2897}
2898
2899impl Drop for PlatformManager {
2900    fn drop(&mut self) {
2901        self.stop(Stop::Abort);
2902        let _ = self.wait_cleanup(self.cleanup_timeout.min(Duration::from_millis(500)));
2903    }
2904}
2905
2906#[cfg(test)]
2907mod tests {
2908    use super::*;
2909    use crate::{
2910        CaptureManager,
2911        core::schema::{CombineMode, InputConversionPolicy},
2912        pipewire_stream::PipeWireStream,
2913    };
2914
2915    fn make_tone_packets_i16_mono(
2916        rate_hz: u32,
2917        freq: f64,
2918        packets: usize,
2919        frames_per_pkt: usize,
2920    ) -> Vec<(Vec<u8>, usize, u64)> {
2921        let mut out = Vec::with_capacity(packets);
2922        let step_ns = ((frames_per_pkt as u64) * 1_000_000_000) / u64::from(rate_hz);
2923        for p in 0..packets {
2924            let mut bytes = Vec::with_capacity(frames_per_pkt * 2);
2925            for n in 0..frames_per_pkt {
2926                let idx = p * frames_per_pkt + n;
2927                let t = idx as f64 / f64::from(rate_hz);
2928                let s =
2929                    (0.25 * (2.0 * std::f64::consts::PI * freq * t).sin() * 32767.0).round() as i16;
2930                bytes.extend_from_slice(&s.to_le_bytes());
2931            }
2932            out.push((bytes, frames_per_pkt, 10_000_000 + (p as u64) * step_ns));
2933        }
2934        out
2935    }
2936
2937    fn make_tone_packets_f32_stereo(
2938        rate_hz: u32,
2939        freq_l: f64,
2940        freq_r: f64,
2941        packets: usize,
2942        frames_per_pkt: usize,
2943    ) -> Vec<(Vec<u8>, usize, u64)> {
2944        let mut out = Vec::with_capacity(packets);
2945        let step_ns = ((frames_per_pkt as u64) * 1_000_000_000) / u64::from(rate_hz);
2946        for p in 0..packets {
2947            let mut bytes = Vec::with_capacity(frames_per_pkt * 8);
2948            for n in 0..frames_per_pkt {
2949                let idx = p * frames_per_pkt + n;
2950                let t = idx as f64 / f64::from(rate_hz);
2951                let l = (0.25 * (2.0 * std::f64::consts::PI * freq_l * t).sin()) as f32;
2952                let r = (0.25 * (2.0 * std::f64::consts::PI * freq_r * t).sin()) as f32;
2953                bytes.extend_from_slice(&l.to_le_bytes());
2954                bytes.extend_from_slice(&r.to_le_bytes());
2955            }
2956            out.push((bytes, frames_per_pkt, 10_000_000 + (p as u64) * step_ns));
2957        }
2958        out
2959    }
2960
2961    fn read_into_via_generic_manager<B: CaptureManagerBackend>(
2962        mgr: &mut crate::core::traits::CaptureManager<B>,
2963        dst: &mut [u8],
2964        frames: usize,
2965        timeout: Duration,
2966    ) -> Result<ReadResult, ReadError> {
2967        mgr.read_into(dst, frames, timeout)
2968    }
2969
2970    #[test]
2971    fn platform_manager_shared_out_pool_zero_steady_allocations_and_format_gates()
2972    -> Result<(), CapabilityError> {
2973        let fmt_16k = Arc::new(
2974            Format::new(
2975                SampleType::I16,
2976                ByteOrder::Little,
2977                16_000,
2978                1,
2979                Layout::Known(Arc::from([Channel::Mono])),
2980            )
2981            .unwrap(),
2982        );
2983        let fmt_48k = Arc::new(
2984            Format::new(
2985                SampleType::F32,
2986                ByteOrder::Little,
2987                48_000,
2988                2,
2989                Layout::Known(Arc::from([Channel::FrontLeft, Channel::FrontRight])),
2990            )
2991            .unwrap(),
2992        );
2993
2994        let budget = StorageBudget::new(8, 32 * 1024 * 1024).unwrap();
2995        let sys_t = CaptureTarget::device("pw-sys-0")
2996            .unwrap()
2997            .with_backend(BackendId::PipeWire);
2998        let mic_t = CaptureTarget::input_device("pa-mic-0")
2999            .unwrap()
3000            .with_backend(BackendId::PulseAudio);
3001        let s_sys = PlatformStream::PipeWire(PipeWireStream::from_synthetic_packets(
3002            fmt_48k.clone(),
3003            1,
3004            make_tone_packets_f32_stereo(48_000, 1000.0, 1500.0, 50, 480),
3005            &budget,
3006        )?);
3007        let s_mic = PlatformStream::PipeWire(PipeWireStream::from_synthetic_packets(
3008            fmt_16k.clone(),
3009            5,
3010            make_tone_packets_i16_mono(16_000, 500.0, 50, 160),
3011            &budget,
3012        )?);
3013        let stream_only_bytes = budget.reserved_bytes();
3014        let stream_only_sessions = budget.resident_sessions();
3015        assert_eq!(stream_only_sessions, 2);
3016
3017        let mut mgr = CaptureManager::from_backend(PlatformManager::from_synthetic_streams(
3018            CaptureRequest::new(vec![sys_t, mic_t]),
3019            vec![(BackendId::PipeWire, s_sys), (BackendId::PulseAudio, s_mic)],
3020            budget.clone(),
3021        )?);
3022        // The output pool charges the shared budget without consuming a stream session slot.
3023        assert_eq!(budget.resident_sessions(), 2);
3024        assert!(budget.reserved_bytes() > stream_only_bytes);
3025        assert!(mgr.is_software_mix());
3026        assert_eq!(mgr.working_format().unwrap().rate(), 48_000);
3027        assert!(mgr.route_guard().is_some_and(|g| !g.allow_reroute()));
3028
3029        let mut dst = [0u8; 256 * 8];
3030        for _ in 0..2 {
3031            let _ =
3032                read_into_via_generic_manager(&mut mgr, &mut dst, 256, Duration::from_millis(40))
3033                    .unwrap();
3034        }
3035        let mut measured_reads = 0usize;
3036        let allocs = allocation_counter::measure(|| {
3037            for _ in 0..64 {
3038                let res = read_into_via_generic_manager(
3039                    &mut mgr,
3040                    &mut dst,
3041                    256,
3042                    Duration::from_millis(40),
3043                )
3044                .unwrap();
3045                if res.frames > 0 {
3046                    measured_reads += 1;
3047                }
3048            }
3049        });
3050        assert!(measured_reads >= 40);
3051        assert_eq!(
3052            allocs.count_total, 0,
3053            "CaptureManager<PlatformManager>::read_into allocated {} times in steady state",
3054            allocs.count_total
3055        );
3056        mgr.stop(Stop::Abort);
3057        assert!(mgr.wait_cleanup(Duration::from_secs(2)));
3058
3059        let follow_in = CaptureTarget::microphone(DefaultDeviceMode::Follow);
3060        let pt_s1 = PlatformStream::PipeWire(PipeWireStream::from_synthetic_packets(
3061            fmt_16k.clone(),
3062            2,
3063            make_tone_packets_i16_mono(16_000, 440.0, 2, 160),
3064            &budget,
3065        )?);
3066        let pt_s2 = PlatformStream::PipeWire(PipeWireStream::from_synthetic_packets(
3067            fmt_48k.clone(),
3068            3,
3069            make_tone_packets_f32_stereo(48_000, 440.0, 440.0, 2, 480),
3070            &budget,
3071        )?);
3072        let mut pt_fail = PlatformManager::from_synthetic_streams(
3073            CaptureRequest::single(follow_in.clone()).with_on_format_change(OnFormatChange::Fail),
3074            vec![(BackendId::PipeWire, pt_s1)],
3075            budget.clone(),
3076        )?;
3077        assert_eq!(
3078            pt_fail.apply_opened_default_stream_for_test(TargetKind::DefaultInput, pt_s2),
3079            Err(CapabilityError::FormatChangeRejected)
3080        );
3081        drop(pt_fail);
3082
3083        let mix_s1 = PlatformStream::PipeWire(PipeWireStream::from_synthetic_packets(
3084            fmt_16k.clone(),
3085            2,
3086            make_tone_packets_i16_mono(16_000, 440.0, 2, 160),
3087            &budget,
3088        )?);
3089        let mix_s2 = PlatformStream::PipeWire(PipeWireStream::from_synthetic_packets(
3090            fmt_48k.clone(),
3091            3,
3092            make_tone_packets_f32_stereo(48_000, 440.0, 440.0, 2, 480),
3093            &budget,
3094        )?);
3095        let mut mix_fail = PlatformManager::from_synthetic_streams(
3096            CaptureRequest::single(follow_in.clone())
3097                .with_combine_mode(CombineMode::CspaMixer)
3098                .with_on_format_change(OnFormatChange::Fail),
3099            vec![(BackendId::PipeWire, mix_s1)],
3100            budget.clone(),
3101        )?;
3102        assert_eq!(
3103            mix_fail.apply_opened_default_stream_for_test(TargetKind::DefaultInput, mix_s2),
3104            Err(CapabilityError::FormatChangeRejected)
3105        );
3106        drop(mix_fail);
3107
3108        let adapt_s1 = PlatformStream::PipeWire(PipeWireStream::from_synthetic_packets(
3109            fmt_16k.clone(),
3110            2,
3111            make_tone_packets_i16_mono(16_000, 440.0, 4, 160),
3112            &budget,
3113        )?);
3114        let adapt_s2 = PlatformStream::PipeWire(PipeWireStream::from_synthetic_packets(
3115            fmt_48k.clone(),
3116            3,
3117            make_tone_packets_f32_stereo(48_000, 440.0, 440.0, 4, 480),
3118            &budget,
3119        )?);
3120        let mut mix_adapt = PlatformManager::from_synthetic_streams(
3121            CaptureRequest::single(follow_in).with_combine_mode(CombineMode::CspaMixer),
3122            vec![(BackendId::PipeWire, adapt_s1)],
3123            budget.clone(),
3124        )?;
3125        assert_eq!(mix_adapt.working_format().unwrap().rate(), 16_000);
3126        assert_eq!(
3127            mix_adapt.apply_opened_default_stream_for_test(TargetKind::DefaultInput, adapt_s2),
3128            Ok(true)
3129        );
3130        assert_eq!(mix_adapt.working_format().unwrap().rate(), 48_000);
3131        drop(mix_adapt);
3132
3133        let strict_a = CaptureTarget::input_device("strict-16k").unwrap();
3134        let strict_b = CaptureTarget::device("strict-48k").unwrap();
3135        let sa = PlatformStream::PipeWire(PipeWireStream::from_synthetic_packets(
3136            fmt_16k,
3137            2,
3138            make_tone_packets_i16_mono(16_000, 440.0, 2, 160),
3139            &budget,
3140        )?);
3141        let sb = PlatformStream::PipeWire(PipeWireStream::from_synthetic_packets(
3142            fmt_48k,
3143            1,
3144            make_tone_packets_f32_stereo(48_000, 440.0, 440.0, 2, 480),
3145            &budget,
3146        )?);
3147        let strict_err = PlatformManager::from_synthetic_streams(
3148            CaptureRequest::new(vec![strict_a, strict_b])
3149                .with_input_conversion(InputConversionPolicy::StrictNoResample),
3150            vec![(BackendId::PipeWire, sa), (BackendId::PipeWire, sb)],
3151            budget,
3152        )
3153        .err();
3154        assert_eq!(strict_err, Some(CapabilityError::UnsupportedFormat));
3155        Ok(())
3156    }
3157}