sim-lib-stream-prelude 0.1.1

Lisp-facing STREAM 6 prelude for memory streams.
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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
use std::sync::{Arc, Mutex};

use sim_citizen_derive::non_citizen;
use sim_kernel::{
    CORE_FUNCTION_CLASS_ID, ClassId, ClassRef, Cx, Error, Expr, Object, ObjectCompat, Result,
    Symbol,
};
use sim_lib_stream_audio::{PcmBuffer, PcmSpec};
use sim_lib_stream_core::{
    MidiPacket, StreamItem, StreamMetadata, StreamPacket, StreamStats, StreamValue,
};

#[non_citizen(
    reason = "live stream handle; reconstruct stream/Metadata and stream/Packet descriptors then open explicitly",
    kind = "handle",
    descriptor = "stream/Metadata"
)]
/// Live handle to a memory stream source, sink, or pipeline.
///
/// A [`StreamHandle`] is a cheap, cloneable reference (an `Arc` inner) to one
/// of four kinds of memory endpoint: a pull source, a PCM sink, a MIDI sink, or
/// a pipeline that connects a source to an optional sink. Reads
/// ([`StreamHandle::next_packet`]), writes ([`StreamHandle::write_packet`]), and
/// whole-stream runs ([`StreamHandle::run`]) are dispatched on the handle kind
/// and fail closed when invoked on an endpoint that does not support them.
#[derive(Clone)]
pub struct StreamHandle {
    inner: Arc<HandleInner>,
}

struct HandleInner {
    metadata: StreamMetadata,
    kind: HandleKind,
}

enum HandleKind {
    Source {
        stream: Arc<StreamValue>,
    },
    PcmSink {
        spec: PcmSpec,
        state: Mutex<SinkState>,
    },
    MidiSink {
        tpq: u16,
        state: Mutex<SinkState>,
    },
    Pipeline {
        source: StreamHandle,
        sink: Option<StreamHandle>,
    },
}

/// Summary of one [`StreamHandle::run`] over a source or pipeline.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct RunReport {
    /// Number of packets pulled from the source.
    pub packets: usize,
    /// Number of packets written into the sink (zero when there is no sink).
    pub written: usize,
}

/// Kind of pipeline stage carried by a [`StageHandle`].
#[derive(Clone, Debug)]
pub enum StageKind {
    /// Pass-through stage that forwards every packet unchanged.
    Identity,
}

#[non_citizen(
    reason = "live stream stage handle; reconstruct stream/StageDescriptor then realize explicitly",
    kind = "handle",
    descriptor = "stream/StageDescriptor"
)]
/// Handle to a pipeline stage placed between a source and a sink.
///
/// In STREAM 6 the only stage is the identity stage (see
/// [`StageHandle::identity`]); `stream/pipe` accepts identity stages and rejects
/// any other stage kind.
#[derive(Clone, Debug)]
pub struct StageHandle {
    kind: StageKind,
}

#[derive(Clone, Debug, Default)]
struct SinkState {
    packets: Vec<StreamPacket>,
    stats: StreamStats,
    closed: bool,
}

impl StreamHandle {
    /// Builds a pull-source handle backed by the given stream value.
    pub fn source(metadata: StreamMetadata, stream: Arc<StreamValue>) -> Self {
        Self::new(metadata, HandleKind::Source { stream })
    }

    /// Builds a PCM sink handle that validates writes against `spec`.
    pub fn pcm_sink(metadata: StreamMetadata, spec: PcmSpec) -> Self {
        Self::new(
            metadata,
            HandleKind::PcmSink {
                spec,
                state: Mutex::new(SinkState::default()),
            },
        )
    }

    /// Builds a MIDI sink handle that validates writes against `tpq`.
    pub fn midi_sink(metadata: StreamMetadata, tpq: u16) -> Self {
        Self::new(
            metadata,
            HandleKind::MidiSink {
                tpq,
                state: Mutex::new(SinkState::default()),
            },
        )
    }

    /// Builds a pipeline handle from a source-like handle and optional sink.
    ///
    /// # Errors
    ///
    /// Returns an error when `source` is not source-like, or when `sink` is
    /// present but is not a sink handle.
    pub fn pipeline(source: StreamHandle, sink: Option<StreamHandle>) -> Result<Self> {
        if !source.is_source_like() {
            return Err(Error::Eval(
                "stream/pipe expects a source stream first".to_owned(),
            ));
        }
        if sink.as_ref().is_some_and(|handle| !handle.is_sink()) {
            return Err(Error::Eval(
                "stream/pipe sink position must be a sink handle".to_owned(),
            ));
        }
        Ok(Self::new(
            source.metadata().clone(),
            HandleKind::Pipeline { source, sink },
        ))
    }

    fn new(metadata: StreamMetadata, kind: HandleKind) -> Self {
        Self {
            inner: Arc::new(HandleInner { metadata, kind }),
        }
    }

    /// Returns the stream metadata describing this handle.
    pub fn metadata(&self) -> &StreamMetadata {
        &self.inner.metadata
    }

