rill-core 0.5.0-beta.1

Core foundation for the Rill ecosystem — traits, math, buffers, queues, time, macros
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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
//! Core node traits for the Rill ecosystem
//!
//! Defines the fundamental building blocks of the signal graph:
//! - `SignalNode`: Base trait for all nodes
//! - `Source`: Active generator (has no inputs)
//! - `Processor`: Passive processor (has inputs and outputs)
//! - `Sink`: Active consumer (has no outputs)

use crate::queues::signal::SetParameter;
use crate::time::ClockTick;
use crate::traits::param::{ParamMetadata, ParamValue, ParameterId};
use crate::traits::ProcessResult;
use std::any::TypeId;
use std::fmt;

// ============================================================================
// Node Identification
// ============================================================================

/// Unique identifier for a node in the graph
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct NodeId(pub u32);

impl NodeId {
    /// Create a new node ID
    pub const fn new(id: u32) -> Self {
        Self(id)
    }

    /// Get the inner value
    pub const fn inner(&self) -> u32 {
        self.0
    }
}

impl fmt::Display for NodeId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Node({})", self.0)
    }
}

impl From<u32> for NodeId {
    fn from(id: u32) -> Self {
        Self(id)
    }
}

// ============================================================================
// Node Category
// ============================================================================

/// Category of a node (for UI/organization)
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum NodeCategory {
    /// Source nodes (generators)
    Source,

    /// Processor nodes (effects, filters)
    Processor,

    /// Sink nodes (outputs)
    Sink,

    /// Utility nodes (routing, mixing)
    Utility,

    /// Analyzer nodes (meters, scopes)
    Analyzer,

    /// Sequencer nodes (pattern generators)
    Sequencer,
}

impl NodeCategory {
    /// Get the name of the category
    pub const fn name(&self) -> &'static str {
        match self {
            Self::Source => "source",
            Self::Processor => "processor",
            Self::Sink => "sink",
            Self::Utility => "utility",
            Self::Analyzer => "analyzer",
            Self::Sequencer => "sequencer",
        }
    }
}

impl fmt::Display for NodeCategory {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.name())
    }
}

// ============================================================================
// Node Type ID
// ============================================================================

/// Type identifier for a node (for downcasting)
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct NodeTypeId(TypeId);

impl NodeTypeId {
    /// Create a new node type ID from a type
    pub fn of<T: 'static + ?Sized>() -> Self {
        Self(TypeId::of::<T>())
    }

    /// Get the inner TypeId
    pub fn as_type_id(&self) -> TypeId {
        self.0
    }
}

// ============================================================================
// Node Metadata
// ============================================================================

/// Metadata about a node
#[derive(Debug, Clone)]
pub struct NodeMetadata {
    /// Name of the node
    pub name: String,

    /// Canonical type name used for serialization / factory lookup
    /// (e.g. `Some("rill/sine_osc")`). When `None`, [`NodeMetadata::name`] is used instead.
    pub type_name: Option<String>,

    /// Category of the node
    pub category: NodeCategory,

    /// Description of what the node does
    pub description: String,

    /// Author of the node
    pub author: String,

    /// Version of the node
    pub version: String,

    /// Number of signal input ports
    pub signal_inputs: usize,

    /// Number of signal output ports
    pub signal_outputs: usize,

    /// Number of control input ports
    pub control_inputs: usize,

    /// Number of control output ports
    pub control_outputs: usize,

    /// Number of clock input ports
    pub clock_inputs: usize,

    /// Number of clock output ports
    pub clock_outputs: usize,

    /// Number of feedback ports
    pub feedback_ports: usize,

    /// Parameters exposed by the node
    pub parameters: Vec<ParamMetadata>,
}

