firewheel-core 0.12.0

Shared types for Firewheel crates
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
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
use core::any::TypeId;
use core::error::Error;
use core::fmt;
use core::marker::PhantomData;
use core::ops::Range;
use core::time::Duration;
use core::{any::Any, fmt::Debug, hash::Hash, num::NonZeroU32};

#[cfg(feature = "std")]
use std::collections::hash_map::{Entry, HashMap};

#[cfg(not(feature = "std"))]
use bevy_platform::collections::hash_map::{Entry, HashMap};
#[cfg(not(feature = "std"))]
use bevy_platform::prelude::{Box, Vec};

use crate::dsp::buffer::ConstSequentialBuffer;
use crate::dsp::volume::is_buffer_silent;
use crate::log::RealtimeLogger;
use crate::mask::{ConnectedMask, ConstantMask, MaskType, SilenceMask};
use crate::{
    StreamInfo,
    channel_config::{ChannelConfig, ChannelCount},
    clock::{DurationSamples, InstantSamples, InstantSeconds},
    dsp::declick::DeclickValues,
    event::{NodeEvent, NodeEventType, ProcEvents},
};

#[cfg(feature = "scheduled_events")]
use crate::clock::EventInstant;

#[cfg(feature = "musical_transport")]
use crate::clock::{InstantMusical, MusicalTransport};

/// A globally unique identifier for a node.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "bevy_reflect", derive(bevy_reflect::Reflect))]
#[cfg_attr(feature = "bevy_reflect", reflect(opaque))]
pub struct NodeID(pub thunderdome::Index);

impl NodeID {
    pub const DANGLING: Self = Self(thunderdome::Index::DANGLING);
}

impl Default for NodeID {
    fn default() -> Self {
        Self::DANGLING
    }
}

/// Trait-based catchall error type for node trait methods
#[derive(Debug)]
pub struct NodeError(pub Box<dyn Error>);

impl NodeError {
    pub const fn from_boxed(error: Box<dyn Error>) -> Self {
        Self(error)
    }
}

impl<E> From<E> for NodeError
where
    E: Error + 'static,
{
    fn from(err: E) -> Self {
        NodeError(Box::new(err))
    }
}

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

impl From<NodeError> for Box<dyn Error> {
    fn from(value: NodeError) -> Self {
        value.0
    }
}

/// Information about an [`AudioNode`].
///
/// This struct enforces the use of the builder pattern for future-proof-ness, as
/// it is likely that more fields will be added in the future.
#[derive(Debug)]
pub struct AudioNodeInfo {
    debug_name: &'static str,
    channel_config: ChannelConfig,
    call_update_method: bool,
    custom_state: Option<Box<dyn Any>>,
    latency_frames: u32,
    in_place_buffers: bool,
}

impl AudioNodeInfo {
    /// Construct a new [`AudioNodeInfo`] builder struct.
    pub const fn new() -> Self {
        Self {
            debug_name: "unnamed",
            channel_config: ChannelConfig {
                num_inputs: ChannelCount::ZERO,
                num_outputs: ChannelCount::ZERO,
            },
            call_update_method: false,
            custom_state: None,
            latency_frames: 0,
            in_place_buffers: false,
        }
    }

    /// A unique name for this type of node, used for debugging purposes.
    pub const fn debug_name(mut self, debug_name: &'static str) -> Self {
        self.debug_name = debug_name;
        self
    }

    /// The channel configuration of this node.
    ///
    /// By default this has a channel configuration with zero input and output
    /// channels.
    ///
    /// WARNING: Audio nodes *MUST* either completely fill all output buffers
    /// with data, or return [`ProcessStatus::ClearAllOutputs`]/[`ProcessStatus::Bypass`].
    /// Failing to do this will result in audio glitches.
    pub const fn channel_config(mut self, channel_config: ChannelConfig) -> Self {
        self.channel_config = channel_config;
        self
    }

    /// Specify that this node is a "pre process" node. Pre-process nodes have zero
    /// inputs and outputs, and they are processed before all other nodes in the
    /// graph.
    pub const fn is_pre_process(mut self) -> Self {
        self.channel_config = ChannelConfig {
            num_inputs: ChannelCount::ZERO,
            num_outputs: ChannelCount::ZERO,
        };
        self
    }

    /// Set to `true` if this node wishes to have the Firewheel context call
    /// [`AudioNode::update`] on every update cycle.
    ///
    /// By default this is set to `false`.
    pub const fn call_update_method(mut self, call_update_method: bool) -> Self {
        self.call_update_method = call_update_method;
        self
    }

