pocketstation 1.0.1

Source-aware desktop audio Session SDK
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;

use crate::endpoint::{
    EndpointDriverFactory, EndpointDriverRegistry, EndpointFailure, EndpointFailureStage,
    EndpointPortInput, PreparedEndpointDriver,
};
use crate::frame::{AudioFrame, RouteId, SampleFormat, SampleSpec};
use crate::graph::{
    AudioCaps, ChannelLayout, MediaCaps, Multiplicity, PortDirection, PortSpec, SafetyContract,
    SignalSpec,
};
use crate::graph::{
    ConfigError, ExecutionPartition, NodeConfig, NodeDescriptor, NodeError, NodeFactory,
    RuntimeNode,
};
use crate::runtime::PlanRunnerError;

use super::*;
use crate::session::{
    ApplicationSelector, EndpointConfiguration, OperatorId, Session, SessionCompiler, Source,
    APPLICATION_SOURCE_NODE_TYPE_ID, BROWSER_NODE_TYPE_ID, BROWSER_OPERATOR_ID,
    CONNECTOR_NODE_TYPE_ID, MICROPHONE_SOURCE_NODE_TYPE_ID, RECORDER_NODE_TYPE_ID,
    RECORDER_OPERATOR_ID,
};

const TEST_CONNECTOR_OPERATOR_ID: &str = "example.connector.runtime-prepare.v1";

struct TestFactory {
    descriptor: NodeDescriptor,
    live_nodes: Arc<AtomicUsize>,
}

struct TestNode {
    live_nodes: Arc<AtomicUsize>,
}

struct CompileOnlyEndpointFactory;

impl EndpointDriverFactory for CompileOnlyEndpointFactory {
    fn prepare(
        &self,
        _inputs: Vec<EndpointPortInput>,
    ) -> Result<Box<dyn PreparedEndpointDriver>, EndpointFailure> {
        Err(EndpointFailure::new(
            EndpointFailureStage::Prepare,
            "runtime-prepare compiler fixture must not prepare an endpoint driver",
        ))
    }
}

#[derive(Clone, Copy)]
enum TestNodeRole {
    Source,
    Endpoint,
}

impl NodeFactory for TestFactory {
    fn descriptor(&self) -> NodeDescriptor {
        self.descriptor.clone()
    }

    fn validate_config(&self, _config: &NodeConfig) -> Result<(), ConfigError> {
        Ok(())
    }

    fn instantiate(
        &self,
        _context: &PrepareContext,
        _config: &NodeConfig,
    ) -> Result<Box<dyn RuntimeNode>, NodeError> {
        self.live_nodes.fetch_add(1, Ordering::Relaxed);
        Ok(Box::new(TestNode {
            live_nodes: Arc::clone(&self.live_nodes),
        }))
    }
}

impl RuntimeNode for TestNode {
    fn prepare(&mut self, _context: &PrepareContext) -> Result<(), NodeError> {
        Ok(())
    }

    fn process(&mut self, frame: AudioFrame) -> Result<Option<AudioFrame>, NodeError> {
        Ok(Some(frame))
    }
}

impl Drop for TestNode {
    fn drop(&mut self) {
        self.live_nodes.fetch_sub(1, Ordering::Relaxed);
    }
}

fn audio_port(name: &str, direction: PortDirection) -> PortSpec {
    PortSpec {
        name: name.to_owned(),
        direction,
        signal: SignalSpec::audio(),
        media: MediaCaps::Audio(AudioCaps {
            sample_rate_hz: Some(48_000),
            frame_samples: Some(960),
            channel_layout: ChannelLayout::Mono,
            format: SampleFormat::F32Interleaved,
        }),
        multiplicity: Multiplicity::One,
        required: true,
    }
}

fn descriptor(
    node_type_id: &'static str,
    partition: ExecutionPartition,
    role: TestNodeRole,
) -> NodeDescriptor {
    let (inputs, outputs) = match role {
        TestNodeRole::Source => (Vec::new(), vec![audio_port("audio", PortDirection::Output)]),
        TestNodeRole::Endpoint => (vec![audio_port("audio", PortDirection::Input)], Vec::new()),
    };
    NodeDescriptor {
        type_id: NodeTypeId::from(node_type_id),
        display_name: "Explicit runtime preparation test node",
        inputs,
        outputs,
        execution: partition,
        safety: if partition.requires_realtime_safety() {
            SafetyContract::RealtimeSafe
        } else {
            SafetyContract::AllocationAllowed
        },
        stateful: true,
    }
}