impl NodeMetadata {
    /// Create new node metadata with minimal info
    pub fn new(name: &str, category: NodeCategory) -> Self {
        Self {
            type_name: None,
            name: name.to_string(),
            category,
            description: String::new(),
            author: String::new(),
            version: String::new(),
            signal_inputs: 0,
            signal_outputs: 0,
            control_inputs: 0,
            control_outputs: 0,
            clock_inputs: 0,
            clock_outputs: 0,
            feedback_ports: 0,
            parameters: Vec::new(),
        }
    }
}

// ============================================================================
// Node State
// ============================================================================

/// State of a node during processing
/// State of a node during processing
#[derive(Debug, Clone)]
pub struct NodeState<T: crate::math::Transcendental, const BUF_SIZE: usize> {
    /// Current sample position
    pub sample_pos: u64,

    /// Number of processed blocks
    pub blocks_processed: u64,

    /// Sample rate
    pub sample_rate: f32,

    /// Whether the node is active
    pub active: bool,

    /// Internal phase (for generators)
    pub phase: T,
}

impl<T: crate::math::Transcendental, const BUF_SIZE: usize> NodeState<T, BUF_SIZE> {
    /// Create new node state
    pub fn new(sample_rate: f32) -> Self {
        Self {
            sample_pos: 0,
            blocks_processed: 0,
            sample_rate,
            active: true,
            phase: T::ZERO,
        }
    }

    /// Advance state by one block
    pub fn advance(&mut self) {
        self.sample_pos += BUF_SIZE as u64;
        self.blocks_processed += 1;
    }

    /// Get current time in seconds
    pub fn current_time_seconds(&self) -> f64 {
        self.sample_pos as f64 / self.sample_rate as f64
    }

    /// Reset state
    pub fn reset(&mut self) {
        self.sample_pos = 0;
        self.blocks_processed = 0;
        self.phase = T::ZERO;
    }
}

// ============================================================================
// SignalNode Trait (Base for all nodes)
// ============================================================================

/// Base trait for all audio nodes
///
/// This trait provides the fundamental operations that every node must implement:
/// - Port counting
/// - Parameter access
/// - Initialization and reset
/// - Optional telemetry sender
///
/// The actual processing is split into specialized traits:
/// - `Source` for generators
/// - `Processor` for processors with inputs/outputs
/// - `Sink` for consumers
pub trait SignalNode<T: crate::math::Transcendental, const BUF_SIZE: usize>: Send + Sync {
    /// Get node metadata
    fn metadata(&self) -> NodeMetadata;

    /// Get the node's type ID
    fn node_type_id(&self) -> NodeTypeId
    where
        Self: 'static + Sized,
    {
        NodeTypeId::of::<Self>()
    }

    /// Initialize the node with a sample rate
    fn init(&mut self, sample_rate: f32);

    /// Reset the node to its initial state
    fn reset(&mut self);

    /// Get the value of a parameter
    fn get_parameter(&self, id: &ParameterId) -> Option<ParamValue>;

    /// Set the value of a parameter
    fn set_parameter(&mut self, id: &ParameterId, value: ParamValue) -> ProcessResult<()>;

    /// Apply a `SetParameter` command to this node.
    ///
    /// Routes the command to the appropriate port based on `cmd.port`.
    /// Falls back to `set_parameter()` when the port is not found.
    fn apply_set_parameter(&mut self, cmd: &SetParameter) -> ProcessResult<()> {
        use crate::traits::port::{PortDirection, PortType};
        let value = T::from_f32(cmd.value);
        let port = match cmd.port.port_type() {
            PortType::Control => self.control_port_mut(cmd.port.index() as usize),
            PortType::Signal => match cmd.port.direction() {
                PortDirection::Input => self.input_port_mut(cmd.port.index() as usize),
                PortDirection::Output => self.output_port_mut(cmd.port.index() as usize),
            },
            PortType::Param => self.input_port_mut(cmd.port.index() as usize),
            PortType::Clock | PortType::Feedback => None,
        };
        match port {
            Some(p) => {
                p.set_value(value);
                Ok(())
            }
            None => self.set_parameter(&cmd.parameter, ParamValue::Float(cmd.value)),
        }
    }