    /// Custom `!Send` state that can be stored in the Firewheel context and accessed
    /// by the user.
    ///
    /// The user accesses this state via `FirewheelCtx::node_state` and
    /// `FirewheelCtx::node_state_mut`.
    pub fn custom_state<T: 'static>(mut self, custom_state: T) -> Self {
        self.custom_state = Some(Box::new(custom_state));
        self
    }

    /// Set the latency of this node in frames (samples in a single channel of audio).
    ///
    /// By default this is set to `0`.
    pub const fn latency_frames(mut self, latency_frames: u32) -> Self {
        self.latency_frames = latency_frames;
        self
    }

    /// If set to `true`, then the input buffers will be merged into the output
    /// buffers. This may improve performance in cases where this node is commonly used
    /// in a serial chain such as when in a node pool.
    ///
    /// If the number of input channels is greater than the number of output channels,
    /// then the input buffers passed into [`AudioNodeProcessor::process`] will contain
    /// ONLY the input buffers in the range `[num_outputs_in_config..num_inputs_in_config]`.
    /// Otherwise, the number of input buffers will be 0.
    ///
    /// Note, this currently doesn't improve performance. But if and when the scheduler
    /// is updated to support in-place buffer processing in a future version, then it
    /// will.
    pub const fn in_place_buffers(mut self, in_place_buffers: bool) -> Self {
        self.in_place_buffers = in_place_buffers;
        self
    }
}

impl Default for AudioNodeInfo {
    fn default() -> Self {
        Self::new()
    }
}

impl From<AudioNodeInfo> for AudioNodeInfoInner {
    fn from(value: AudioNodeInfo) -> Self {
        AudioNodeInfoInner {
            debug_name: value.debug_name,
            channel_config: value.channel_config,
            call_update_method: value.call_update_method,
            custom_state: value.custom_state,
            latency_frames: value.latency_frames,
            in_place_buffers: value.in_place_buffers,
        }
    }
}

/// Information about an [`AudioNode`]. Used internally by the Firewheel context.
#[derive(Debug)]
pub struct AudioNodeInfoInner {
    pub debug_name: &'static str,
    pub channel_config: ChannelConfig,
    pub call_update_method: bool,
    pub custom_state: Option<Box<dyn Any>>,
    pub latency_frames: u32,
    pub in_place_buffers: bool,
}

/// A trait representing a node in a Firewheel audio graph.
///
/// # Notes about ECS
///
/// In order to be friendlier to ECS's (entity component systems), it is encouraged
/// that any struct deriving this trait be POD (plain ol' data). If you want your
/// audio node to be usable in the Bevy game engine, also derive
/// `bevy_ecs::prelude::Component`. (You can hide this derive behind a feature flag
/// by using `#[cfg_attr(feature = "bevy", derive(bevy_ecs::prelude::Component))]`).
///
/// # Audio Node Lifecycle
///
/// 1. The user constructs the node as POD or from a custom constructor method for
///    that node.
/// 2. The user adds the node to the graph using `FirewheelCtx::add_node`. If the
///    node has any custom configuration, then the user passes that configuration to this
///    method as well. In this method, the Firewheel context calls [`AudioNode::info`] to
///    get information about the node. The node can also store any custom state in the
///    [`AudioNodeInfo`] struct.
/// 3. At this point the user may now call `FirewheelCtx::node_state` and
///    `FirewheelCtx::node_state_mut` to retrieve the node's custom state.
/// 4. If [`AudioNodeInfo::call_update_method`] was set to `true`, then
///    [`AudioNode::update`] will be called every time the Firewheel context updates.
///    The node's custom state is also accessible in this method.
/// 5. When the Firewheel context is ready for the node to start processing data,
///    it calls [`AudioNode::construct_processor`] to retrieve the realtime
///    [`AudioNodeProcessor`] counterpart of the node. This processor counterpart is
///    then sent to the audio thread.
/// 6. The Firewheel processor calls [`AudioNodeProcessor::process`] whenever there
///    is a new block of audio data to process.
///    WARNING: Audio nodes *MUST* either completely fill all output buffers
///    with data, or return [`ProcessStatus::ClearAllOutputs`]/[`ProcessStatus::Bypass`].
///    Failing to do this will result in audio glitches.
/// 7. (Graceful shutdown)
///
///    7a. The Firewheel processor calls [`AudioNodeProcessor::stream_stopped`].
///    The processor is then sent back to the main thread.
///
///    7b. If a new audio stream is started, then the context will call
///    [`AudioNodeProcessor::new_stream`] on the main thread, and then send the
///    processor back to the audio thread for processing.
///
///    7c. If the Firewheel context is dropped before a new stream is started, then
///    both the node and the processor counterpart are dropped on the main thread.
/// 8. (Audio thread crashes or stops unexpectedly) - The node's processor counterpart
///    may or may not be dropped. The user may try to create a new audio stream, in which
///    case [`AudioNode::construct_processor`] might be called again. If a second processor
///    instance is not able to be created, or if dropping the processor on the audio thread
///    is unacceptable behavior, then the node may panic.
pub trait AudioNode {
    /// A type representing this constructor's configuration.
    ///
    /// This is intended as a one-time configuration to be used
    /// when constructing an audio node. When no configuration
    /// is required, [`EmptyConfig`] should be used.
    type Configuration: Default;

    /// Get information about this node.
    ///
    /// This method is only called once per instance after the node is added to the
    /// audio graph.
    fn info(&self, configuration: &Self::Configuration) -> Result<AudioNodeInfo, NodeError>;