fn registries(
    endpoint_partition: ExecutionPartition,
    live_nodes: &Arc<AtomicUsize>,
) -> (NodeRegistry, EndpointDriverRegistry) {
    let mut node_registry = NodeRegistry::new();
    for node_type_id in [
        APPLICATION_SOURCE_NODE_TYPE_ID,
        MICROPHONE_SOURCE_NODE_TYPE_ID,
    ] {
        node_registry
            .register(Arc::new(TestFactory {
                descriptor: descriptor(
                    node_type_id,
                    ExecutionPartition::RealtimeCpu,
                    TestNodeRole::Source,
                ),
                live_nodes: Arc::clone(live_nodes),
            }))
            .unwrap();
    }
    for node_type_id in [
        CONNECTOR_NODE_TYPE_ID,
        BROWSER_NODE_TYPE_ID,
        RECORDER_NODE_TYPE_ID,
    ] {
        node_registry
            .register(Arc::new(TestFactory {
                descriptor: descriptor(node_type_id, endpoint_partition, TestNodeRole::Endpoint),
                live_nodes: Arc::clone(live_nodes),
            }))
            .unwrap();
    }

    let mut endpoint_registry = EndpointDriverRegistry::new();
    let endpoint_factory: Arc<dyn EndpointDriverFactory> = Arc::new(CompileOnlyEndpointFactory);
    for (operator_id, node_type_id) in [
        (TEST_CONNECTOR_OPERATOR_ID, CONNECTOR_NODE_TYPE_ID),
        (BROWSER_OPERATOR_ID, BROWSER_NODE_TYPE_ID),
        (RECORDER_OPERATOR_ID, RECORDER_NODE_TYPE_ID),
    ] {
        endpoint_registry
            .register(
                OperatorId::new(operator_id),
                NodeTypeId::from(node_type_id),
                Arc::clone(&endpoint_factory),
            )
            .expect("test endpoint registration must succeed");
    }
    (node_registry, endpoint_registry)
}

fn product_spec() -> SessionSpec {
    let session = Session::new();
    let application = session
        .capture(Source::application(ApplicationSelector::name(
            "Meeting App",
        )))
        .expect("application declaration must succeed");
    let microphone = session
        .capture(Source::microphone_default())
        .expect("microphone declaration must succeed");
    let connector = session
        .connector(
            OperatorId::new(TEST_CONNECTOR_OPERATOR_ID),
            EndpointConfiguration::new(),
        )
        .expect("connector declaration must succeed");
    let browser = session
        .browser("wss://receiver.example.test")
        .expect("browser declaration must succeed");

    for stem in [&application, &microphone] {
        stem.send(connector).expect("connector route must succeed");
        stem.send(browser).expect("browser route must succeed");
    }
    application
        .record("application")
        .expect("application recording route must succeed");
    microphone
        .record("microphone")
        .expect("microphone recording route must succeed");
    session.freeze().expect("product spec must freeze")
}

fn prepare_context() -> PrepareContext {
    PrepareContext::new(SampleSpec::new(48_000, 1, SampleFormat::F32Interleaved))
}

#[test]
fn given_product_plan_when_prepared_then_two_sources_and_six_workers_are_owned() {
    let live_nodes = Arc::new(AtomicUsize::new(0));
    let (node_registry, endpoint_registry) =
        registries(ExecutionPartition::AsyncWorker, &live_nodes);
    let compiled = SessionCompiler::new(&node_registry, &endpoint_registry)
        .compile(product_spec())
        .expect("product Session must compile");

    let prepared = prepare_session_runtime(compiled, &node_registry, &prepare_context(), 8)
        .expect("runtime preparation must succeed");

    assert_eq!(prepared.source_mappings().len(), 2);
    assert_eq!(prepared.source_input_count(), 2);
    assert_eq!(prepared.worker_mappings().len(), 6);
    assert!(prepared
        .source_mappings()
        .iter()
        .all(|mapping| mapping.sender_observations().queue_capacity_frames == 8));
    assert_eq!(
        prepared
            .source_inputs
            .iter()
            .map(PlanSourceInput::source_node_id)
            .collect::<HashSet<_>>()
            .len(),
        2
    );
    assert_eq!(
        prepared
            .worker_mappings()
            .iter()
            .map(PreparedWorkerMapping::route_id)
            .collect::<HashSet<_>>()
            .len(),
        6
    );
    assert_eq!(
        prepared
            .worker_mappings()
            .iter()
            .map(|mapping| mapping.receiver.edge_id())
            .collect::<HashSet<_>>()
            .len(),
        6
    );
    assert_eq!(live_nodes.load(Ordering::Relaxed), 2);
    drop(prepared);
    assert_eq!(live_nodes.load(Ordering::Relaxed), 0);
}