    /// Get node ID
    fn id(&self) -> NodeId;

    /// Set node ID
    fn set_id(&mut self, id: NodeId);

    /// Get input port by index
    fn input_port(&self, index: usize) -> Option<&crate::traits::port::Port<T, BUF_SIZE>>;

    /// Get mutable input port by index
    fn input_port_mut(
        &mut self,
        index: usize,
    ) -> Option<&mut crate::traits::port::Port<T, BUF_SIZE>>;

    /// Get output port by index
    fn output_port(&self, index: usize) -> Option<&crate::traits::port::Port<T, BUF_SIZE>>;

    /// Get mutable output port by index
    fn output_port_mut(
        &mut self,
        index: usize,
    ) -> Option<&mut crate::traits::port::Port<T, BUF_SIZE>>;

    /// Get control port by index
    fn control_port(&self, index: usize) -> Option<&crate::traits::port::Port<T, BUF_SIZE>>;

    /// Get mutable control port by index
    fn control_port_mut(
        &mut self,
        index: usize,
    ) -> Option<&mut crate::traits::port::Port<T, BUF_SIZE>>;

    /// Get node state
    fn state(&self) -> &NodeState<T, BUF_SIZE>;

    /// Get mutable node state
    fn state_mut(&mut self) -> &mut NodeState<T, BUF_SIZE>;

    // ========================================================================
    // Port Counting (with defaults)
    // ========================================================================

    /// Number of signal input ports
    fn num_signal_inputs(&self) -> usize {
        0
    }

    /// Number of signal output ports
    fn num_signal_outputs(&self) -> usize {
        0
    }

    /// Number of control input ports
    fn num_control_inputs(&self) -> usize {
        0
    }

    /// Number of control output ports
    fn num_control_outputs(&self) -> usize {
        0
    }

    /// Number of clock input ports
    fn num_clock_inputs(&self) -> usize {
        0
    }

    /// Number of clock output ports
    fn num_clock_outputs(&self) -> usize {
        0
    }

    /// Number of feedback ports
    fn num_feedback_ports(&self) -> usize {
        0
    }

    /// Total number of input ports
    fn num_inputs(&self) -> usize {
        self.num_signal_inputs()
            + self.num_control_inputs()
            + self.num_clock_inputs()
            + self.num_feedback_ports()
    }

    /// Total number of output ports
    fn num_outputs(&self) -> usize {
        self.num_signal_outputs() + self.num_control_outputs() + self.num_clock_outputs()
    }

    /// Attach a telemetry sender to this node.
    ///
    /// Nodes that push telemetry (e.g. clock tick from a hardware source)
    /// should store this sender and use it from their `generate()` /
    /// `process()` / `consume()` methods via `TelemetryTx::try_send`.
    /// Default is no-op — override only in nodes that produce telemetry.
    fn set_telemetry_tx(&mut self, _tx: crate::queues::telemetry::TelemetryTx) {
    }
}

// ============================================================================
// Source Trait (Active generators)
// ============================================================================

/// Active source of signals
///
/// Sources generate audio from internal state. They have no audio inputs,
/// but may have control and clock inputs for modulation.
pub trait Source<T: crate::math::Transcendental, const BUF_SIZE: usize>: SignalNode<T, BUF_SIZE> {
    /// Generate the next block of audio
    ///
    /// # Arguments
    /// * `clock` - Current clock tick
    /// * `control_inputs` - Control signal values (one per control input)
    /// * `clock_inputs` - Clock signal values (one per clock input)
    ///
    /// The source writes output samples into its own output port buffers,
    /// accessible via `self.output_port_mut(index)`.
    fn generate(
        &mut self,
        clock: &ClockTick,
        control_inputs: &[T],
        clock_inputs: &[ClockTick],
    ) -> ProcessResult<()>;