    /// Construct a realtime processor for this node.
    ///
    /// * `configuration` - The custom configuration of this node.
    /// * `cx` - A context for interacting with the Firewheel context. This context
    ///   also includes information about the audio stream.
    fn construct_processor(
        &self,
        configuration: &Self::Configuration,
        cx: ConstructProcessorContext,
    ) -> Result<impl AudioNodeProcessor, NodeError>;

    /// If [`AudioNodeInfo::call_update_method`] was set to `true`, then the Firewheel
    /// context will call this method on every update cycle.
    ///
    /// * `configuration` - The custom configuration of this node.
    /// * `cx` - A context for interacting with the Firewheel context.
    fn update(&mut self, configuration: &Self::Configuration, cx: UpdateContext) {
        let _ = configuration;
        let _ = cx;
    }
}

/// A context for [`AudioNode::construct_processor`].
pub struct ConstructProcessorContext<'a> {
    /// The ID of this audio node.
    pub node_id: NodeID,
    /// Information about the running audio stream.
    pub stream_info: &'a StreamInfo,
    custom_state: &'a mut Option<Box<dyn Any>>,
}

impl<'a> ConstructProcessorContext<'a> {
    pub fn new(
        node_id: NodeID,
        stream_info: &'a StreamInfo,
        custom_state: &'a mut Option<Box<dyn Any>>,
    ) -> Self {
        Self {
            node_id,
            stream_info,
            custom_state,
        }
    }

    /// Get an immutable reference to the custom state that was created in
    /// [`AudioNodeInfo::custom_state`].
    pub fn custom_state<T: 'static>(&self) -> Option<&T> {
        self.custom_state
            .as_ref()
            .and_then(|s| s.downcast_ref::<T>())
    }

    /// Get a mutable reference to the custom state that was created in
    /// [`AudioNodeInfo::custom_state`].
    pub fn custom_state_mut<T: 'static>(&mut self) -> Option<&mut T> {
        self.custom_state
            .as_mut()
            .and_then(|s| s.downcast_mut::<T>())
    }
}

/// A context for [`AudioNode::update`].
pub struct UpdateContext<'a> {
    /// The ID of this audio node.
    pub node_id: NodeID,
    /// Information about the running audio stream. If no audio stream is running,
    /// then this will be `None`.
    pub stream_info: Option<&'a StreamInfo>,
    custom_state: &'a mut Option<Box<dyn Any>>,
    event_queue: &'a mut Vec<NodeEvent>,
}

impl<'a> UpdateContext<'a> {
    pub fn new(
        node_id: NodeID,
        stream_info: Option<&'a StreamInfo>,
        custom_state: &'a mut Option<Box<dyn Any>>,
        event_queue: &'a mut Vec<NodeEvent>,
    ) -> Self {
        Self {
            node_id,
            stream_info,
            custom_state,
            event_queue,
        }
    }

    /// Queue an event to send to this node's processor counterpart.
    pub fn queue_event(&mut self, event: NodeEventType) {
        self.event_queue.push(NodeEvent {
            node_id: self.node_id,
            #[cfg(feature = "scheduled_events")]
            time: None,
            event,
        });
    }

    /// Queue an event to send to this node's processor counterpart, at a certain time.
    ///
    /// # Performance
    ///
    /// Note that for most nodes that handle scheduled events, this will split the buffer
    /// into chunks and process those chunks. If two events are scheduled too close to one
    /// another in time then that chunk may be too small for the audio processing to be
    /// fully vectorized.
    #[cfg(feature = "scheduled_events")]
    pub fn schedule_event(&mut self, event: NodeEventType, time: EventInstant) {
        self.event_queue.push(NodeEvent {
            node_id: self.node_id,
            time: Some(time),
            event,
        });
    }

    /// Get an immutable reference to the custom state that was created in
    /// [`AudioNodeInfo::custom_state`].
    pub fn custom_state<T: 'static>(&self) -> Option<&T> {
        self.custom_state
            .as_ref()
            .and_then(|s| s.downcast_ref::<T>())
    }

    /// Get a mutable reference to the custom state that was created in
    /// [`AudioNodeInfo::custom_state`].
    pub fn custom_state_mut<T: 'static>(&mut self) -> Option<&mut T> {
        self.custom_state
            .as_mut()
            .and_then(|s| s.downcast_mut::<T>())
    }
}

/// An empty constructor configuration.
///
/// This should be preferred over `()` because it implements
/// Bevy's `Component` trait, making the
/// [`AudioNode`] implementor trivially Bevy-compatible.
#[derive(Debug, Default, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "bevy", derive(bevy_ecs::prelude::Component))]
#[cfg_attr(feature = "bevy_reflect", derive(bevy_reflect::Reflect))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct EmptyConfig;

/// A type-erased dyn-compatible [`AudioNode`].
pub trait DynAudioNode {
    /// Get information about this node.
    ///
    /// This method is only called once after the node is added to the audio graph.
    fn info(&self) -> Result<AudioNodeInfo, NodeError>;

    /// Construct a realtime processor for this node.
    ///
    /// * `cx` - A context for interacting with the Firewheel context. This context
    ///   also includes information about the audio stream.
    fn construct_processor(
        &self,
        cx: ConstructProcessorContext,
    ) -> Result<Box<dyn AudioNodeProcessor>, NodeError>;