#[test]
fn given_compiled_endpoint_configuration_when_prepared_then_worker_mapping_preserves_it() {
    let live_nodes = Arc::new(AtomicUsize::new(0));
    let (node_registry, endpoint_registry) =
        registries(ExecutionPartition::AsyncWorker, &live_nodes);
    let mut compiled = SessionCompiler::new(&node_registry, &endpoint_registry)
        .compile(product_spec())
        .expect("product Session must compile");
    let (endpoint_node_id, route_id) = compiled
        .graph_ir()
        .nodes
        .iter()
        .find_map(|node| match compiled.bindings().node(node.id()) {
            Some(CompiledNodeBinding::Endpoint { route_id, .. }) => {
                Some((node.id(), route_id.to_owned()))
            }
            _ => None,
        })
        .expect("compiled endpoint node must carry typed route identity");
    let endpoint_node = compiled
        .graph_ir_mut()
        .nodes
        .iter_mut()
        .find(|node| node.id() == endpoint_node_id)
        .expect("compiled endpoint node");
    endpoint_node.spec.config = endpoint_node
        .spec
        .config
        .clone()
        .with("compiled_test_marker", "authoritative");

    let prepared = prepare_session_runtime(compiled, &node_registry, &prepare_context(), 8)
        .expect("runtime preparation must succeed");
    let mapping = prepared
        .worker_mappings()
        .iter()
        .find(|mapping| mapping.route_id() == route_id)
        .expect("prepared route mapping");

    assert_eq!(
        mapping.node_configuration().get("compiled_test_marker"),
        Some("authoritative")
    );
}

#[test]
fn given_worker_partition_mismatch_when_prepared_then_error_is_typed_and_nodes_roll_back() {
    let live_nodes = Arc::new(AtomicUsize::new(0));
    let (node_registry, endpoint_registry) =
        registries(ExecutionPartition::RealtimeCpu, &live_nodes);
    let compiled = SessionCompiler::new(&node_registry, &endpoint_registry)
        .compile(product_spec())
        .expect("mismatched product Session must still compile");

    let result = prepare_session_runtime(compiled, &node_registry, &prepare_context(), 8);

    assert!(matches!(
        result,
        Err(SessionPrepareError::WorkerTopologyMismatch {
            expected: 6,
            actual: 0,
            expected_operator_inputs: 0,
            actual_operator_inputs: 0,
            expected_signal_endpoints: 0,
            actual_signal_endpoints: 0,
        })
    ));
    assert_eq!(live_nodes.load(Ordering::Relaxed), 0);
}

#[test]
fn given_unknown_worker_route_when_prepared_then_error_is_typed_and_nodes_roll_back() {
    let live_nodes = Arc::new(AtomicUsize::new(0));
    let (node_registry, endpoint_registry) =
        registries(ExecutionPartition::AsyncWorker, &live_nodes);
    let mut compiled = SessionCompiler::new(&node_registry, &endpoint_registry)
        .compile(product_spec())
        .expect("product Session must compile");
    let endpoint_node_id = compiled
        .graph_ir()
        .nodes
        .iter()
        .find(|node| {
            matches!(
                compiled.bindings().node(node.id()),
                Some(CompiledNodeBinding::Endpoint { .. })
            )
        })
        .map(|node| node.id())
        .expect("compiled endpoint node must carry typed route identity");
    let binding = compiled
        .bindings_mut()
        .node_mut(endpoint_node_id)
        .expect("typed endpoint binding");
    let CompiledNodeBinding::Endpoint { route_id, .. } = binding else {
        panic!("endpoint binding");
    };
    *route_id = RouteId(999_999);

    let result = prepare_session_runtime(compiled, &node_registry, &prepare_context(), 8);

    assert!(matches!(
        result,
        Err(SessionPrepareError::UnknownWorkerRoute {
            route_id: RouteId(999_999),
            ..
        })
    ));
    assert_eq!(live_nodes.load(Ordering::Relaxed), 0);
}

#[test]
fn given_zero_source_capacity_when_prepared_then_error_is_typed_and_nodes_roll_back() {
    let live_nodes = Arc::new(AtomicUsize::new(0));
    let (node_registry, endpoint_registry) =
        registries(ExecutionPartition::AsyncWorker, &live_nodes);
    let compiled = SessionCompiler::new(&node_registry, &endpoint_registry)
        .compile(product_spec())
        .expect("product Session must compile");

    let result = prepare_session_runtime(compiled, &node_registry, &prepare_context(), 0);

    assert!(matches!(
        result,
        Err(SessionPrepareError::SourceChannel(
            PlanRunnerError::ZeroSourceCapacity { .. }
        ))
    ));
    assert_eq!(live_nodes.load(Ordering::Relaxed), 0);
}