    /// Number of audio outputs (default 1)
    fn num_signal_outputs(&self) -> usize {
        1
    }

    /// Number of control inputs (default 0)
    fn num_control_inputs(&self) -> usize {
        0
    }

    /// Number of clock inputs (default 0)
    fn num_clock_inputs(&self) -> usize {
        0
    }
}

// ============================================================================
// Processor Trait (Passive processors)
// ============================================================================

/// Passive processor of signals
///
/// Processors transform input signals into output signals.
/// They have audio inputs and outputs, and may have control and clock ports.
pub trait Processor<T: crate::math::Transcendental, const BUF_SIZE: usize>:
    SignalNode<T, BUF_SIZE>
{
    /// Process a block of audio
    ///
    /// # Arguments
    /// * `clock` - Current clock tick
    /// * `signal_inputs` - Audio input buffers (one per audio input)
    /// * `control_inputs` - Control signal values (one per control input)
    /// * `clock_inputs` - Clock signal values (one per clock input)
    /// * `feedback_inputs` - Feedback values from previous blocks (one per feedback port)
    ///
    /// The processor writes output samples into its own output port buffers,
    /// accessible via `self.output_port_mut(index)`.
    fn process(
        &mut self,
        clock: &ClockTick,
        signal_inputs: &[&[T; BUF_SIZE]],
        control_inputs: &[T],
        clock_inputs: &[ClockTick],
        feedback_inputs: &[&[T; BUF_SIZE]],
    ) -> ProcessResult<()>;

    /// Latency in samples (for delay compensation)
    fn latency(&self) -> usize {
        0
    }
}

// ============================================================================
// Sink Trait (Active consumers)
// ============================================================================

/// Active sink of signals
///
/// Sinks consume audio and send it to external destinations.
/// They have no audio outputs, but may have control and clock ports.
pub trait Sink<T: crate::math::Transcendental, const BUF_SIZE: usize>: SignalNode<T, BUF_SIZE> {
    /// Consume a block of audio
    ///
    /// # Arguments
    /// * `clock` - Current clock tick
    /// * `signal_inputs` - Audio input buffers (one per audio input)
    /// * `control_inputs` - Control signal values (one per control input)
    /// * `clock_inputs` - Clock signal values (one per clock input)
    /// * `feedback_inputs` - Feedback values from previous blocks
    fn consume(
        &mut self,
        clock: &ClockTick,
        signal_inputs: &[&[T; BUF_SIZE]],
        control_inputs: &[T],
        clock_inputs: &[ClockTick],
        feedback_inputs: &[&[T; BUF_SIZE]],
    ) -> ProcessResult<()>;
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_node_id() {
        let id = NodeId::new(42);
        assert_eq!(id.inner(), 42);
        assert_eq!(format!("{}", id), "Node(42)");
    }

    #[test]
    fn test_node_category() {
        assert_eq!(NodeCategory::Source.name(), "source");
        assert_eq!(NodeCategory::Processor.name(), "processor");
        assert_eq!(NodeCategory::Sink.name(), "sink");
        assert_eq!(NodeCategory::Utility.name(), "utility");
    }

    #[test]
    fn test_node_metadata_new() {
        let metadata = NodeMetadata::new("Test", NodeCategory::Source);
        assert_eq!(metadata.name, "Test");
        assert_eq!(metadata.category, NodeCategory::Source);
    }

    #[test]
    fn test_node_state() {
        let mut state = NodeState::<f32, 64>::new(44100.0);
        assert_eq!(state.sample_pos, 0);
        assert_eq!(state.sample_rate, 44100.0);

        state.advance();
        assert_eq!(state.sample_pos, 64);
        assert_eq!(state.blocks_processed, 1);

        state.reset();
        assert_eq!(state.sample_pos, 0);
        assert_eq!(state.blocks_processed, 0);
    }
}