    /// If [`AudioNodeInfo::call_update_method`] was set to `true`, then the Firewheel
    /// context will call this method on every update cycle.
    ///
    /// * `cx` - A context for interacting with the Firewheel context.
    fn update(&mut self, cx: UpdateContext) {
        let _ = cx;
    }
}

/// Pairs constructors with their configurations.
///
/// This is useful for type-erasing an [`AudioNode`].
pub struct Constructor<T, C> {
    constructor: T,
    configuration: C,
}

impl<T: AudioNode> Constructor<T, T::Configuration> {
    pub fn new(constructor: T, configuration: Option<T::Configuration>) -> Self {
        Self {
            constructor,
            configuration: configuration.unwrap_or_default(),
        }
    }
}

impl<T: AudioNode> DynAudioNode for Constructor<T, T::Configuration> {
    fn info(&self) -> Result<AudioNodeInfo, NodeError> {
        self.constructor.info(&self.configuration)
    }

    fn construct_processor(
        &self,
        cx: ConstructProcessorContext,
    ) -> Result<Box<dyn AudioNodeProcessor>, NodeError> {
        Ok(Box::new(
            self.constructor
                .construct_processor(&self.configuration, cx)?,
        ))
    }

    fn update(&mut self, cx: UpdateContext) {
        self.constructor.update(&self.configuration, cx);
    }
}

/// The trait describing the realtime processor counterpart to an
/// audio node.
pub trait AudioNodeProcessor: 'static + Send {
    /// Called when there are new events for this node to process.
    ///
    /// This is called once before the first call to `process`, and after that
    /// it will be called whenever there are new events (including when the
    /// node is bypassed).
    ///
    /// Unless this node is bypassed, then [`AudioNodeProcessor::process`] will be
    /// called immediately after.
    ///
    /// * `info` - Information about this processing block.
    /// * `events` - A list of events for this node to process.
    /// * `extra` - Additional buffers and utilities.
    ///
    /// This is always called in a realtime thread, so do not perform any
    /// realtime-unsafe operations.
    fn events(&mut self, info: &ProcInfo, events: &mut ProcEvents, extra: &mut ProcExtra) {
        let _ = info;
        let _ = events;
        let _ = extra;
    }

    /// Called when the node has been fully bypassed/un-bypassed.
    ///
    /// The Firewheel processor automatically handles bypass declicking, so
    /// there is no need to handle that manually.
    ///
    /// This is always called in a realtime thread, so do not perform any
    /// realtime-unsafe operations.
    fn bypassed(&mut self, bypassed: bool) {
        let _ = bypassed;
    }

    /// Process the given block of audio.
    ///
    /// * `info` - Information about this processing block.
    /// * `buffers` - The buffers of data to process.
    /// * `extra` - Additional buffers and utilities.
    ///
    /// WARNING: Audio nodes *MUST* either completely fill all output buffers
    /// with data, or return [`ProcessStatus::ClearAllOutputs`]/[`ProcessStatus::Bypass`].
    /// Failing to do this will result in audio glitches. If using
    /// [`AudioNodeInfo::in_place_buffers`], then the output buffers in the
    /// range `[0..num_inputs_in_config.min(num_outputs_in_config)]` do not
    /// need to be filled with data.
    ///
    /// This is always called in a realtime thread, so do not perform any
    /// realtime-unsafe operations.
    fn process(
        &mut self,
        info: &ProcInfo,
        buffers: ProcBuffers,
        extra: &mut ProcExtra,
    ) -> ProcessStatus {
        let _ = info;
        let _ = buffers;
        let _ = extra;

        ProcessStatus::Bypass
    }

    /// Called when the audio stream has been stopped.
    ///
    /// This may or may not be called in a realtime thread, so prefer not
    /// perform any realtime-unsafe operations.
    fn stream_stopped(&mut self, context: &mut ProcStreamCtx) {
        let _ = context;
    }

    /// Called when a new audio stream has been started after a previous
    /// call to [`AudioNodeProcessor::stream_stopped`].
    ///
    /// This method gets called on the main thread, not the realtime audio
    /// thread. So it is safe to allocate/deallocate here.
    fn new_stream(&mut self, stream_info: &StreamInfo, context: &mut ProcStreamCtx) {
        let _ = stream_info;
        let _ = context;
    }
}

impl AudioNodeProcessor for Box<dyn AudioNodeProcessor> {
    fn events(&mut self, info: &ProcInfo, events: &mut ProcEvents, extra: &mut ProcExtra) {
        self.as_mut().events(info, events, extra);
    }
    fn bypassed(&mut self, bypassed: bool) {
        self.as_mut().bypassed(bypassed);
    }
    fn process(
        &mut self,
        info: &ProcInfo,
        buffers: ProcBuffers,
        extra: &mut ProcExtra,
    ) -> ProcessStatus {
        self.as_mut().process(info, buffers, extra)
    }
    fn stream_stopped(&mut self, context: &mut ProcStreamCtx) {
        self.as_mut().stream_stopped(context)
    }
    fn new_stream(&mut self, stream_info: &StreamInfo, context: &mut ProcStreamCtx) {
        self.as_mut().new_stream(stream_info, context)
    }
}