    /// Returns `true` when this handle is a PCM or MIDI sink.
    pub fn is_sink(&self) -> bool {
        matches!(
            self.inner.kind,
            HandleKind::PcmSink { .. } | HandleKind::MidiSink { .. }
        )
    }

    /// Returns `true` when this handle is a pipeline that drives a sink.
    pub fn is_pipeline_with_sink(&self) -> bool {
        matches!(&self.inner.kind, HandleKind::Pipeline { sink: Some(_), .. })
    }

    /// Pulls the next packet from a source or pipeline source.
    ///
    /// Returns `Ok(None)` once the stream is exhausted.
    ///
    /// # Errors
    ///
    /// Returns an error when called on a sink handle, or when the underlying
    /// source fails to produce the next packet.
    pub fn next_packet(&self) -> Result<Option<StreamItem>> {
        match &self.inner.kind {
            HandleKind::Source { stream } => stream.next_packet(),
            HandleKind::Pipeline { source, .. } => source.next_packet(),
            HandleKind::PcmSink { .. } | HandleKind::MidiSink { .. } => Err(Error::Eval(
                "stream/next! expects a source stream handle".to_owned(),
            )),
        }
    }

    /// Writes one packet into a PCM or MIDI sink.
    ///
    /// # Errors
    ///
    /// Returns an error when called on a non-sink handle, when the packet media
    /// does not match the sink, or when the packet fails sink validation.
    pub fn write_packet(&self, packet: StreamPacket) -> Result<()> {
        match &self.inner.kind {
            HandleKind::PcmSink { spec, state } => {
                let StreamPacket::Pcm(pcm) = &packet else {
                    return Err(Error::Eval(
                        "PCM memory sink expects PCM stream packets".to_owned(),
                    ));
                };
                PcmBuffer::from_packet(*spec, pcm)?;
                write_sink_packet(state, packet)
            }
            HandleKind::MidiSink { tpq, state } => {
                let StreamPacket::Midi(midi) = &packet else {
                    return Err(Error::Eval(
                        "MIDI memory sink expects MIDI stream packets".to_owned(),
                    ));
                };
                ensure_midi_tpq(*tpq, midi)?;
                write_sink_packet(state, packet)
            }
            HandleKind::Source { .. } | HandleKind::Pipeline { .. } => Err(Error::Eval(
                "stream/write! expects a sink stream handle".to_owned(),
            )),
        }
    }

    /// Drains a source or pipeline to completion, returning a [`RunReport`].
    ///
    /// For a pipeline with a sink, every pulled packet is written into the sink
    /// and the sink is closed at the end.
    ///
    /// # Errors
    ///
    /// Returns an error when called on a bare sink handle, or when reading or
    /// writing a packet fails.
    pub fn run(&self) -> Result<RunReport> {
        match &self.inner.kind {
            HandleKind::Source { .. } => {
                let mut report = RunReport::default();
                while self.next_packet()?.is_some() {
                    report.packets += 1;
                }
                Ok(report)
            }
            HandleKind::Pipeline { source, sink } => run_pipeline(source, sink.as_ref()),
            HandleKind::PcmSink { .. } | HandleKind::MidiSink { .. } => Err(Error::Eval(
                "stream/run! expects a source or pipeline handle".to_owned(),
            )),
        }
    }

    /// Cancels the stream, marking sources and sinks closed and cancelled.
    ///
    /// Cancelling a pipeline cancels its source and sink in turn.
    ///
    /// # Errors
    ///
    /// Returns an error when a sink lock is poisoned or a source cancel fails.
    pub fn cancel(&self) -> Result<()> {
        match &self.inner.kind {
            HandleKind::Source { stream } => stream.cancel(),
            HandleKind::Pipeline { source, sink } => {
                source.cancel()?;
                if let Some(sink) = sink {
                    sink.cancel()?;
                }
                Ok(())
            }
            HandleKind::PcmSink { state, .. } | HandleKind::MidiSink { state, .. } => {
                let mut state = state
                    .lock()
                    .map_err(|_| Error::PoisonedLock("stream sink"))?;
                state.closed = true;
                state.stats.closed = true;
                state.stats.cancelled = true;
                Ok(())
            }
        }
    }

    /// Returns a snapshot of the stream's runtime statistics.
    ///
    /// # Errors
    ///
    /// Returns an error when a sink lock is poisoned or a source cannot report
    /// its statistics.
    pub fn stats(&self) -> Result<StreamStats> {
        match &self.inner.kind {
            HandleKind::Source { stream } => stream.stats(),
            HandleKind::Pipeline { source, .. } => source.stats(),
            HandleKind::PcmSink { state, .. } | HandleKind::MidiSink { state, .. } => state
                .lock()
                .map_err(|_| Error::PoisonedLock("stream sink"))
                .map(|state| state.stats.clone()),
        }
    }