pub struct ProcStreamCtx<'a> {
    pub store: &'a mut ProcStore,
    pub logger: &'a mut RealtimeLogger,
}

pub const NUM_SCRATCH_BUFFERS: usize = 8;

/// The buffers used in [`AudioNodeProcessor::process`]
#[derive(Debug)]
pub struct ProcBuffers<'a, 'b> {
    /// The audio input buffers.
    ///
    /// The number of channels will always equal the [`ChannelConfig::num_inputs`]
    /// value that was returned in [`AudioNode::info`]. Except when
    /// [`AudioNodeInfo::in_place_buffers`] is used, in which case this will contain
    /// ONLY the input buffers in the range `[num_outputs_in_config..num_inputs_in_config]`.
    ///
    /// Each channel slice will have a length of [`ProcInfo::frames`].
    pub inputs: &'a [&'b [f32]],

    /// The audio output buffers.
    ///
    /// WARNING: The node *MUST* either completely fill all output buffers
    /// with data, or return [`ProcessStatus::ClearAllOutputs`]/[`ProcessStatus::Bypass`].
    /// Failing to do this will result in audio glitches. If using
    /// [`AudioNodeInfo::in_place_buffers`], then the output buffers in the
    /// range `[0..num_inputs_in_config.min(num_outputs_in_config)]` do not
    /// need to be filled with data.
    ///
    /// The number of channels will always equal the [`ChannelConfig::num_outputs`]
    /// value that was returned in [`AudioNode::info`].
    ///
    /// Each channel slice will have a length of [`ProcInfo::frames`].
    ///
    /// These buffers may contain stale data from previous processing cycles.
    /// They are zero-initialized before the first use, so this is not
    /// uninitialized memory, but the contents should not be assumed zero.
    pub outputs: &'a mut [&'b mut [f32]],
}

impl<'a, 'b> ProcBuffers<'a, 'b> {
    /// Thoroughly checks if all output buffers contain silence (as in all
    /// samples have an absolute amplitude less than or equal to `min_amp`).
    ///
    /// If all buffers are silent, then [`ProcessStatus::ClearAllOutputs`] will
    /// be returned. Otherwise, [`ProcessStatus::OutputsModified`] will be
    /// returned.
    pub fn check_for_silence_on_outputs(&self, min_amp: f32) -> ProcessStatus {
        let mut silent = true;
        for buffer in self.outputs.iter() {
            if !is_buffer_silent(buffer, min_amp) {
                silent = false;
                break;
            }
        }

        if silent {
            ProcessStatus::ClearAllOutputs
        } else {
            ProcessStatus::OutputsModified
        }
    }

    /// Returns `true` if the input signal has settled to silence by the end
    /// of the block.
    pub fn inputs_settled_at_zero(&self) -> bool {
        let mut settled_at_zero = true;

        for ch in self.inputs.iter() {
            // Check the last two samples instead of just one since it is
            // incredibly unlikely that an active signal has two exact
            // zeros in a row.
            settled_at_zero = ch.iter().rev().take(2).all(|s| *s == 0.0);

            if !settled_at_zero {
                break;
            }
        }

        settled_at_zero
    }
}

/// Extra buffers and utilities for [`AudioNodeProcessor::process`]
pub struct ProcExtra {
    /// A list of extra scratch buffers that can be used for processing.
    /// This removes the need for nodes to allocate their own scratch buffers.
    /// Each buffer has a length of [`StreamInfo::max_block_frames`]. These
    /// buffers are shared across all nodes, so assume that they contain junk
    /// data.
    pub scratch_buffers: ConstSequentialBuffer<f32, NUM_SCRATCH_BUFFERS>,

    /// A buffer of values that linearly ramp up/down between `0.0` and `1.0`
    /// which can be used to implement efficient declicking when
    /// pausing/resuming/stopping.
    pub declick_values: DeclickValues,

    /// A realtime-safe logger helper.
    pub logger: RealtimeLogger,

    /// A type-erased store accessible to all [`AudioNodeProcessor`]s.
    pub store: ProcStore,
}

/// Information for [`AudioNodeProcessor::process`]
#[derive(Debug)]
pub struct ProcInfo {
    /// The number of frames (samples in a single channel of audio) in
    /// this processing block.
    ///
    /// Not to be confused with video frames.
    pub frames: usize,

    /// An optional optimization hint on which input channels contain
    /// all zeros (silence). The first bit (`0x1`) is the first channel,
    /// the second bit is the second channel, and so on.
    pub in_silence_mask: SilenceMask,

    /// An optional optimization hint on which output channels contain
    /// all zeros (silence). The first bit (`0x1`) is the first channel,
    /// the second bit is the second channel, and so on.
    pub out_silence_mask: SilenceMask,

    /// An optional optimization hint on which input channels have all
    /// samples set to the same value. The first bit (`0x1`) is the
    /// first channel, the second bit is the second channel, and so on.
    ///
    /// This can be useful for nodes that use audio buffers as CV
    /// (control voltage) ports.
    pub in_constant_mask: ConstantMask,

    /// An optional optimization hint on which input channels have all
    /// samples set to the same value. The first bit (`0x1`) is the
    /// first channel, the second bit is the second channel, and so on.
    ///
    /// This can be useful for nodes that use audio buffers as CV
    /// (control voltage) ports.
    pub out_constant_mask: ConstantMask,

    /// An optional hint on which input channels are connected to other
    /// nodes in the graph.
    pub in_connected_mask: ConnectedMask,

    /// An optional hint on which output channels are connected to other
    /// nodes in the graph.
    pub out_connected_mask: ConnectedMask,

    /// The sample rate of the audio stream in samples per second.
    pub sample_rate: NonZeroU32,

    /// The reciprocal of the sample rate. This can be used to avoid a
    /// division and improve performance.
    pub sample_rate_recip: f64,

    /// The current time of the audio clock at the first frame in this
    /// processing block, equal to the total number of frames (samples in
    /// a single channel of audio) that have been processed since this
    /// Firewheel context was first started.
    ///
    /// Note, this value does *NOT* account for any output underflows
    /// (underruns) that may have occurred.
    ///
    /// Note, generally this value will always count up, but there may be
    /// a few edge cases that cause this value to be less than the previous
    /// block, such as when the sample rate of the stream has been changed.
    pub clock_samples: InstantSamples,

    /// The reciprocal of the total amount of seconds that the CPU can
    /// spend in this call to the Firewheel Processor's process method
    /// before underruns will occur.
    ///
    /// This can be used for performance profiling.
    pub total_cpu_seconds_recip: f64,

    /// The duration between when the stream was started an when the
    /// Firewheel processor's `process` method was called.
    ///
    /// Note, this clock is not as accurate as the audio clock.
    pub duration_since_stream_start: Duration,

    /// Flags indicating the current status of the audio stream
    pub stream_status: StreamStatus,

    /// If an output underflow (underrun) occurred, then this will contain
    /// an estimate for the number of frames (samples in a single channel
    /// of audio) that were dropped.
    ///
    /// This can be used to correct the timing of events if desired.
    ///
    /// Note, this is just an estimate, and may not always be perfectly
    /// accurate.
    ///
    /// If an underrun did not occur, then this will be `0`.
    pub dropped_frames: u32,

    /// The estimated time between when this process loop was called and
    /// when the data will be delivered to the output device for playback.
    ///
    /// If the audio backend does not provide this information, then this
    /// will be `None`.
    pub process_to_playback_delay: Option<Duration>,

    /// If the node has just been un-bypassed, then this will be `true`.
    pub did_just_unbypass: bool,

    /// Information about the musical transport.
    ///
    /// This will be `None` if no musical transport is currently active,
    /// or if the current transport is currently paused.
    #[cfg(feature = "musical_transport")]
    pub transport_info: Option<TransportInfo>,
}

impl ProcInfo {
    /// The current time of the audio clock at the first frame in this
    /// processing block, equal to the total number of seconds of data that
    /// have been processed since this Firewheel context was first started.
    ///
    /// Note, this value does *NOT* account for any output underflows
    /// (underruns) that may have occurred.
    ///
    /// Note, generally this value will always count up, but there may be
    /// a few edge cases that cause this value to be less than the previous
    /// block, such as when the sample rate of the stream has been changed.
    pub fn clock_seconds(&self) -> InstantSeconds {
        self.clock_samples
            .to_seconds(self.sample_rate, self.sample_rate_recip)
    }

    /// Get the current time of the audio clock in frames as a range for this
    /// processing block.
    pub fn clock_samples_range(&self) -> Range<InstantSamples> {
        self.clock_samples..self.clock_samples + DurationSamples(self.frames as i64)
    }

    /// Get the current time of the audio clock in frames as a range for this
    /// processing block.
    pub fn clock_seconds_range(&self) -> Range<InstantSeconds> {
        self.clock_seconds()
            ..(self.clock_samples + DurationSamples(self.frames as i64))
                .to_seconds(self.sample_rate, self.sample_rate_recip)
    }

    /// Get the playhead of the transport at the first frame in this processing
    /// block.
    ///
    /// If there is no active transport, or if the transport is not currently
    /// playing, then this will return `None`.
    #[cfg(feature = "musical_transport")]
    pub fn playhead(&self) -> Option<InstantMusical> {
        self.transport_info.as_ref().and_then(|transport_info| {
            transport_info
                .start_clock_samples
                .map(|start_clock_samples| {
                    transport_info.transport.samples_to_musical(
                        self.clock_samples,
                        start_clock_samples,
                        transport_info.speed_multiplier,
                        self.sample_rate,
                        self.sample_rate_recip,
                    )
                })
        })
    }

    /// Get the playhead of the transport as a range for this processing
    /// block.
    ///
    /// If there is no active transport, or if the transport is not currently
    /// playing, then this will return `None`.
    #[cfg(feature = "musical_transport")]
    pub fn playhead_range(&self) -> Option<Range<InstantMusical>> {
        self.transport_info.as_ref().and_then(|transport_info| {
            transport_info
                .start_clock_samples
                .map(|start_clock_samples| {
                    transport_info.transport.samples_to_musical(
                        self.clock_samples,
                        start_clock_samples,
                        transport_info.speed_multiplier,
                        self.sample_rate,
                        self.sample_rate_recip,
                    )
                        ..transport_info.transport.samples_to_musical(
                            self.clock_samples + DurationSamples(self.frames as i64),
                            start_clock_samples,
                            transport_info.speed_multiplier,
                            self.sample_rate,
                            self.sample_rate_recip,
                        )
                })
        })
    }