    /// Returns `true` when the stream has no more work to do.
    ///
    /// A pipeline is done only when both its source and its sink are done.
    ///
    /// # Errors
    ///
    /// Returns an error when a sink lock is poisoned or a source cannot report
    /// its completion state.
    pub fn done(&self) -> Result<bool> {
        match &self.inner.kind {
            HandleKind::Source { stream } => stream.is_done(),
            HandleKind::Pipeline { source, sink } => {
                let source_done = source.done()?;
                let sink_done = match sink {
                    Some(sink) => sink.done()?,
                    None => true,
                };
                Ok(source_done && sink_done)
            }
            HandleKind::PcmSink { state, .. } | HandleKind::MidiSink { state, .. } => state
                .lock()
                .map_err(|_| Error::PoisonedLock("stream sink"))
                .map(|state| state.closed),
        }
    }

    /// Returns a copy of the packets accumulated by a sink handle.
    ///
    /// # Errors
    ///
    /// Returns an error when called on a non-sink handle or when the sink lock
    /// is poisoned.
    pub fn sink_packets(&self) -> Result<Vec<StreamPacket>> {
        match &self.inner.kind {
            HandleKind::PcmSink { state, .. } | HandleKind::MidiSink { state, .. } => state
                .lock()
                .map_err(|_| Error::PoisonedLock("stream sink"))
                .map(|state| state.packets.clone()),
            _ => Err(Error::Eval(
                "stream/sink-packets expects a sink stream handle".to_owned(),
            )),
        }
    }

    /// Renders this handle as a stream graph expression.
    ///
    /// A pipeline renders as a `stream/pipe` call over its source and optional
    /// sink ids; a bare source or sink renders as its id string.
    pub fn graph_lisp_expr(&self) -> Expr {
        match &self.inner.kind {
            HandleKind::Pipeline { source, sink } => {
                let mut args = vec![source.graph_lisp_atom()];
                if let Some(sink) = sink {
                    args.push(sink.graph_lisp_atom());
                }
                Expr::Call {
                    operator: Box::new(Expr::Symbol(Symbol::qualified("stream", "pipe"))),
                    args,
                }
            }
            HandleKind::Source { .. }
            | HandleKind::PcmSink { .. }
            | HandleKind::MidiSink { .. } => self.graph_lisp_atom(),
        }
    }

    fn graph_lisp_atom(&self) -> Expr {
        Expr::String(self.metadata().id().to_string())
    }

    fn is_source_like(&self) -> bool {
        matches!(
            self.inner.kind,
            HandleKind::Source { .. } | HandleKind::Pipeline { .. }
        )
    }

    fn close_sink(&self) -> Result<()> {
        match &self.inner.kind {
            HandleKind::PcmSink { state, .. } | HandleKind::MidiSink { state, .. } => {
                let mut state = state
                    .lock()
                    .map_err(|_| Error::PoisonedLock("stream sink"))?;
                state.closed = true;
                state.stats.closed = true;
                Ok(())
            }
            _ => Ok(()),
        }
    }
}

impl StageHandle {
    /// Builds the identity pass-through stage handle.
    pub fn identity() -> Self {
        Self {
            kind: StageKind::Identity,
        }
    }

    /// Returns `true` when this stage is the identity pass-through stage.
    pub fn is_identity(&self) -> bool {
        matches!(self.kind, StageKind::Identity)
    }
}

impl Object for StreamHandle {
    fn display(&self, _cx: &mut Cx) -> Result<String> {
        Ok(format!("#<stream-handle {}>", self.metadata().id()))
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

impl ObjectCompat for StreamHandle {
    fn class(&self, cx: &mut Cx) -> Result<ClassRef> {
        cx.factory()
            .class_stub(ClassId(0), Symbol::qualified("stream", "Handle"))
    }
}

impl Object for StageHandle {
    fn display(&self, _cx: &mut Cx) -> Result<String> {
        Ok("#<stream-stage identity>".to_owned())
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

impl ObjectCompat for StageHandle {
    fn class(&self, cx: &mut Cx) -> Result<ClassRef> {
        cx.factory()
            .class_stub(CORE_FUNCTION_CLASS_ID, Symbol::qualified("stream", "Stage"))
    }
}

fn run_pipeline(source: &StreamHandle, sink: Option<&StreamHandle>) -> Result<RunReport> {
    let mut report = RunReport::default();
    while let Some(item) = source.next_packet()? {
        report.packets += 1;
        if let Some(sink) = sink {
            sink.write_packet(item.packet().clone())?;
            report.written += 1;
        }
    }
    if let Some(sink) = sink {
        sink.close_sink()?;
    }
    Ok(report)
}

fn write_sink_packet(state: &Mutex<SinkState>, packet: StreamPacket) -> Result<()> {
    let mut state = state
        .lock()
        .map_err(|_| Error::PoisonedLock("stream sink"))?;
    if state.closed {
        return Err(Error::Eval(
            "cannot write to a closed stream sink".to_owned(),
        ));
    }
    state.stats.pushed += 1;
    state.stats.accepted += 1;
    state.packets.push(packet);
    Ok(())
}

fn ensure_midi_tpq(expected: u16, packet: &MidiPacket) -> Result<()> {
    if packet.tpq() != expected {
        return Err(Error::Eval(format!(
            "MIDI packet TPQ {} does not match sink TPQ {expected}",
            packet.tpq()
        )));
    }
    Ok(())
}