    /// Returns `true` if there is a transport and that transport is playing,
    /// `false` otherwise.
    #[cfg(feature = "musical_transport")]
    pub fn transport_is_playing(&self) -> bool {
        self.transport_info
            .as_ref()
            .map(|t| t.playing())
            .unwrap_or(false)
    }

    /// Converts the given musical time to the corresponding time in samples.
    ///
    /// If there is no musical transport or the transport is not currently playing,
    /// then this will return `None`.
    #[cfg(feature = "musical_transport")]
    pub fn musical_to_samples(&self, musical: InstantMusical) -> Option<InstantSamples> {
        self.transport_info.as_ref().and_then(|transport_info| {
            transport_info
                .start_clock_samples
                .map(|start_clock_samples| {
                    transport_info.transport.musical_to_samples(
                        musical,
                        start_clock_samples,
                        transport_info.speed_multiplier,
                        self.sample_rate,
                    )
                })
        })
    }
}

#[cfg(feature = "musical_transport")]
#[derive(Debug, Clone, PartialEq)]
pub struct TransportInfo {
    /// The current transport.
    pub transport: MusicalTransport,

    /// The instant that `MusicaltTime::ZERO` occurred in units of
    /// `ClockSamples`.
    ///
    /// If the transport is not currently playing, then this will be `None`.
    pub start_clock_samples: Option<InstantSamples>,

    /// The beats per minute at the first frame of this process block.
    ///
    /// (The `speed_multipler` has already been applied to this value.)
    pub beats_per_minute: f64,

    /// A multiplier for the playback speed of the transport. A value of `1.0`
    /// means no change in speed, a value less than `1.0` means a decrease in
    /// speed, and a value greater than `1.0` means an increase in speed.
    pub speed_multiplier: f64,
}

#[cfg(feature = "musical_transport")]
impl TransportInfo {
    /// Whether or not the transport is currently playing (true) or paused
    /// (false).
    pub const fn playing(&self) -> bool {
        self.start_clock_samples.is_some()
    }
}

bitflags::bitflags! {
    /// Flags indicating the current status of the audio stream
    #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
    pub struct StreamStatus: u32 {
        /// Some input data was discarded because of an overflow condition
        /// at the audio driver.
        const INPUT_OVERFLOW = 0b001;

        /// The output buffer ran low, likely producing a break in the
        /// output sound. (This is also known as an "underrun").
        const OUTPUT_UNDERFLOW = 0b010;

        /// The stream was closed (i.e. because a microphone was unplugged).
        const CLOSED = 0b100;
    }
}

/// The status of processing buffers in an audio node.
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
pub enum ProcessStatus {
    /// No output buffers were modified. If this is returned, then
    /// the engine will automatically clear all output buffers
    /// for you as efficiently as possible.
    #[default]
    ClearAllOutputs,
    /// No output buffers were modified. If this is returned, then
    /// the engine will automatically copy the input buffers to
    /// their corresponding output buffers for you as efficiently
    /// as possible.
    Bypass,
    /// All output buffers were filled with data.
    ///
    /// WARNING: The node must fill all audio audio output buffers
    /// completely with data when returning this process status.
    /// Failing to do so will result in audio glitches. If using
    /// [`AudioNodeInfo::in_place_buffers`], then the output buffers
    /// in the range `[0..num_inputs_in_config.min(num_outputs_in_config)]`
    /// do not need to be filled with data.
    OutputsModified,
    /// All output buffers were filled with data. Additionally,
    /// a constant/silence mask is provided for optimizations.
    ///
    /// WARNING: The node must fill all audio audio output buffers
    /// completely with data when returning this process status.
    /// Failing to do so will result in audio glitches. If using
    /// [`AudioNodeInfo::in_place_buffers`], then the output buffers
    /// in the range `[0..num_inputs_in_config.min(num_outputs_in_config)]`
    /// do not need to be filled with data.
    ///
    /// WARNING: Incorrectly marking a channel as containing
    /// silence/constant values when it doesn't will result in audio
    /// glitches. Please take great care when using this, or
    /// use [`ProcessStatus::OutputsModified`] instead.
    OutputsModifiedWithMask(MaskType),
}

impl ProcessStatus {
    /// All output buffers were filled with data. Additionally,
    /// a constant/silence mask is provided for optimizations.
    ///
    /// WARNING: The node must fill all audio audio output buffers
    /// completely with data when returning this process status.
    /// Failing to do so will result in audio glitches. If using
    /// [`AudioNodeInfo::in_place_buffers`], then the output buffers
    /// in the range `[0..num_inputs_in_config.min(num_outputs_in_config)]`
    /// do not need to be filled with data.
    ///
    /// WARNING: Incorrectly marking a channel as containing
    /// silence when it doesn't will result in audio glitches.
    /// Please take great care when using this, or use
    /// [`ProcessStatus::OutputsModified`] instead.
    pub const fn outputs_modified_with_silence_mask(mask: SilenceMask) -> Self {
        Self::OutputsModifiedWithMask(MaskType::Silence(mask))
    }

    /// All output buffers were filled with data. Additionally,
    /// a constant/silence mask is provided for optimizations.
    ///
    /// WARNING: The node must fill all audio audio output buffers
    /// completely with data when returning this process status.
    /// Failing to do so will result in audio glitches. If using
    /// [`AudioNodeInfo::in_place_buffers`], then the output buffers
    /// in the range `[0..num_inputs_in_config.min(num_outputs_in_config)]`
    /// do not need to be filled with data.
    ///
    /// WARNING: Incorrectly marking a channel as containing
    /// constant values when it doesn't will result in audio
    /// glitches. Please take great care when using this, or use
    /// [`ProcessStatus::OutputsModified`] instead.
    pub const fn outputs_modified_with_constant_mask(mask: ConstantMask) -> Self {
        Self::OutputsModifiedWithMask(MaskType::Constant(mask))
    }
}

/// A type-erased store accessible to all [`AudioNodeProcessor`]s.
pub struct ProcStore(HashMap<TypeId, Box<dyn Any + Send>>);

impl ProcStore {
    pub fn with_capacity(capacity: usize) -> Self {
        let mut h = HashMap::default();
        h.reserve(capacity);
        Self(h)
    }

    /// Insert a new resource into the store.
    ///
    /// If a resource with this `TypeID` already exists, then an error will
    /// be returned instead.
    pub fn insert<S: Send + 'static>(&mut self, resource: S) -> Result<(), S> {
        if let Entry::Vacant(e) = self.0.entry(TypeId::of::<S>()) {
            e.insert(Box::new(resource));
            Ok(())
        } else {
            Err(resource)
        }
    }

    /// Insert a new already type-erased resource into the store.
    ///
    /// If a resource with this `TypeID` already exists, then an error will
    /// be returned instead.
    pub fn insert_any<S: Send + 'static>(
        &mut self,
        resource: Box<dyn Any + Send>,
        type_id: TypeId,
    ) -> Result<(), Box<dyn Any + Send>> {
        if let Entry::Vacant(e) = self.0.entry(type_id) {
            e.insert(resource);
            Ok(())
        } else {
            Err(resource)
        }
    }

    /// Get the entry for the given resource.
    pub fn entry<'a, S: Send + 'static>(&'a mut self) -> ProcStoreEntry<'a, S> {
        ProcStoreEntry {
            boxed_entry: self.0.entry(TypeId::of::<S>()),
            type_: PhantomData,
        }
    }

    /// Returns `true` if a resource with the given `TypeID` exists in this
    /// store.
    pub fn contains<S: Send + 'static>(&self) -> bool {
        self.0.contains_key(&TypeId::of::<S>())
    }

    /// Get an immutable reference to a resource in the store.
    ///
    /// # Panics
    /// Panics if the given resource does not exist.
    pub fn get<S: Send + 'static>(&self) -> &S {
        self.try_get().unwrap()
    }

    /// Get a mutable reference to a resource in the store.
    ///
    /// # Panics
    /// Panics if the given resource does not exist.
    pub fn get_mut<S: Send + 'static>(&mut self) -> &mut S {
        self.try_get_mut().unwrap()
    }

    /// Get an immutable reference to a resource in the store.
    ///
    /// Returns `None` if the given resource does not exist.
    pub fn try_get<S: Send + 'static>(&self) -> Option<&S> {
        self.0
            .get(&TypeId::of::<S>())
            .map(|s| s.downcast_ref().unwrap())
    }

    /// Get a mutable reference to a resource in the store.
    ///
    /// Returns `None` if the given resource does not exist.
    pub fn try_get_mut<S: Send + 'static>(&mut self) -> Option<&mut S> {
        self.0
            .get_mut(&TypeId::of::<S>())
            .map(|s| s.downcast_mut().unwrap())
    }
}

pub struct ProcStoreEntry<'a, S: Send + 'static> {
    pub boxed_entry: Entry<'a, TypeId, Box<dyn Any + Send>>,
    type_: PhantomData<S>,
}

impl<'a, S: Send + 'static> ProcStoreEntry<'a, S> {
    pub fn or_insert_with(self, default: impl FnOnce() -> S) -> &'a mut S {
        self.boxed_entry
            .or_insert_with(|| Box::new((default)()))
            .downcast_mut()
            .unwrap()
    }

    pub fn or_insert_with_any(self, default: impl FnOnce() -> Box<dyn Any + Send>) -> &'a mut S {
        self.boxed_entry
            .or_insert_with(default)
            .downcast_mut()
            .unwrap()
    }

    pub fn and_modify(self, f: impl FnOnce(&mut S)) -> Self {
        let entry = self
            .boxed_entry
            .and_modify(|e| (f)(e.downcast_mut().unwrap()));
        Self {
            boxed_entry: entry,
            type_: PhantomData,
        }
    }
}