1use std::collections::HashMap;
18
19use alpha2_audio::{
20 Biquad, BiquadKind, ChannelLayout, Compressor, CompressorSettings, Controls, Delay, Detector,
21 DetectorFilter, Ducker, Expander, ExpanderSettings, Interpolator, LoudnessMeter,
22 LoudnessReport, Matrix, PeakLimiter, ProcessCtx, Processor, ProcessorChain, SchroederReverb,
23 Stretch, TransportState,
24};
25use alpha2_eval::{ActiveAudioClip, AudioSpanScratch, SampleContext, next_knot, sample_scalar};
26use alpha2_media::{AudioBlock, AudioBlockProvider, SourceId, SpeakerLayout};
27use alpha2_model::{
28 Animated, AudioEffect, AudioNodeRef, ClipId, Domain, EqBandKind, LOOP_FADE_SECONDS, LoopMode,
29 MAX_GAIN, MasterAudio, TimeMap, TrackId,
30};
31use alpha2_time::{MediaTime, TICKS_PER_SECOND, TimeRange};
32
33use crate::downmix::{ChannelMix, Downmix};
34use crate::{EngineError, EngineProject};
35
36mod control;
37mod curve_read;
38mod edge;
39mod graph;
40mod stretch_read;
41
42use control::{ChainControl, Param, Retuned};
43use curve_read::curve_requests;
44use edge::{AfterFader, BlockRun, DelayedTap, ENVELOPE_PLANES, Edge, Input, KeyInput};
45use graph::{Format, MasterChain, MixGraph};
46use stretch_read::{StretchSlot, stretched_request, stretches};
47
48const MAX_CACHED_WEIGHTS: usize = 1 << 15;
50
51pub const MAX_AUDIO_BLOCK: usize = 8_192;
53
54const _: () = {
57 let rate = *alpha2_model::SAMPLE_RATE_RANGE.start() as usize;
58 let samples = MAX_AUDIO_BLOCK + 2 + alpha2_model::MAX_CHAIN_EFFECTS;
59 assert!(
60 samples * 1_000 <= alpha2_model::AUDIO_EFFECT_STATE_MARGIN_MS as usize * rate,
61 "AUDIO_EFFECT_STATE_MARGIN_MS must hold a largest block at the lowest rate"
62 );
63};
64
65pub const MAX_SETTLING_SECONDS: u32 = 30;
71
72#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
75pub enum AudioContinuity {
76 #[default]
80 Exact,
81 ContinueSmallGaps,
87}
88
89#[derive(Clone, Debug, PartialEq, Eq)]
91pub struct AudioRenderStatus {
92 pub start_sample: i64,
94 pub frames: usize,
96 pub missing_sources: Vec<SourceId>,
103}
104
105impl AudioRenderStatus {
106 #[must_use]
108 pub fn is_complete(&self) -> bool {
109 self.missing_sources.is_empty()
110 }
111}
112
113#[derive(Clone, Debug, PartialEq, Eq)]
115pub struct AudioNeed {
116 pub source_id: SourceId,
118 pub stream: Option<u32>,
121 pub source_range: TimeRange,
123}
124
125pub const MAX_AUDIO_TAPS: usize = 32;
127
128#[derive(
130 Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Deserialize, serde::Serialize,
131)]
132#[serde(rename_all = "snake_case")]
133pub enum TapPoint {
134 PreFader,
136 #[default]
138 PostFader,
139}
140
141#[derive(Clone, Debug, PartialEq, Eq, serde::Deserialize, serde::Serialize)]
144#[serde(deny_unknown_fields)]
145pub struct AudioTap {
146 pub node: AudioNodeRef,
148 #[serde(default, rename = "tap")]
150 pub point: TapPoint,
151}
152
153#[derive(Clone, Debug, PartialEq, serde::Serialize)]
156#[serde(rename_all = "camelCase")]
157pub struct NodeLevels {
158 pub node: Option<AudioNodeRef>,
160 pub start_sample: i64,
163 pub frames: usize,
165 pub peak: [f32; 2],
168 pub rms: [f32; 2],
172}
173
174struct HostTap {
175 input: Input,
176 planes: [Vec<f32>; 2],
177}
178
179struct MixNode {
180 id: AudioNodeRef,
181 track: Option<TrackId>,
182 gain: Animated<f32>,
183 pan: Animated<f32>,
184 chain: ProcessorChain,
185 control: ChainControl,
186 keys: Vec<KeyInput>,
187 output: [Vec<f32>; 2],
189 after_fader: [Vec<f32>; 2],
190 after_fader_use: AfterFader,
191 delayed_taps: Vec<DelayedTap>,
192 live: bool,
195 ahead_of_output: i64,
196 latency: i64,
198 clips: Vec<ClipSlot>,
200 chain_lead: i64,
202 processed: bool,
203 inputs: Vec<Input>,
204 outputs: Vec<usize>,
205}
206
207impl MixNode {
208 fn make_live(&mut self, channels: usize, frames: usize) {
210 if self.live {
211 return;
212 }
213 for plane in self.output.iter_mut().take(channels) {
214 plane[..frames].fill(0.0);
215 }
216 self.live = true;
217 #[cfg(test)]
218 BUS_PLANES_CLEARED.set(BUS_PLANES_CLEARED.get() + channels);
219 }
220}
221
222struct ClipSlot {
223 id: ClipId,
224 chain: Option<ClipChain>,
225}
226
227struct ClipChain {
233 effects: Vec<AudioEffect>,
234 chain: Option<(ProcessorChain, ChainControl)>,
235 ran_in: u64,
237 latency: i64,
239 history: u32,
241 next_input: Option<i64>,
243 lead: i64,
245}
246
247pub struct AudioRenderer {
249 layout: ChannelLayout,
250 sample_rate: u32,
251 max_block: usize,
252 nodes: Vec<MixNode>,
253 track_count: usize,
254 edges: Vec<Edge>,
255 nodes_sources_first: Vec<usize>,
256 master_inputs: Vec<Input>,
257 master_keys: Vec<KeyInput>,
258 nodes_with_delayed_taps: Vec<usize>,
259 bus_of_track: HashMap<TrackId, usize>,
261 slot_of_clip: HashMap<ClipId, (usize, usize)>,
263 span_scratch: AudioSpanScratch,
264 master_chain: ProcessorChain,
265 master_control: ChainControl,
266 master_latency: i64,
268 lookahead: i64,
270 history: i64,
272 master_lead: i64,
274 limiter_lead: i64,
276 stage_leads: Vec<i64>,
279 master: MasterAudio,
280 limiter: Option<PeakLimiter>,
281 normalization_gain: f32,
283 hold_incomplete: bool,
284 continuity: AudioContinuity,
285 meter: Option<LoudnessMeter>,
287 output_meter: Option<LoudnessMeter>,
289 clip_a: [Vec<f32>; 2],
290 clip_b: [Vec<f32>; 2],
291 bus_in: [Vec<f32>; 2],
292 mix: [Vec<f32>; 2],
293 output: [Vec<f32>; 2],
294 envelope: [Vec<f32>; ENVELOPE_PLANES],
296 next_sample: Option<i64>,
298 live_chains: Vec<(usize, usize)>,
300 blocks_mixed: u64,
301 weights: Vec<f64>,
303 phase_weights: Vec<f64>,
305 host_taps: Vec<HostTap>,
306 measures_levels: bool,
307 levels: Vec<NodeLevels>,
308 levels_measured: bool,
309 stretch: Stretch,
311 stretch_slots: HashMap<(ClipId, usize), StretchSlot>,
312 #[cfg(test)]
314 most_held: (usize, u64),
315 #[cfg(test)]
317 samples_read: usize,
318}
319
320#[derive(Clone, Copy, Debug, PartialEq, Eq)]
322enum Fill {
323 Samples,
325 Presence,
327}
328
329impl AudioRenderer {
330 pub fn new(
337 snapshot: &EngineProject,
338 channels: usize,
339 max_block: usize,
340 ) -> Result<Self, EngineError> {
341 Self::with_taps(snapshot, channels, max_block, &[])
342 }
343
344 pub fn with_taps(
350 snapshot: &EngineProject,
351 channels: usize,
352 max_block: usize,
353 taps: &[AudioTap],
354 ) -> Result<Self, EngineError> {
355 let layout =
356 ChannelLayout::from_channels(channels).ok_or(EngineError::InvalidAudioConfiguration)?;
357 let project = snapshot.project();
358 let sample_rate = project.settings.sample_rate;
359 if sample_rate == 0 || max_block == 0 || max_block > MAX_AUDIO_BLOCK {
360 return Err(EngineError::InvalidAudioConfiguration);
361 }
362
363 let (master_chain, master_layout, master_control) =
364 master_chain_of(&project.audio, layout, sample_rate, max_block);
365 let limiter = project.audio.limiter.map(|limiter| {
366 let mut peak = PeakLimiter::new(limiter.threshold, limiter.release_ms);
367 peak.prepare(sample_rate, max_block);
368 peak
369 });
370 let master_latency = i64::from(master_chain.latency_samples());
371 let mut graph = MixGraph::new(
372 project,
373 Format {
374 layout,
375 sample_rate,
376 max_block,
377 },
378 &MasterChain {
379 chain: &master_chain,
380 layout: &master_layout,
381 },
382 taps,
383 )?;
384 let host_taps = std::mem::take(&mut graph.host_taps)
385 .into_iter()
386 .map(|input| HostTap {
387 input,
388 planes: buffers(max_block),
389 })
390 .collect();
391 let slot_of_clip = slots_by_clip(&graph.nodes);
392 let lookahead = graph.longest_read_lead(master_latency);
393 let settling = Settling(i64::from(sample_rate) * i64::from(MAX_SETTLING_SECONDS));
394 let limiter_lead = settling.lead(0, limiter.as_ref().map_or(0, Processor::history_samples));
395 let master_lead = settling.lead(limiter_lead, master_chain.history_samples());
396 let history = assign_leads(&mut graph, master_lead, settling).max(master_lead);
397 let stage_leads = stage_leads(&graph, master_lead, limiter_lead);
398
399 Ok(Self {
400 layout,
401 sample_rate,
402 max_block,
403 nodes: graph.nodes,
404 track_count: graph.track_count,
405 edges: graph.edges,
406 nodes_sources_first: graph.nodes_sources_first,
407 master_inputs: graph.master_inputs,
408 master_keys: graph.master_keys,
409 nodes_with_delayed_taps: graph.nodes_with_delayed_taps,
410 bus_of_track: graph.node_of_track,
411 slot_of_clip,
412 span_scratch: AudioSpanScratch::default(),
413 master_chain,
414 master_control,
415 master_latency,
416 lookahead,
417 history,
418 master_lead,
419 limiter_lead,
420 stage_leads,
421 master: project.audio.clone(),
422 limiter,
423 normalization_gain: 1.0,
424 hold_incomplete: false,
425 continuity: AudioContinuity::Exact,
426 meter: None,
427 output_meter: None,
428 clip_a: buffers(max_block),
429 clip_b: buffers(max_block),
430 bus_in: buffers(max_block),
431 mix: buffers(max_block),
432 output: buffers(max_block),
433 envelope: std::array::from_fn(|_| vec![0.0; max_block]),
434 next_sample: None,
435 live_chains: Vec::new(),
436 blocks_mixed: 0,
437 weights: Vec::new(),
438 phase_weights: Vec::new(),
439 stretch: Stretch::new(sample_rate),
440 stretch_slots: HashMap::new(),
441 host_taps,
442 measures_levels: false,
443 levels: Vec::new(),
444 levels_measured: false,
445 #[cfg(test)]
446 most_held: (0, 0),
447 #[cfg(test)]
448 samples_read: 0,
449 })
450 }
451
452 pub fn set_taps(
461 &mut self,
462 snapshot: &EngineProject,
463 taps: &[AudioTap],
464 ) -> Result<(), EngineError> {
465 let mut rebuilt = Self::with_taps(snapshot, self.layout.channels(), self.max_block, taps)?;
466 rebuilt.normalization_gain = self.normalization_gain;
467 rebuilt.hold_incomplete = self.hold_incomplete;
468 rebuilt.continuity = self.continuity;
469 rebuilt.meter = self.meter.take();
470 rebuilt.output_meter = self.output_meter.take();
471 rebuilt.set_levels(self.measures_levels);
472 *self = rebuilt;
473 Ok(())
474 }
475
476 #[must_use]
478 pub const fn taps(&self) -> usize {
479 self.host_taps.len()
480 }
481
482 #[must_use]
485 pub fn tap_channel(&self, index: usize, channel: usize) -> &[f32] {
486 self.host_taps
487 .get(index)
488 .and_then(|tap| tap.planes.get(channel))
489 .map_or(&[], Vec::as_slice)
490 }
491
492 pub fn set_levels(&mut self, enabled: bool) {
494 self.measures_levels = enabled;
495 self.levels_measured = false;
496 self.levels.clear();
497 if enabled {
498 let blank = |node: Option<AudioNodeRef>| NodeLevels {
499 node,
500 start_sample: 0,
501 frames: 0,
502 peak: [0.0; 2],
503 rms: [0.0; 2],
504 };
505 let mixed = self.nodes.iter().filter(|node| node.processed);
506 self.levels
507 .extend(mixed.map(|node| blank(Some(node.id.clone()))));
508 self.levels.push(blank(None));
509 }
510 }
511
512 #[must_use]
515 pub fn levels(&self) -> &[NodeLevels] {
516 if self.levels_measured {
517 &self.levels
518 } else {
519 &[]
520 }
521 }
522
523 #[must_use]
525 pub const fn sample_rate(&self) -> u32 {
526 self.sample_rate
527 }
528
529 #[must_use]
531 pub const fn channels(&self) -> usize {
532 self.layout.channels()
533 }
534
535 #[must_use]
537 pub fn track_ids(&self) -> Vec<&TrackId> {
538 self.nodes
539 .iter()
540 .filter_map(|node| node.track.as_ref())
541 .collect()
542 }
543
544 #[must_use]
546 pub const fn max_block(&self) -> usize {
547 self.max_block
548 }
549
550 #[must_use]
552 pub fn channel(&self, index: usize) -> &[f32] {
553 self.output.get(index).map_or(&[], Vec::as_slice)
554 }
555
556 #[must_use]
562 pub fn required_lookahead_samples(&self) -> u32 {
563 u32::try_from(self.lookahead).unwrap_or(u32::MAX)
564 }
565
566 pub fn audio_needs(
578 &self,
579 snapshot: &EngineProject,
580 start_sample: i64,
581 frames: usize,
582 ) -> Result<Vec<AudioNeed>, EngineError> {
583 self.check_block(start_sample, frames)?;
584 let mut needs = Vec::new();
585 let mut scratch = AudioSpanScratch::default();
586 if self.continues_at(start_sample).is_none() {
587 let mut position = self.preroll_start(start_sample)?;
588 while position < start_sample {
589 let count = self.replay_frames(position, start_sample);
590 self.block_needs(
591 snapshot,
592 position,
593 count,
594 Some(start_sample),
595 &mut scratch,
596 &mut needs,
597 )?;
598 position += i64::try_from(count).unwrap_or(i64::MAX);
599 }
600 }
601 self.block_needs(
602 snapshot,
603 start_sample,
604 frames,
605 None,
606 &mut scratch,
607 &mut needs,
608 )?;
609 Ok(needs)
610 }
611
612 fn block_needs(
614 &self,
615 snapshot: &EngineProject,
616 start: i64,
617 frames: usize,
618 replay_target: Option<i64>,
619 scratch: &mut AudioSpanScratch,
620 needs: &mut Vec<AudioNeed>,
621 ) -> Result<(), EngineError> {
622 let frames_i64 = i64::try_from(frames).map_err(|_| EngineError::OutOfRange)?;
623 let stages = Stages {
624 target: replay_target,
625 block_end: start + frames_i64,
626 lookahead: self.lookahead,
627 };
628 let span = self.block_span(start, frames_i64)?;
629 let described = snapshot
630 .evaluate_audio_in(span, scratch)
631 .map_err(EngineError::Evaluate)?;
632 let rate = self.sample_rate;
633 for clip in described.iter() {
634 let Some(read) = self.clip_read(&clip, start, frames, stages) else {
635 continue;
636 };
637 source_requests(
638 snapshot,
639 &self.stretch,
640 &clip,
641 read.first,
642 read.window.content,
643 rate,
644 |from, to| {
645 let (Some(start), Some(end)) =
646 (checked_ticks_at(from, rate), ticks_at_or_after(to, rate))
647 else {
648 return;
649 };
650 if let Ok(range) =
651 TimeRange::new(MediaTime::from_ticks(start), MediaTime::from_ticks(end))
652 {
653 merge_need(needs, clip.source_id, clip.audio.stream, range);
654 }
655 },
656 );
657 }
658 Ok(())
659 }
660
661 fn check_block(&self, start_sample: i64, frames: usize) -> Result<(), EngineError> {
662 if start_sample < 0 || frames == 0 || frames > self.max_block {
663 return Err(EngineError::InvalidAudioConfiguration);
664 }
665 i64::try_from(frames)
667 .ok()
668 .and_then(|frames| start_sample.checked_add(frames))
669 .and_then(|end| end.checked_add(self.lookahead))
670 .and_then(|end| checked_ticks_at(end, self.sample_rate))
671 .map(|_| ())
672 .ok_or(EngineError::InvalidAudioConfiguration)
673 }
674
675 #[must_use]
678 pub const fn required_history_samples(&self) -> i64 {
679 self.history
680 }
681
682 fn preroll_start(&self, start: i64) -> Result<i64, EngineError> {
683 if start < 0 {
684 return Err(EngineError::InvalidAudioConfiguration);
685 }
686 let history = if self.continues_at(start).is_some() {
687 0
688 } else {
689 self.history
690 };
691 Ok(start
693 .saturating_sub(history)
694 .max(0)
695 .saturating_sub(self.lookahead))
696 }
697
698 fn replay_frames(&self, position: i64, target: i64) -> usize {
701 let room = i64::try_from(self.max_block).unwrap_or(i64::MAX);
702 let mut end = target.min(position.saturating_add(room));
703 let begun = self
705 .stage_leads
706 .partition_point(|&lead| Stages::start(target, lead, self.lookahead) <= position);
707 if let Some(&lead) = self.stage_leads.get(begun) {
708 end = end.min(Stages::start(target, lead, self.lookahead));
709 }
710 usize::try_from(end - position).unwrap_or(1)
711 }
712
713 fn continues_at(&self, start: i64) -> Option<i64> {
716 let step = start.checked_sub(self.next_sample?)?;
717 let room = i64::try_from(self.max_block).unwrap_or(i64::MAX);
718 let joins = self.continuity == AudioContinuity::ContinueSmallGaps && step.abs() <= room;
719 (step == 0 || joins).then_some(step)
720 }
721
722 fn step_live_chains(&mut self, step: i64) {
725 if step == 0 {
726 return;
727 }
728 for &(bus, position) in &self.live_chains {
729 if let Some(clip) = self.nodes[bus].clips[position].chain.as_mut() {
730 clip.next_input = clip.next_input.and_then(|next| next.checked_add(step));
731 }
732 }
733 }
734
735 pub fn set_continuity(&mut self, continuity: AudioContinuity) {
738 if self.continuity != continuity {
739 self.reset();
740 self.continuity = continuity;
741 }
742 }
743
744 #[must_use]
746 pub const fn continuity(&self) -> AudioContinuity {
747 self.continuity
748 }
749
750 pub fn reset(&mut self) {
755 self.next_sample = None;
756 for &(bus, position) in &self.live_chains {
758 if let Some(clip) = self.nodes[bus].clips[position].chain.as_mut() {
759 if let Some((chain, _)) = clip.chain.as_mut() {
760 chain.reset();
761 }
762 clip.next_input = None;
763 }
764 }
765 for bus in &mut self.nodes {
766 bus.chain.reset();
767 }
768 for &node in &self.nodes_with_delayed_taps {
769 for tap in &mut self.nodes[node].delayed_taps {
770 tap.reset();
771 }
772 }
773 self.master_chain.reset();
774 if let Some(limiter) = self.limiter.as_mut() {
775 limiter.reset();
776 }
777 }
778
779 pub fn render(
795 &mut self,
796 snapshot: &EngineProject,
797 start_sample: i64,
798 frames: usize,
799 provider: &dyn AudioBlockProvider,
800 transport: TransportState,
801 ) -> Result<AudioRenderStatus, EngineError> {
802 self.check_block(start_sample, frames)?;
803 self.levels_measured = false;
804 let end_sample = start_sample + i64::try_from(frames).unwrap_or(i64::MAX);
805 if self.hold_incomplete {
806 let missing_sources = self.unready_sources(snapshot, start_sample, frames, provider)?;
807 if !missing_sources.is_empty() {
808 for channel in 0..self.layout.channels() {
809 self.output[channel][..frames].fill(0.0);
810 }
811 return Ok(AudioRenderStatus {
812 start_sample,
813 frames,
814 missing_sources,
815 });
816 }
817 }
818 let mut missing_sources: Vec<SourceId> = Vec::new();
819 if let Some(step) = self.continues_at(start_sample) {
820 self.step_live_chains(step);
821 } else {
822 let mut position = self.preroll_start(start_sample)?;
823 self.reset();
824 while position < start_sample {
825 let count = self.replay_frames(position, start_sample);
826 self.mix_block(
827 snapshot,
828 position,
829 count,
830 provider,
831 transport,
832 Some(start_sample),
833 &mut missing_sources,
834 )?;
835 position += i64::try_from(count).unwrap_or(i64::MAX);
836 }
837 }
838 self.mix_block(
839 snapshot,
840 start_sample,
841 frames,
842 provider,
843 transport,
844 None,
845 &mut missing_sources,
846 )?;
847 self.next_sample = Some(end_sample);
848
849 Ok(AudioRenderStatus {
850 start_sample,
851 frames,
852 missing_sources,
853 })
854 }
855
856 fn unready_sources(
859 &mut self,
860 snapshot: &EngineProject,
861 start_sample: i64,
862 frames: usize,
863 provider: &dyn AudioBlockProvider,
864 ) -> Result<Vec<SourceId>, EngineError> {
865 let mut missing = Vec::new();
866 let mut position = if self.continues_at(start_sample).is_some() {
867 start_sample
868 } else {
869 self.preroll_start(start_sample)?
870 };
871 while position < start_sample {
872 let count = self.replay_frames(position, start_sample);
873 self.read_block(
874 snapshot,
875 position,
876 count,
877 provider,
878 Some(start_sample),
879 &mut missing,
880 )?;
881 position += i64::try_from(count).unwrap_or(i64::MAX);
882 }
883 self.read_block(snapshot, start_sample, frames, provider, None, &mut missing)?;
884 Ok(missing)
885 }
886
887 fn read_block(
889 &mut self,
890 snapshot: &EngineProject,
891 start: i64,
892 frames: usize,
893 provider: &dyn AudioBlockProvider,
894 replay_target: Option<i64>,
895 missing: &mut Vec<SourceId>,
896 ) -> Result<(), EngineError> {
897 let frames_i64 = i64::try_from(frames).map_err(|_| EngineError::OutOfRange)?;
898 let stages = Stages {
899 target: replay_target,
900 block_end: start + frames_i64,
901 lookahead: self.lookahead,
902 };
903 let span = self.block_span(start, frames_i64)?;
904 let mut scratch = std::mem::take(&mut self.span_scratch);
905 let described = match snapshot.evaluate_audio_in(span, &mut scratch) {
906 Ok(described) => described,
907 Err(error) => {
908 self.span_scratch = scratch;
909 return Err(EngineError::Evaluate(error));
910 }
911 };
912 for clip in described.iter() {
913 let Some(read) = self.clip_read(&clip, start, frames, stages) else {
914 continue;
915 };
916 let complete = self.fill_clip(snapshot, &clip, &read, provider, Fill::Presence);
917 if !complete && !missing.contains(clip.source_id) {
918 missing.push(clip.source_id.clone());
919 }
920 }
921 self.span_scratch = scratch;
922 Ok(())
923 }
924
925 #[allow(clippy::too_many_arguments)]
932 fn mix_block(
933 &mut self,
934 snapshot: &EngineProject,
935 start: i64,
936 frames: usize,
937 provider: &dyn AudioBlockProvider,
938 transport: TransportState,
939 replay_target: Option<i64>,
940 missing_sources: &mut Vec<SourceId>,
941 ) -> Result<(), EngineError> {
942 let channels = self.layout.channels();
943 let context = snapshot.sample_context();
944 let frames_i64 = i64::try_from(frames).map_err(|_| EngineError::OutOfRange)?;
945 let stages = Stages {
946 target: replay_target,
947 block_end: start + frames_i64,
948 lookahead: self.lookahead,
949 };
950 let span = self.block_span(start, frames_i64)?;
951 let mut scratch = std::mem::take(&mut self.span_scratch);
953 let described = match snapshot.evaluate_audio_in(span, &mut scratch) {
954 Ok(described) => described,
955 Err(error) => {
956 self.span_scratch = scratch;
957 return Err(EngineError::Evaluate(error));
958 }
959 };
960
961 for channel in 0..channels {
962 self.mix[channel][..frames].fill(0.0);
963 }
964 for bus in &mut self.nodes {
965 bus.live = false;
966 }
967 for &node in &self.nodes_with_delayed_taps {
968 for tap in &mut self.nodes[node].delayed_taps {
969 tap.delayed_this_block = false;
970 }
971 }
972
973 self.keep_mixed_chains(&described, start, frames, stages);
974 let mut complete_block = true;
975 for clip in described.iter() {
976 let clip = &clip;
977 let Some(read) = self.clip_read(clip, start, frames, stages) else {
978 continue;
979 };
980 let window = read.window;
981 let complete = self.fill_clip(snapshot, clip, &read, provider, Fill::Samples);
982 complete_block &= complete;
983 if !complete && !missing_sources.contains(clip.source_id) {
984 missing_sources.push(clip.source_id.clone());
985 }
986 if let Some(slot) = read.slot {
987 self.apply_clip_chain(slot, read.first, transport, window.count, &context);
988 }
989 self.mix_clip_into_bus(
990 clip,
991 read.bus,
992 read.bus_input,
993 window.offset,
994 window.count,
995 frames,
996 &context,
997 );
998 }
999 self.span_scratch = scratch;
1000 let block = self.blocks_mixed;
1002 self.stretch_slots.retain(|_, slot| slot.used_in == block);
1003
1004 self.mix_tracks_and_buses(start, transport, frames, stages, &context);
1005 if replay_target.is_none() {
1006 self.read_host_taps(start, frames, &context);
1007 }
1008 if stages.run(self.master_lead) {
1009 edge::add_inputs(
1010 &self.master_inputs,
1011 &self.edges,
1012 &self.nodes,
1013 &mut self.mix,
1014 &mut BlockRun {
1015 start,
1016 frames,
1017 channels,
1018 sample_rate: self.sample_rate,
1019 envelope: &mut self.envelope,
1020 context: &context,
1021 },
1022 );
1023 self.finish_master(
1024 start,
1025 start + self.master_latency,
1026 transport,
1027 frames,
1028 stages,
1029 complete_block,
1030 &context,
1031 );
1032 }
1033 if self.measures_levels && replay_target.is_none() && complete_block {
1034 self.measure_levels(start, frames, &context);
1035 }
1036 self.blocks_mixed += 1;
1037 Ok(())
1038 }
1039
1040 fn read_host_taps(&mut self, start: i64, frames: usize, context: &SampleContext<'_>) {
1041 let channels = self.layout.channels();
1042 for tap in &mut self.host_taps {
1043 for plane in tap.planes.iter_mut().take(channels) {
1044 plane[..frames].fill(0.0);
1045 }
1046 edge::add_inputs(
1047 &[tap.input],
1048 &self.edges,
1049 &self.nodes,
1050 &mut tap.planes,
1051 &mut BlockRun {
1052 start,
1053 frames,
1054 channels,
1055 sample_rate: self.sample_rate,
1056 envelope: &mut self.envelope,
1057 context,
1058 },
1059 );
1060 }
1061 }
1062
1063 fn measure_levels(&mut self, start: i64, frames: usize, context: &SampleContext<'_>) {
1064 let channels = self.layout.channels();
1065 #[expect(clippy::cast_precision_loss, reason = "a block length")]
1066 let root_mean = |sum_of_squares: f32| libm::sqrtf(sum_of_squares / frames.max(1) as f32);
1067 let mixed = self.nodes.iter().filter(|node| node.processed);
1068 for (node, levels) in mixed.zip(&mut self.levels) {
1069 let measured = edge::measure_after_fader(
1070 node,
1071 &mut BlockRun {
1072 start,
1073 frames,
1074 channels,
1075 sample_rate: self.sample_rate,
1076 envelope: &mut self.envelope,
1077 context,
1078 },
1079 );
1080 levels.start_sample = start + node.ahead_of_output;
1081 levels.frames = frames;
1082 levels.peak = measured.peak;
1083 levels.rms = measured.sum_of_squares.map(root_mean);
1084 }
1085 if let Some(master) = self.levels.last_mut() {
1086 master.start_sample = start;
1087 master.frames = frames;
1088 (master.peak, master.rms) = ([0.0; 2], [0.0; 2]);
1089 for channel in 0..channels {
1090 let (peak, sum_of_squares) =
1091 edge::peak_and_sum_of_squares(&self.output[channel][..frames]);
1092 master.peak[channel] = peak;
1093 master.rms[channel] = root_mean(sum_of_squares);
1094 }
1095 }
1096 self.levels_measured = true;
1097 }
1098
1099 fn keep_mixed_chains(
1103 &mut self,
1104 described: &alpha2_eval::AudioSpan<'_, '_>,
1105 start: i64,
1106 frames: usize,
1107 stages: Stages,
1108 ) {
1109 let block = self.blocks_mixed;
1110 for clip in described.iter() {
1111 let Some((bus, position)) = self
1112 .clip_read(&clip, start, frames, stages)
1113 .and_then(|read| read.slot)
1114 else {
1115 continue;
1116 };
1117 if let Some(chain) = self.nodes[bus].clips[position].chain.as_mut() {
1118 chain.ran_in = block;
1119 }
1120 }
1121 let buses = &mut self.nodes;
1122 self.live_chains.retain(|&(bus, position)| {
1123 let Some(clip) = buses[bus].clips[position].chain.as_mut() else {
1124 return false;
1125 };
1126 if clip.ran_in == block {
1127 return true;
1128 }
1129 clip.chain = None;
1130 clip.next_input = None;
1131 false
1132 });
1133 }
1134
1135 fn ctx(&self, sample: i64, transport: TransportState) -> ProcessCtx {
1136 ProcessCtx {
1137 position: MediaTime::from_ticks(ticks_at(sample, self.sample_rate)),
1138 sample_position: sample,
1139 sample_rate: self.sample_rate,
1140 transport,
1141 }
1142 }
1143
1144 pub fn set_normalization_gain_db(&mut self, gain_db: f64) -> Result<(), EngineError> {
1151 #[allow(clippy::cast_possible_truncation)]
1152 let gain = libm::pow(10.0, gain_db / 20.0) as f32;
1153 if !gain_db.is_finite() || !gain.is_normal() {
1154 return Err(EngineError::InvalidNormalizationGain);
1155 }
1156 self.normalization_gain = gain;
1157 Ok(())
1158 }
1159
1160 pub const fn set_hold_incomplete_blocks(&mut self, hold: bool) {
1164 self.hold_incomplete = hold;
1165 }
1166
1167 pub fn set_loudness_metering(&mut self, enabled: bool) -> Result<(), EngineError> {
1176 if enabled {
1177 self.normalization_gain = 1.0;
1178 }
1179 self.meter = if enabled {
1180 Some(
1181 LoudnessMeter::new(self.sample_rate, self.layout.channels())
1182 .map_err(|_| EngineError::InvalidAudioConfiguration)?,
1183 )
1184 } else {
1185 None
1186 };
1187 Ok(())
1188 }
1189
1190 #[must_use]
1192 pub fn loudness_report(&self) -> Option<LoudnessReport> {
1193 self.meter.as_ref().map(LoudnessMeter::report)
1194 }
1195
1196 #[must_use]
1199 pub fn limiter_threshold(&self) -> Option<f64> {
1200 self.master
1201 .limiter
1202 .map(|limiter| f64::from(limiter.threshold))
1203 }
1204
1205 pub fn set_output_loudness_metering(&mut self, enabled: bool) -> Result<(), EngineError> {
1212 self.output_meter = if enabled {
1213 Some(
1214 LoudnessMeter::new(self.sample_rate, self.layout.channels())
1215 .map_err(|_| EngineError::InvalidAudioConfiguration)?,
1216 )
1217 } else {
1218 None
1219 };
1220 Ok(())
1221 }
1222
1223 #[must_use]
1225 pub fn output_loudness_report(&self) -> Option<LoudnessReport> {
1226 self.output_meter.as_ref().map(LoudnessMeter::report)
1227 }
1228
1229 #[must_use]
1231 pub fn block(&self, status: &AudioRenderStatus) -> AudioBlock {
1232 AudioBlock {
1233 start_sample: status.start_sample,
1234 sample_rate: self.sample_rate,
1235 speakers: match self.layout {
1236 ChannelLayout::Mono => SpeakerLayout::MONO,
1237 ChannelLayout::Stereo => SpeakerLayout::STEREO,
1238 },
1239 channels: (0..self.layout.channels())
1240 .map(|channel| self.output[channel][..status.frames].to_vec())
1241 .collect(),
1242 }
1243 }
1244
1245 #[must_use]
1248 pub fn tap_block(&self, index: usize, status: &AudioRenderStatus) -> Option<AudioBlock> {
1249 let tap = self.host_taps.get(index)?;
1250 Some(AudioBlock {
1251 start_sample: status.start_sample,
1252 sample_rate: self.sample_rate,
1253 speakers: match self.layout {
1254 ChannelLayout::Mono => SpeakerLayout::MONO,
1255 ChannelLayout::Stereo => SpeakerLayout::STEREO,
1256 },
1257 channels: (0..self.layout.channels())
1258 .map(|channel| tap.planes[channel][..status.frames].to_vec())
1259 .collect(),
1260 })
1261 }
1262
1263 fn bus_of(&self, clip: &ActiveAudioClip) -> Option<usize> {
1265 match self.nodes.get(clip.track_order) {
1266 Some(bus) if bus.track.as_ref() == Some(clip.track_id) => Some(clip.track_order),
1267 _ => self.bus_of_track.get(clip.track_id).copied(),
1268 }
1269 }
1270
1271 fn slot_of(&self, clip: &ActiveAudioClip) -> Option<(usize, usize)> {
1273 let slot = (clip.track_order, clip.clip_order);
1274 let matches = self
1275 .nodes
1276 .get(slot.0)
1277 .and_then(|bus| bus.clips.get(slot.1))
1278 .is_some_and(|found| found.id == *clip.clip_id);
1279 if matches {
1280 Some(slot)
1281 } else {
1282 self.slot_of_clip.get(clip.clip_id).copied()
1283 }
1284 }
1285
1286 fn clip_chain(&self, (bus, position): (usize, usize)) -> Option<&ClipChain> {
1287 self.nodes[bus].clips[position].chain.as_ref()
1288 }
1289
1290 fn block_span(&self, start: i64, frames: i64) -> Result<TimeRange, EngineError> {
1293 let invalid = EngineError::InvalidAudioConfiguration;
1294 let span_end = start
1295 .checked_add(frames)
1296 .and_then(|end| end.checked_add(self.lookahead))
1297 .ok_or(invalid.clone())?;
1298 let start_ticks = checked_ticks_at(start, self.sample_rate).ok_or(invalid.clone())?;
1299 let end_ticks = checked_ticks_at(span_end, self.sample_rate)
1300 .zip(start_ticks.checked_add(1))
1301 .map(|(end, after_start)| end.max(after_start))
1302 .ok_or(invalid.clone())?;
1303 TimeRange::new(
1304 MediaTime::from_ticks(start_ticks),
1305 MediaTime::from_ticks(end_ticks),
1306 )
1307 .map_err(|_| invalid)
1308 }
1309
1310 fn clip_read(
1313 &self,
1314 clip: &ActiveAudioClip,
1315 start: i64,
1316 frames: usize,
1317 stages: Stages,
1318 ) -> Option<ClipRead> {
1319 let bus = self.bus_of(clip)?;
1320 let node = &self.nodes[bus];
1321 if !clip.audio.is_audible() || !node.processed {
1322 return None;
1323 }
1324 let bus_input = start + node.ahead_of_output + node.latency;
1325 let slot = self.slot_of(clip);
1326 let chain = slot.and_then(|slot| self.clip_chain(slot));
1327 let lead = chain.map_or(node.chain_lead, |chain| chain.lead);
1328 if !stages.run(lead) {
1329 return None;
1330 }
1331 let clip_latency = chain.map_or(0, |chain| chain.latency);
1332 let chain_input = bus_input + clip_latency;
1333 let window = self.clip_window(clip, chain_input, frames, clip_latency)?;
1334 Some(ClipRead {
1335 bus,
1336 bus_input,
1337 slot,
1338 first: chain_input + i64::try_from(window.offset).ok()?,
1339 window,
1340 })
1341 }
1342
1343 fn clip_window(
1346 &self,
1347 clip: &ActiveAudioClip,
1348 input: i64,
1349 frames: usize,
1350 latency: i64,
1351 ) -> Option<ClipWindow> {
1352 let first = sample_at_or_after(clip.timeline_range.start().ticks(), self.sample_rate);
1353 let last = sample_at_or_after(clip.timeline_range.end().ticks(), self.sample_rate);
1354 let block_end = input.checked_add(i64::try_from(frames).ok()?)?;
1355 let begin = first.max(input);
1356 let end = last.saturating_add(latency).min(block_end);
1357 if end <= begin {
1358 return None;
1359 }
1360 Some(ClipWindow {
1361 offset: usize::try_from(begin - input).ok()?,
1362 count: usize::try_from(end - begin).ok()?,
1363 content: usize::try_from((last.min(end) - begin).max(0)).ok()?,
1364 })
1365 }
1366
1367 fn fill_clip(
1370 &mut self,
1371 snapshot: &EngineProject,
1372 clip: &ActiveAudioClip,
1373 read: &ClipRead,
1374 provider: &dyn AudioBlockProvider,
1375 fill: Fill,
1376 ) -> bool {
1377 let (first_sample, count, content) = (read.first, read.window.count, read.window.content);
1378 if fill == Fill::Samples {
1379 for channel in 0..self.layout.channels() {
1380 self.clip_a[channel][..count].fill(0.0);
1381 }
1382 }
1383 let count = content;
1385 if count == 0 {
1386 return true;
1387 }
1388 let rate = self.sample_rate;
1389 match clip.time_map {
1390 TimeMap::Freeze { .. } => true,
1392 TimeMap::Forward | TimeMap::Reverse if stretches(clip) => {
1393 self.read_stretched(clip, None, first_sample, 0, count, provider, fill)
1394 }
1395 TimeMap::Forward | TimeMap::Reverse => {
1396 let reversed = *clip.time_map == TimeMap::Reverse;
1397 SourceMap::stretched(clip, reversed, rate).is_some_and(|map| {
1398 self.read_source(clip, &map, first_sample, 0, count, provider, fill)
1399 })
1400 }
1401 TimeMap::Loop { mode } => {
1402 self.fill_loop(clip, *mode, first_sample, count, provider, fill)
1403 }
1404 TimeMap::Curve { .. } => {
1405 self.fill_curve(snapshot, clip, first_sample, count, provider, fill)
1406 }
1407 }
1408 }
1409
1410 fn fill_loop(
1412 &mut self,
1413 clip: &ActiveAudioClip,
1414 mode: LoopMode,
1415 first_sample: i64,
1416 count: usize,
1417 provider: &dyn AudioBlockProvider,
1418 fill: Fill,
1419 ) -> bool {
1420 let rate = self.sample_rate;
1421 let end = clip.timeline_range.end().ticks();
1422 let fade = wrap_fade(rate);
1423 let mut complete = true;
1424 let mapped = loop_pieces(clip, mode, first_sample, count, rate, |piece| {
1425 complete &= self.read_source(
1426 clip,
1427 &piece.map,
1428 piece.sample,
1429 piece.index,
1430 piece.length,
1431 provider,
1432 fill,
1433 );
1434 if mode == LoopMode::Repeat && fill == Fill::Samples {
1435 let fade_in = (piece.pass > 0).then(|| sample_at_or_after(piece.pass_start, rate));
1437 let fade_out = (piece.pass_end < end).then_some(piece.piece_end);
1438 self.fade_wraps(
1439 piece.sample,
1440 piece.index,
1441 piece.length,
1442 fade_in,
1443 fade_out,
1444 fade,
1445 );
1446 }
1447 });
1448 mapped && complete
1449 }
1450
1451 fn fade_wraps(
1454 &mut self,
1455 first_sample: i64,
1456 offset: usize,
1457 count: usize,
1458 fade_in: Option<i64>,
1459 fade_out: Option<i64>,
1460 fade: i64,
1461 ) {
1462 #[allow(clippy::cast_precision_loss)]
1463 let fade = fade as f64;
1464 for index in 0..count {
1465 let sample = first_sample + i64::try_from(index).unwrap_or(i64::MAX);
1466 #[allow(clippy::cast_precision_loss)]
1467 let after = fade_in.map_or(f64::INFINITY, |wrap| (sample - wrap) as f64 + 0.5);
1468 #[allow(clippy::cast_precision_loss)]
1469 let before = fade_out.map_or(f64::INFINITY, |wrap| (wrap - sample) as f64 - 0.5);
1470 let distance = after.min(before);
1471 if distance >= fade {
1472 continue;
1473 }
1474 #[allow(clippy::cast_possible_truncation)]
1475 let gain = (distance / fade).clamp(0.0, 1.0) as f32;
1476 for channel in 0..self.layout.channels() {
1477 self.clip_a[channel][offset + index] *= gain;
1478 }
1479 }
1480 }
1481
1482 #[allow(clippy::too_many_arguments)]
1485 fn read_source(
1486 &mut self,
1487 clip: &ActiveAudioClip,
1488 map: &SourceMap,
1489 first_sample: i64,
1490 offset: usize,
1491 count: usize,
1492 provider: &dyn AudioBlockProvider,
1493 fill: Fill,
1494 ) -> bool {
1495 let Some((request_start, request_end)) = map.request(first_sample, count) else {
1497 return false;
1498 };
1499 let request_frames =
1500 usize::try_from(request_end.saturating_sub(request_start)).unwrap_or(0);
1501 let Some(span) = provider.block(
1502 clip.source_id,
1503 clip.audio.stream,
1504 request_start,
1505 request_frames,
1506 ) else {
1507 return false;
1508 };
1509 if !span.covers(request_start, request_end) {
1511 return false;
1512 }
1513 let source = span.block;
1514 if source.sample_rate != self.sample_rate {
1515 return false;
1516 }
1517
1518 let Some(downmix) = clip_downmix(clip, source, self.layout) else {
1519 return false;
1520 };
1521 if fill == Fill::Presence {
1522 return true;
1523 }
1524 #[cfg(test)]
1525 {
1526 self.samples_read += count;
1527 }
1528 let read = SourceRead {
1529 planes: source.channels.as_slice(),
1530 downmix: &downmix,
1531 start: source.start_sample,
1532 offset,
1533 count,
1534 };
1535 match (map.cursor(first_sample), map.interpolator()) {
1536 (None, interpolator) => self.read_divided(&read, map, first_sample, interpolator),
1538 (Some(cursor), None) => self.read_copied(&read, cursor),
1539 (Some(cursor), Some(interpolator)) => {
1540 self.read_filtered(&read, map, cursor, interpolator);
1541 }
1542 }
1543 true
1544 }
1545
1546 fn read_copied(&mut self, read: &SourceRead<'_>, cursor: RationalCursor) {
1548 let Some(first) = cursor.whole.checked_sub(read.start) else {
1549 return;
1550 };
1551 for channel in 0..self.layout.channels() {
1552 let mix = read.downmix.channel(channel);
1553 let mut at = first;
1554 let outputs = &mut self.clip_a[channel][read.offset..read.offset + read.count];
1555 if let Some(plane) = mix.unity() {
1556 let plane = read.planes[plane].as_slice();
1557 for output in outputs {
1558 *output = copied(plane, at);
1559 at = at.wrapping_add(cursor.step_whole);
1560 }
1561 } else {
1562 for output in outputs {
1563 *output = mixed_sample(mix, read.planes, at);
1564 at = at.wrapping_add(cursor.step_whole);
1565 }
1566 }
1567 }
1568 }
1569
1570 fn read_filtered(
1573 &mut self,
1574 read: &SourceRead<'_>,
1575 map: &SourceMap,
1576 mut cursor: RationalCursor,
1577 interpolator: Interpolator,
1578 ) {
1579 let mut weights = std::mem::take(&mut self.weights);
1580 let reach = interpolator.half_taps() - 1;
1581 let taps = usize::try_from(2 * interpolator.half_taps()).unwrap_or(0);
1582 let phases = usize::try_from(cursor.period())
1583 .ok()
1584 .filter(|&period| period <= read.count / 2 && period * taps <= MAX_CACHED_WEIGHTS);
1585 if let Some(phases) = phases {
1586 weights.resize(phases * taps, 0.0);
1587 let mut scratch = std::mem::take(&mut self.phase_weights);
1588 let mut walk = cursor;
1589 for row in weights.chunks_exact_mut(taps) {
1590 interpolator.weights(map.fraction(&walk).1, &mut scratch);
1591 row.copy_from_slice(&scratch);
1592 walk.advance();
1593 }
1594 self.phase_weights = scratch;
1595 }
1596 let mut phase = 0;
1597 for index in 0..read.count {
1598 let (whole, fraction) = map.fraction(&cursor);
1599 cursor.advance();
1600 let row = if let Some(phases) = phases {
1601 let row = phase;
1602 phase = if phase + 1 == phases { 0 } else { phase + 1 };
1603 &weights[row * taps..(row + 1) * taps]
1604 } else {
1605 interpolator.weights(fraction, &mut weights);
1606 &weights[..]
1607 };
1608 let Some(first) = whole
1609 .checked_sub(read.start)
1610 .and_then(|at| at.checked_sub(reach))
1611 else {
1612 continue;
1613 };
1614 for channel in 0..self.layout.channels() {
1615 self.clip_a[channel][read.offset + index] =
1616 filtered_sample(read.downmix.channel(channel), read.planes, first, row);
1617 }
1618 }
1619 self.weights = weights;
1620 }
1621
1622 fn read_divided(
1624 &mut self,
1625 read: &SourceRead<'_>,
1626 map: &SourceMap,
1627 first_sample: i64,
1628 interpolator: Option<Interpolator>,
1629 ) {
1630 let mut weights = std::mem::take(&mut self.weights);
1631 for index in 0..read.count {
1632 let sample = first_sample + i64::try_from(index).unwrap_or(0);
1633 let Some((whole, fraction)) = map.position(sample) else {
1634 continue;
1635 };
1636 let Some(at) = whole.checked_sub(read.start) else {
1637 continue;
1638 };
1639 if let Some(interpolator) = interpolator {
1640 interpolator.weights(fraction, &mut weights);
1641 }
1642 for channel in 0..self.layout.channels() {
1643 let mix = read.downmix.channel(channel);
1644 self.clip_a[channel][read.offset + index] = match interpolator {
1645 None => mixed_sample(mix, read.planes, at),
1646 Some(interpolator) => filtered_sample(
1647 mix,
1648 read.planes,
1649 at - interpolator.half_taps() + 1,
1650 &weights,
1651 ),
1652 };
1653 }
1654 }
1655 self.weights = weights;
1656 }
1657
1658 fn apply_clip_chain(
1661 &mut self,
1662 (bus, position): (usize, usize),
1663 input: i64,
1664 transport: TransportState,
1665 count: usize,
1666 context: &SampleContext<'_>,
1667 ) {
1668 let ctx = self.ctx(input, transport);
1669 let (layout, sample_rate, max_block) = (self.layout, self.sample_rate, self.max_block);
1670 let Some(clip_chain) = self.nodes[bus].clips[position].chain.as_mut() else {
1671 return;
1672 };
1673 if clip_chain.chain.is_none() {
1674 self.live_chains.push((bus, position));
1675 }
1676 let effects = &clip_chain.effects;
1677 let (chain, control) = clip_chain
1678 .chain
1679 .get_or_insert_with(|| clip_processors(effects, layout, sample_rate, max_block));
1680 clip_chain.ran_in = self.blocks_mixed;
1681 if clip_chain.next_input != Some(input) {
1682 chain.reset();
1683 }
1684 clip_chain.next_input = Some(input + i64::try_from(count).unwrap_or(0));
1685 let controls = control.fill(input, count, sample_rate, context);
1686 chain.process_in_place_controlled(
1687 &ctx,
1688 &controls,
1689 &mut self.clip_a,
1690 &mut self.clip_b,
1691 count,
1692 );
1693 #[cfg(test)]
1694 self.note_held();
1695 }
1696
1697 #[cfg(test)]
1699 fn note_held(&mut self) {
1700 let held = self
1701 .live_chains
1702 .iter()
1703 .filter_map(|&(bus, position)| self.nodes[bus].clips[position].chain.as_ref())
1704 .filter(|clip| clip.chain.is_some())
1705 .fold((0, 0), |(effects, delay), clip| {
1706 (
1707 effects + clip.effects.len(),
1708 delay
1709 + clip
1710 .effects
1711 .iter()
1712 .map(AudioEffect::delay_ticks)
1713 .sum::<u64>(),
1714 )
1715 });
1716 self.most_held = (self.most_held.0.max(held.0), self.most_held.1.max(held.1));
1717 }
1718
1719 #[allow(clippy::too_many_arguments)]
1722 fn mix_clip_into_bus(
1723 &mut self,
1724 clip: &ActiveAudioClip,
1725 bus_index: usize,
1726 start_sample: i64,
1727 offset: usize,
1728 count: usize,
1729 frames: usize,
1730 context: &SampleContext<'_>,
1731 ) {
1732 let channels = self.layout.channels();
1733 let sample_rate = self.sample_rate;
1734 let bus = &mut self.nodes[bus_index];
1735 let first = start_sample + i64::try_from(offset).unwrap_or(0);
1736 bus.make_live(channels, frames);
1737 let gain = constant_value(&clip.audio.gain).map(|gain| gain.clamp(0.0, MAX_GAIN));
1738 let weights =
1739 constant_value(&clip.audio.pan).map(|pan| pan_gains(pan.clamp(-1.0, 1.0), channels));
1740 if let (Some(gain), Some(weights), false) =
1741 (gain, weights, fades_reach(clip, first, count, sample_rate))
1742 {
1743 for (channel, weight) in weights.iter().enumerate().take(channels) {
1744 let input = &self.clip_a[channel][..count];
1745 let output = &mut bus.output[channel][offset..offset + count];
1746 for (output, sample) in output.iter_mut().zip(input) {
1747 *output += sample * gain * weight;
1748 }
1749 }
1750 return;
1751 }
1752 let audio = clip.audio;
1753 fill_envelope(
1754 &mut self.envelope[..],
1755 first,
1756 count,
1757 sample_rate,
1758 |ticks| {
1759 earliest(
1760 earliest(
1761 next_knot(&audio.gain, ticks, context),
1762 next_knot(&audio.pan, ticks, context),
1763 ),
1764 next_fade_edge(clip, ticks),
1765 )
1766 },
1767 |time| {
1768 let gain = sample_scalar(&audio.gain, time, context).clamp(0.0, MAX_GAIN)
1769 * fade_gain(clip, time);
1770 let [left, right] = pan_gains(sample_scalar(&audio.pan, time, context), channels);
1771 [gain, left, right]
1772 },
1773 );
1774 let [gains, left, right, _] = &self.envelope;
1775 for (channel, weights) in [left, right].into_iter().enumerate().take(channels) {
1776 let input = &self.clip_a[channel][..count];
1777 let output = &mut bus.output[channel][offset..offset + count];
1778 for (((output, sample), gain), weight) in
1779 output.iter_mut().zip(input).zip(gains).zip(weights)
1780 {
1781 *output += sample * gain * weight;
1782 }
1783 }
1784 }
1785
1786 fn mix_tracks_and_buses(
1787 &mut self,
1788 start: i64,
1789 transport: TransportState,
1790 frames: usize,
1791 stages: Stages,
1792 context: &SampleContext<'_>,
1793 ) {
1794 for position in 0..self.nodes_sources_first.len() {
1795 let node = self.nodes_sources_first[position];
1796 if node >= self.track_count {
1797 self.sum_into_bus(node, start, frames, stages, context);
1798 }
1799 self.run_chain(node, start, transport, frames, stages, context);
1800 if self.nodes[node].feeds_taps() {
1801 self.feed_delayed_taps(node, start, frames, stages, context);
1802 }
1803 }
1804 }
1805
1806 fn run_chain(
1807 &mut self,
1808 index: usize,
1809 start: i64,
1810 transport: TransportState,
1811 frames: usize,
1812 stages: Stages,
1813 context: &SampleContext<'_>,
1814 ) {
1815 let channels = self.layout.channels();
1816 let sample_rate = self.sample_rate;
1817 let bus = &mut self.nodes[index];
1818 if !bus.processed || !stages.run(bus.chain_lead) || bus.chain.passes_through() {
1819 return;
1820 }
1821 let input = start + bus.ahead_of_output + bus.latency;
1822 let ctx = &ProcessCtx {
1823 position: MediaTime::from_ticks(ticks_at(input, sample_rate)),
1824 sample_position: input,
1825 sample_rate,
1826 transport,
1827 };
1828 bus.make_live(channels, frames);
1829 for channel in 0..channels {
1830 self.bus_in[channel][..frames].copy_from_slice(&bus.output[channel][..frames]);
1831 }
1832 if bus.keys.is_empty() {
1833 let controls = bus.control.fill(input, frames, sample_rate, context);
1834 let block = (&self.bus_in, &mut bus.output, frames);
1835 process_block(&mut bus.chain, ctx, channels, &[], &controls, block);
1836 return;
1837 }
1838 let mut chain = std::mem::replace(&mut bus.chain, ProcessorChain::new(self.layout));
1839 let mut control = std::mem::replace(&mut bus.control, ChainControl::none());
1840 let mut output = std::mem::take(&mut bus.output);
1841 let keys = edge::key_planes(&self.nodes[index].keys, &self.nodes, frames);
1842 let controls = control.fill(input, frames, sample_rate, context);
1843 let block = (&self.bus_in, &mut output, frames);
1844 process_block(&mut chain, ctx, channels, &keys, &controls, block);
1845 let bus = &mut self.nodes[index];
1846 bus.chain = chain;
1847 bus.control = control;
1848 bus.output = output;
1849 }
1850
1851 fn sum_into_bus(
1852 &mut self,
1853 index: usize,
1854 start: i64,
1855 frames: usize,
1856 stages: Stages,
1857 context: &SampleContext<'_>,
1858 ) {
1859 let channels = self.layout.channels();
1860 let bus = &self.nodes[index];
1861 if !bus.processed
1862 || !stages.run(bus.chain_lead)
1863 || !bus
1864 .inputs
1865 .iter()
1866 .any(|&input| edge::carries(input, &self.nodes))
1867 {
1868 return;
1869 }
1870 self.nodes[index].make_live(channels, frames);
1871 let mut sum = std::mem::take(&mut self.nodes[index].output);
1872 edge::add_inputs(
1873 &self.nodes[index].inputs,
1874 &self.edges,
1875 &self.nodes,
1876 &mut sum,
1877 &mut BlockRun {
1878 start,
1879 frames,
1880 channels,
1881 sample_rate: self.sample_rate,
1882 envelope: &mut self.envelope,
1883 context,
1884 },
1885 );
1886 self.nodes[index].output = sum;
1887 }
1888
1889 fn feed_delayed_taps(
1890 &mut self,
1891 index: usize,
1892 start: i64,
1893 frames: usize,
1894 stages: Stages,
1895 context: &SampleContext<'_>,
1896 ) {
1897 let node = &mut self.nodes[index];
1898 if !node.processed || !stages.run(node.chain_lead) {
1899 return;
1900 }
1901 edge::feed_delayed_taps(
1902 node,
1903 &mut BlockRun {
1904 start,
1905 frames,
1906 channels: self.layout.channels(),
1907 sample_rate: self.sample_rate,
1908 envelope: &mut self.envelope,
1909 context,
1910 },
1911 stages,
1912 );
1913 }
1914
1915 #[allow(clippy::too_many_arguments)]
1916 fn finish_master(
1917 &mut self,
1918 start_sample: i64,
1919 master_input: i64,
1920 transport: TransportState,
1921 frames: usize,
1922 stages: Stages,
1923 complete: bool,
1924 context: &SampleContext<'_>,
1925 ) {
1926 let channels = self.layout.channels();
1927 let input_ctx = self.ctx(master_input, transport);
1928 let ctx = &self.ctx(start_sample, transport);
1929 let keys = edge::key_planes(&self.master_keys, &self.nodes, frames);
1930 let controls = self
1931 .master_control
1932 .fill(master_input, frames, self.sample_rate, context);
1933 let block = (&self.mix, &mut self.output, frames);
1934 process_block(
1935 &mut self.master_chain,
1936 &input_ctx,
1937 channels,
1938 &keys,
1939 &controls,
1940 block,
1941 );
1942 if let Some(gain) = constant_value(&self.master.gain) {
1943 let gain = gain.clamp(0.0, MAX_GAIN);
1944 for channel in 0..channels {
1945 for sample in &mut self.output[channel][..frames] {
1946 *sample *= gain;
1947 }
1948 }
1949 } else {
1950 let gain = &self.master.gain;
1951 fill_envelope(
1952 &mut self.envelope[..],
1953 start_sample,
1954 frames,
1955 self.sample_rate,
1956 |ticks| next_knot(gain, ticks, context),
1957 |time| [sample_scalar(gain, time, context).clamp(0.0, MAX_GAIN)],
1958 );
1959 for channel in 0..channels {
1960 let envelope = &self.envelope[0][..frames];
1961 for (sample, gain) in self.output[channel][..frames].iter_mut().zip(envelope) {
1962 *sample *= gain;
1963 }
1964 }
1965 }
1966 if self.normalization_gain.to_bits() != 1.0_f32.to_bits() {
1967 for channel in 0..channels {
1968 for sample in &mut self.output[channel][..frames] {
1969 *sample *= self.normalization_gain;
1970 }
1971 }
1972 }
1973 let measured = stages.target.is_none() && complete;
1975 if measured && let Some(meter) = self.meter.as_mut() {
1976 let planes = [&self.output[0][..frames], &self.output[1][..frames]];
1977 let _ = meter.push(&planes[..channels]);
1979 }
1980 if let Some(limiter) = self
1981 .limiter
1982 .as_mut()
1983 .filter(|_| stages.run(self.limiter_lead))
1984 {
1985 for channel in 0..channels {
1986 self.mix[channel][..frames].copy_from_slice(&self.output[channel][..frames]);
1987 }
1988 match channels {
1989 1 => limiter.process(
1990 ctx,
1991 &[&self.mix[0][..frames]],
1992 &mut [&mut self.output[0][..frames]],
1993 ),
1994 2 => {
1995 let (left, right) = self.output.split_at_mut(1);
1996 limiter.process(
1997 ctx,
1998 &[&self.mix[0][..frames], &self.mix[1][..frames]],
1999 &mut [&mut left[0][..frames], &mut right[0][..frames]],
2000 );
2001 }
2002 _ => {}
2003 }
2004 }
2005 if measured && let Some(meter) = self.output_meter.as_mut() {
2006 let planes = [&self.output[0][..frames], &self.output[1][..frames]];
2007 let _ = meter.push(&planes[..channels]);
2008 }
2009 }
2010}
2011
2012fn master_chain_of(
2013 master: &MasterAudio,
2014 layout: ChannelLayout,
2015 sample_rate: u32,
2016 max_block: usize,
2017) -> (ProcessorChain, ChainLayout, ChainControl) {
2018 let mut chain = ProcessorChain::new(layout);
2019 let mut chain_layout = push_effects(&mut chain, &master.effects, sample_rate);
2020 chain.prepare(sample_rate, max_block);
2021 let control = ChainControl::new(std::mem::take(&mut chain_layout.retuned), &chain, max_block);
2022 (chain, chain_layout, control)
2023}
2024
2025fn slots_by_clip(nodes: &[MixNode]) -> HashMap<ClipId, (usize, usize)> {
2026 nodes
2027 .iter()
2028 .enumerate()
2029 .flat_map(|(bus, track)| {
2030 track
2031 .clips
2032 .iter()
2033 .enumerate()
2034 .map(move |(position, slot)| (slot.id.clone(), (bus, position)))
2035 })
2036 .collect()
2037}
2038
2039fn clip_slots(
2041 clips: &[alpha2_model::Clip],
2042 layout: ChannelLayout,
2043 sample_rate: u32,
2044 max_block: usize,
2045) -> Vec<ClipSlot> {
2046 clips
2047 .iter()
2048 .map(|clip| ClipSlot {
2049 id: clip.id.clone(),
2050 chain: (!clip.audio.effects.is_empty()).then(|| {
2051 let (chain, _) =
2053 clip_processors(&clip.audio.effects, layout, sample_rate, max_block);
2054 ClipChain {
2055 effects: clip.audio.effects.clone(),
2056 chain: None,
2057 ran_in: 0,
2058 latency: i64::from(chain.latency_samples()),
2059 history: chain.history_samples(),
2060 next_input: None,
2061 lead: 0,
2062 }
2063 }),
2064 })
2065 .collect()
2066}
2067
2068fn clip_processors(
2069 effects: &[AudioEffect],
2070 layout: ChannelLayout,
2071 sample_rate: u32,
2072 max_block: usize,
2073) -> (ProcessorChain, ChainControl) {
2074 let mut chain = ProcessorChain::new(layout);
2075 let retuned = push_effects(&mut chain, effects, sample_rate).retuned;
2076 chain.prepare_nodes(sample_rate, max_block);
2077 let control = ChainControl::new(retuned, &chain, max_block);
2078 (chain, control)
2079}
2080
2081fn assign_leads(graph: &mut MixGraph, master_lead: i64, settling: Settling) -> i64 {
2082 let mut longest = master_lead;
2083 for position in (0..graph.nodes_sources_first.len()).rev() {
2084 let index = graph.nodes_sources_first[position];
2085 let readers = graph.settle_taps_and_longest_reader_lead(index, master_lead, settling);
2086 let bus = &mut graph.nodes[index];
2087 bus.chain_lead = settling.lead(readers, bus.chain.history_samples());
2088 longest = longest.max(bus.chain_lead);
2089 for clip in bus.clips.iter_mut().filter_map(|slot| slot.chain.as_mut()) {
2090 clip.lead = settling.lead(bus.chain_lead, clip.history);
2091 longest = longest.max(clip.lead);
2092 }
2093 }
2094 longest
2095}
2096
2097#[derive(Clone, Copy)]
2099struct Settling(i64);
2100
2101impl Settling {
2102 fn lead(self, downstream: i64, history: u32) -> i64 {
2105 downstream
2106 .saturating_add(i64::from(history))
2107 .min(self.0.max(downstream))
2108 }
2109}
2110
2111#[derive(Clone, Copy)]
2114struct Stages {
2115 target: Option<i64>,
2116 block_end: i64,
2117 lookahead: i64,
2118}
2119
2120impl Stages {
2121 fn run(self, lead: i64) -> bool {
2122 self.target
2123 .is_none_or(|target| self.block_end > Self::start(target, lead, self.lookahead))
2124 }
2125
2126 fn start(target: i64, lead: i64, lookahead: i64) -> i64 {
2129 (target - lead).max(0).saturating_sub(lookahead)
2130 }
2131}
2132
2133fn stage_leads(graph: &MixGraph, master_lead: i64, limiter_lead: i64) -> Vec<i64> {
2135 let mut leads = vec![master_lead, limiter_lead];
2136 for bus in &graph.nodes {
2137 leads.push(bus.chain_lead);
2138 leads.extend(
2139 bus.clips
2140 .iter()
2141 .filter_map(|slot| slot.chain.as_ref())
2142 .map(|chain| chain.lead),
2143 );
2144 }
2145 leads.extend(
2146 graph
2147 .nodes
2148 .iter()
2149 .flat_map(|node| &node.delayed_taps)
2150 .map(|tap| tap.settling_lead),
2151 );
2152 leads.sort_unstable_by(|a, b| b.cmp(a));
2153 leads.dedup();
2154 leads
2155}
2156
2157fn buffers(max_block: usize) -> [Vec<f32>; 2] {
2158 [vec![0.0; max_block], vec![0.0; max_block]]
2159}
2160
2161struct ChainLayout {
2162 first_processor_of_effect: Vec<usize>,
2163 key_slot_of_effect: Vec<Option<usize>>,
2164 processors: usize,
2165 retuned: Vec<Retuned>,
2166}
2167
2168impl ChainLayout {
2169 fn first_processor(&self, effect: usize) -> usize {
2170 self.first_processor_of_effect
2171 .get(effect)
2172 .copied()
2173 .unwrap_or(self.processors)
2174 }
2175
2176 fn key_slot(&self, effect: usize) -> Option<usize> {
2177 self.key_slot_of_effect.get(effect).copied().flatten()
2178 }
2179
2180 fn retune(&mut self, params: Vec<Param>) {
2181 if control::varies(¶ms) {
2182 self.retuned.push(Retuned {
2183 processor: self.processors,
2184 params,
2185 });
2186 }
2187 }
2188}
2189
2190fn push_effects(
2191 chain: &mut ProcessorChain,
2192 effects: &[AudioEffect],
2193 sample_rate: u32,
2194) -> ChainLayout {
2195 let mut build = ChainBuild {
2196 chain,
2197 sample_rate,
2198 layout: ChainLayout {
2199 first_processor_of_effect: Vec::with_capacity(effects.len()),
2200 key_slot_of_effect: Vec::with_capacity(effects.len()),
2201 processors: 0,
2202 retuned: Vec::new(),
2203 },
2204 };
2205 for effect in effects {
2206 build
2207 .layout
2208 .first_processor_of_effect
2209 .push(build.layout.processors);
2210 let key_slot = match effect {
2211 AudioEffect::Eq { bands } => {
2212 for band in bands {
2213 build.band(band);
2214 }
2215 None
2216 }
2217 AudioEffect::Compressor { .. } => build.compressor(effect),
2218 AudioEffect::Expander { .. } => build.expander(effect),
2219 AudioEffect::Ducker {
2220 sidechain: _,
2221 threshold,
2222 depth_db,
2223 attack_ms,
2224 release_ms,
2225 } => {
2226 let params = vec![
2227 Param::new(threshold, Domain::POSITIVE),
2228 Param::new(depth_db, Domain::LEVEL_DB),
2229 ];
2230 let ducker = build.slowest(¶ms, |values| {
2231 Ducker::new(values[0], values[1], *attack_ms, *release_ms)
2232 });
2233 build.push(ducker, params, Reads::ProgramAndKey)
2234 }
2235 AudioEffect::Delay {
2236 time_ms,
2237 feedback,
2238 mix,
2239 } => {
2240 let params = vec![
2241 Param::new(feedback, Domain::DELAY_FEEDBACK),
2242 Param::new(mix, Domain::UNIT),
2243 ];
2244 let delay =
2245 build.slowest(¶ms, |values| Delay::new(*time_ms, values[0], values[1]));
2246 build.push(delay, params, Reads::Program)
2247 }
2248 AudioEffect::Reverb {
2249 room_size,
2250 damping,
2251 mix,
2252 } => {
2253 let params = vec![Param::new(mix, Domain::UNIT)];
2254 let reverb = build.slowest(¶ms, |values| {
2255 SchroederReverb::new(*room_size, *damping, values[0])
2256 });
2257 build.push(reverb, params, Reads::Program)
2258 }
2259 AudioEffect::Matrix { left, right } => {
2260 let params: Vec<Param> = left
2261 .iter()
2262 .chain(right)
2263 .map(|gain| Param::new(gain, Domain::MATRIX_GAIN))
2264 .collect();
2265 let matrix = build.slowest(¶ms, |values| {
2266 Matrix::new([values[0], values[1]], [values[2], values[3]])
2267 });
2268 build.push(matrix, params, Reads::Program)
2269 }
2270 };
2271 build.layout.key_slot_of_effect.push(key_slot);
2272 }
2273 build.layout
2274}
2275
2276#[derive(Clone, Copy)]
2277enum Reads {
2278 Program,
2279 ProgramAndKey,
2280}
2281
2282struct ChainBuild<'a> {
2283 chain: &'a mut ProcessorChain,
2284 sample_rate: u32,
2285 layout: ChainLayout,
2286}
2287
2288impl ChainBuild<'_> {
2289 fn slowest<P: Processor>(&self, params: &[Param], make: impl Fn(&[f32]) -> P) -> P {
2290 control::slowest_to_settle(params, self.sample_rate, make)
2291 }
2292
2293 fn push(
2294 &mut self,
2295 effect: impl Processor + 'static,
2296 params: Vec<Param>,
2297 reads: Reads,
2298 ) -> Option<usize> {
2299 let key_slot = match reads {
2300 Reads::Program => {
2301 self.chain
2302 .push(effect)
2303 .expect("a model effect reads one input per output");
2304 None
2305 }
2306 Reads::ProgramAndKey => Some(
2307 self.chain
2308 .push_keyed(effect)
2309 .expect("a keyed model effect reads its key as a second input"),
2310 ),
2311 };
2312 self.layout.retune(params);
2313 self.layout.processors += 1;
2314 key_slot
2315 }
2316
2317 fn band(&mut self, band: &alpha2_model::EqBand) {
2318 let kind = biquad_kind(band.kind);
2319 let params = vec![
2320 Param::new(&band.frequency_hz, Domain::EQ_FREQUENCY_HZ),
2321 Param::new(&band.q, Domain::EQ_Q),
2322 Param::new(&band.gain_db, Domain::EQ_GAIN_DB),
2323 ];
2324 let filter = self.slowest(¶ms, |values| {
2325 Biquad::new(kind, values[0], values[1], values[2])
2326 });
2327 self.push(filter, params, Reads::Program);
2328 }
2329
2330 fn compressor(&mut self, effect: &AudioEffect) -> Option<usize> {
2331 let AudioEffect::Compressor {
2332 threshold_db,
2333 ratio,
2334 knee_db,
2335 makeup_db,
2336 attack_ms,
2337 release_ms,
2338 lookahead_ms,
2339 detector,
2340 detector_filter,
2341 sidechain,
2342 } = effect
2343 else {
2344 return None;
2345 };
2346 let params = vec![
2347 Param::new(threshold_db, Domain::LEVEL_DB),
2348 Param::new(ratio, Domain::COMPRESSOR_RATIO),
2349 Param::new(knee_db, Domain::KNEE_DB),
2350 Param::new(makeup_db, Domain::MAKEUP_DB),
2351 ];
2352 let compressor = self.slowest(¶ms, |values| {
2353 Compressor::new(CompressorSettings {
2354 threshold_db: values[0],
2355 ratio: values[1],
2356 knee_db: values[2],
2357 makeup_db: values[3],
2358 attack_ms: *attack_ms,
2359 release_ms: *release_ms,
2360 lookahead_ms: *lookahead_ms,
2361 detector: match detector {
2362 alpha2_model::Detector::Peak => Detector::Peak,
2363 alpha2_model::Detector::Rms => Detector::Rms,
2364 },
2365 detector_filter: detector_filter.map(detector_filter_of),
2366 })
2367 });
2368 if sidechain.is_some() {
2369 self.push(compressor.keyed(), params, Reads::ProgramAndKey)
2370 } else {
2371 self.push(compressor, params, Reads::Program)
2372 }
2373 }
2374
2375 fn expander(&mut self, effect: &AudioEffect) -> Option<usize> {
2376 let AudioEffect::Expander {
2377 threshold_db,
2378 ratio,
2379 range_db,
2380 attack_ms,
2381 hold_ms,
2382 release_ms,
2383 lookahead_ms,
2384 detector_filter,
2385 sidechain,
2386 } = effect
2387 else {
2388 return None;
2389 };
2390 let params = vec![
2391 Param::new(threshold_db, Domain::LEVEL_DB),
2392 Param::new(ratio, Domain::COMPRESSOR_RATIO),
2393 Param::new(range_db, Domain::EXPANDER_RANGE_DB),
2394 ];
2395 let expander = self.slowest(¶ms, |values| {
2396 Expander::new(ExpanderSettings {
2397 threshold_db: values[0],
2398 ratio: values[1],
2399 range_db: values[2],
2400 attack_ms: *attack_ms,
2401 hold_ms: *hold_ms,
2402 release_ms: *release_ms,
2403 lookahead_ms: *lookahead_ms,
2404 detector_filter: detector_filter.map(detector_filter_of),
2405 })
2406 });
2407 if sidechain.is_some() {
2408 self.push(expander.keyed(), params, Reads::ProgramAndKey)
2409 } else {
2410 self.push(expander, params, Reads::Program)
2411 }
2412 }
2413}
2414
2415const fn biquad_kind(kind: EqBandKind) -> BiquadKind {
2416 match kind {
2417 EqBandKind::Peaking => BiquadKind::Peaking,
2418 EqBandKind::LowPass => BiquadKind::LowPass,
2419 EqBandKind::HighPass => BiquadKind::HighPass,
2420 EqBandKind::LowShelf => BiquadKind::LowShelf,
2421 EqBandKind::HighShelf => BiquadKind::HighShelf,
2422 EqBandKind::Notch => BiquadKind::Notch,
2423 EqBandKind::BandPass => BiquadKind::BandPass,
2424 EqBandKind::AllPass => BiquadKind::AllPass,
2425 }
2426}
2427
2428const fn detector_filter_of(filter: alpha2_model::DetectorFilter) -> DetectorFilter {
2429 DetectorFilter {
2430 kind: biquad_kind(filter.kind),
2431 frequency_hz: filter.frequency_hz,
2432 q: filter.q,
2433 }
2434}
2435
2436fn process_block(
2437 chain: &mut ProcessorChain,
2438 ctx: &ProcessCtx,
2439 channels: usize,
2440 keys: &[[&[f32]; 2]],
2441 controls: &Controls<'_>,
2442 (input, output, frames): (&[Vec<f32>; 2], &mut [Vec<f32>; 2], usize),
2443) {
2444 match channels {
2445 1 => chain.process_controlled(
2446 ctx,
2447 &[&input[0][..frames]],
2448 keys,
2449 controls,
2450 &mut [&mut output[0][..frames]],
2451 ),
2452 2 => {
2453 let (left, right) = output.split_at_mut(1);
2454 chain.process_controlled(
2455 ctx,
2456 &[&input[0][..frames], &input[1][..frames]],
2457 keys,
2458 controls,
2459 &mut [&mut left[0][..frames], &mut right[0][..frames]],
2460 );
2461 }
2462 _ => {}
2463 }
2464}
2465
2466fn ticks_at(sample: i64, sample_rate: u32) -> i64 {
2467 checked_ticks_at(sample, sample_rate).unwrap_or(i64::MAX)
2468}
2469
2470fn checked_ticks_at(sample: i64, sample_rate: u32) -> Option<i64> {
2472 let rate = i128::from(sample_rate.max(1));
2473 i64::try_from((i128::from(sample) * i128::from(TICKS_PER_SECOND)).div_euclid(rate)).ok()
2474}
2475
2476struct SourceRead<'a> {
2478 planes: &'a [Vec<f32>],
2479 downmix: &'a Downmix,
2480 start: i64,
2482 offset: usize,
2483 count: usize,
2484}
2485
2486struct ClipRead {
2488 bus: usize,
2489 bus_input: i64,
2490 slot: Option<(usize, usize)>,
2491 first: i64,
2493 window: ClipWindow,
2494}
2495
2496#[derive(Clone, Copy)]
2498struct ClipWindow {
2499 offset: usize,
2501 count: usize,
2503 content: usize,
2505}
2506
2507fn ticks_at_or_after(sample: i64, sample_rate: u32) -> Option<i64> {
2509 let rate = i128::from(sample_rate.max(1));
2510 let numerator = i128::from(sample) * i128::from(TICKS_PER_SECOND);
2511 i64::try_from(numerator.div_euclid(rate) + i128::from(numerator.rem_euclid(rate) != 0)).ok()
2512}
2513
2514pub(crate) fn clip_downmix(
2515 clip: &ActiveAudioClip,
2516 source: &AudioBlock,
2517 layout: ChannelLayout,
2518) -> Option<Downmix> {
2519 if source.speakers.channels() != source.channels.len() {
2520 return None;
2521 }
2522 match &clip.audio.channel_map {
2523 Some(map) => Downmix::mapped(map, source.channels.len(), layout),
2524 None => Downmix::new(source.speakers.speakers(), layout),
2525 }
2526}
2527
2528fn merge_need(
2531 needs: &mut Vec<AudioNeed>,
2532 source_id: &SourceId,
2533 stream: Option<u32>,
2534 mut source_range: TimeRange,
2535) {
2536 while let Some(index) = needs.iter().position(|need| {
2538 need.source_id == *source_id
2539 && need.stream == stream
2540 && need.source_range.start() <= source_range.end()
2541 && source_range.start() <= need.source_range.end()
2542 }) {
2543 let existing = needs.remove(index).source_range;
2544 let merged_start = existing.start().min(source_range.start());
2545 let merged_end = existing.end().max(source_range.end());
2546 if let Ok(merged) = TimeRange::new(merged_start, merged_end) {
2547 source_range = merged;
2548 }
2549 }
2550 needs.push(AudioNeed {
2551 source_id: source_id.clone(),
2552 stream,
2553 source_range,
2554 });
2555}
2556
2557fn source_requests(
2560 snapshot: &EngineProject,
2561 stretch: &Stretch,
2562 clip: &ActiveAudioClip,
2563 first_sample: i64,
2564 count: usize,
2565 rate: u32,
2566 mut request: impl FnMut(i64, i64),
2567) {
2568 if count == 0 {
2569 return;
2570 }
2571 match clip.time_map {
2572 TimeMap::Freeze { .. } => {}
2573 TimeMap::Curve { .. } => {
2574 curve_requests(snapshot, stretch, clip, first_sample, count, rate, request);
2575 }
2576 TimeMap::Forward | TimeMap::Reverse if stretches(clip) => {
2577 if let Some((from, to)) =
2578 stretched_request(stretch, clip, None, first_sample, count, rate)
2579 {
2580 request(from, to);
2581 }
2582 }
2583 TimeMap::Forward | TimeMap::Reverse => {
2584 let reversed = *clip.time_map == TimeMap::Reverse;
2585 if let Some((from, to)) = SourceMap::stretched(clip, reversed, rate)
2586 .and_then(|map| map.request(first_sample, count))
2587 {
2588 request(from, to);
2589 }
2590 }
2591 TimeMap::Loop { mode } => {
2592 loop_pieces(clip, *mode, first_sample, count, rate, |piece| {
2593 if let Some((from, to)) = piece.map.request(piece.sample, piece.length) {
2594 request(from, to);
2595 }
2596 });
2597 }
2598 }
2599}
2600
2601fn wrap_fade(rate: u32) -> i64 {
2602 #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
2603 let samples = (f64::from(rate) * LOOP_FADE_SECONDS).round() as i64;
2604 samples.max(1)
2605}
2606
2607struct LoopPiece {
2609 sample: i64,
2611 index: usize,
2612 length: usize,
2613 pass: i64,
2615 pass_start: i64,
2616 pass_end: i64,
2617 piece_end: i64,
2619 map: SourceMap,
2620}
2621
2622fn loop_pieces(
2625 clip: &ActiveAudioClip,
2626 mode: LoopMode,
2627 first_sample: i64,
2628 count: usize,
2629 rate: u32,
2630 mut piece: impl FnMut(LoopPiece),
2631) -> bool {
2632 let Some(period) = clip.source_range.duration().map(MediaTime::ticks) else {
2633 return false;
2634 };
2635 if period <= 0 {
2636 return false;
2637 }
2638 let start = clip.timeline_range.start().ticks();
2639 let mut index = 0;
2640 while index < count {
2641 let sample = first_sample + i64::try_from(index).unwrap_or(i64::MAX);
2642 let pass = (ticks_at(sample, rate) - start).div_euclid(period);
2643 let Some(pass_start) = pass
2644 .checked_mul(period)
2645 .and_then(|ticks| ticks.checked_add(start))
2646 else {
2647 return false;
2648 };
2649 let pass_end = pass_start.saturating_add(period);
2650 let piece_end = sample_at_or_after(pass_end, rate);
2651 let length = usize::try_from(piece_end.saturating_sub(sample))
2652 .unwrap_or(usize::MAX)
2653 .clamp(1, count - index);
2654 let reversed = mode == LoopMode::PingPong && pass.rem_euclid(2) == 1;
2655 let Some(map) = SourceMap::pass(clip, pass_start, reversed, rate) else {
2656 return false;
2657 };
2658 piece(LoopPiece {
2659 sample,
2660 index,
2661 length,
2662 pass,
2663 pass_start,
2664 pass_end,
2665 piece_end,
2666 map,
2667 });
2668 index += length;
2669 }
2670 true
2671}
2672
2673fn sample_at_or_after(ticks: i64, sample_rate: u32) -> i64 {
2674 let rate = i128::from(sample_rate.max(1));
2675 let numerator = i128::from(ticks) * rate;
2676 let denominator = i128::from(TICKS_PER_SECOND);
2677 let value =
2678 numerator.div_euclid(denominator) + i128::from(numerator.rem_euclid(denominator) != 0);
2679 i64::try_from(value).unwrap_or(i64::MAX)
2680}
2681
2682fn mixed_sample(mix: &ChannelMix, planes: &[Vec<f32>], index: i64) -> f32 {
2683 if let Some(plane) = mix.unity() {
2684 return copied(&planes[plane], index);
2685 }
2686 let mut sum = 0.0;
2687 for &(plane, weight) in mix.terms() {
2688 sum += weight * copied(&planes[plane], index);
2689 }
2690 sum
2691}
2692
2693fn filtered_sample(mix: &ChannelMix, planes: &[Vec<f32>], first: i64, weights: &[f64]) -> f32 {
2695 if let Some(plane) = mix.unity() {
2696 return filtered(&planes[plane], first, weights);
2697 }
2698 let mut sum = 0.0;
2699 for &(plane, weight) in mix.terms() {
2700 sum += weight * filtered(&planes[plane], first, weights);
2701 }
2702 sum
2703}
2704
2705fn copied(plane: &[f32], index: i64) -> f32 {
2708 let value = usize::try_from(index)
2709 .ok()
2710 .and_then(|index| plane.get(index).copied())
2711 .unwrap_or(0.0);
2712 if value.is_finite() { value } else { 0.0 }
2713}
2714
2715fn filtered(plane: &[f32], first: i64, weights: &[f64]) -> f32 {
2717 let mut sum = weighed(plane, first, weights, false);
2718 if !sum.is_finite() {
2719 sum = weighed(plane, first, weights, true);
2720 }
2721 #[allow(clippy::cast_possible_truncation)]
2722 let value = sum as f32;
2723 if value.is_finite() { value } else { 0.0 }
2724}
2725
2726fn weighed(plane: &[f32], first: i64, weights: &[f64], finite_only: bool) -> f64 {
2729 let inside = usize::try_from(first).ok().filter(|&from| {
2730 from.checked_add(weights.len())
2731 .is_some_and(|end| end <= plane.len())
2732 });
2733 let mut sums = [0.0_f64; 4];
2734 match inside {
2735 Some(from) if !finite_only => {
2736 let (weight_quads, weight_rest) = weights.as_chunks::<4>();
2737 let (sample_quads, sample_rest) = plane[from..from + weights.len()].as_chunks::<4>();
2738 for (weight, value) in weight_quads.iter().zip(sample_quads) {
2739 for lane in 0..4 {
2740 sums[lane] += weight[lane] * f64::from(value[lane]);
2741 }
2742 }
2743 for (lane, (weight, value)) in weight_rest.iter().zip(sample_rest).enumerate() {
2744 sums[lane] += weight * f64::from(*value);
2745 }
2746 }
2747 _ => {
2748 for (index, (at, weight)) in (first..).zip(weights).enumerate() {
2749 let value = usize::try_from(at)
2750 .ok()
2751 .and_then(|at| plane.get(at).copied())
2752 .unwrap_or(0.0);
2753 if value.is_finite() {
2754 sums[index % 4] += weight * f64::from(value);
2755 }
2756 }
2757 }
2758 }
2759 (sums[0] + sums[1]) + (sums[2] + sums[3])
2760}
2761
2762struct SourceMap {
2767 a: i128,
2768 b: i128,
2769 d: i128,
2770}
2771
2772impl SourceMap {
2773 fn stretched(clip: &ActiveAudioClip, reversed: bool, rate: u32) -> Option<Self> {
2776 let timeline = clip.timeline_range;
2777 let forward = Self::line(
2778 i128::from(timeline.start().ticks()),
2779 i128::from(clip.source_range.start().ticks()),
2780 i128::from(timeline.duration()?.ticks()),
2781 i128::from(clip.source_range.duration()?.ticks()),
2782 rate,
2783 )?;
2784 if !reversed {
2785 return Some(forward);
2786 }
2787 forward.mirrored(
2788 sample_at_or_after(timeline.start().ticks(), rate),
2789 sample_at_or_after(timeline.end().ticks(), rate),
2790 )
2791 }
2792
2793 fn pass(clip: &ActiveAudioClip, pass_start: i64, reversed: bool, rate: u32) -> Option<Self> {
2795 let period = clip.source_range.duration()?.ticks();
2796 let forward = Self::line(
2797 i128::from(pass_start),
2798 i128::from(clip.source_range.start().ticks()),
2799 i128::from(period),
2800 i128::from(period),
2801 rate,
2802 )?;
2803 if !reversed {
2804 return Some(forward);
2805 }
2806 forward.mirrored(
2807 sample_at_or_after(pass_start, rate),
2808 sample_at_or_after(pass_start.checked_add(period)?, rate),
2809 )
2810 }
2811
2812 fn mirrored(&self, first: i64, last: i64) -> Option<Self> {
2814 let pivot = i128::from(first)
2815 .checked_add(i128::from(last))?
2816 .checked_sub(1)?;
2817 Some(Self {
2818 a: self.a.checked_add(pivot.checked_mul(self.b)?)?,
2819 b: self.b.checked_neg()?,
2820 d: self.d,
2821 })
2822 }
2823
2824 fn line(t0: i128, s0: i128, timeline: i128, source: i128, rate: u32) -> Option<Self> {
2827 if timeline <= 0 || source == 0 {
2828 return None;
2829 }
2830 let divisor = gcd(timeline, source);
2831 let (timeline, source) = (timeline / divisor, source / divisor);
2832 let rate = i128::from(rate);
2833 let ticks = i128::from(TICKS_PER_SECOND);
2834 let a = rate.checked_mul(
2836 s0.checked_mul(timeline)?
2837 .checked_sub(t0.checked_mul(source)?)?,
2838 )?;
2839 let b = ticks.checked_mul(source)?;
2840 let d = ticks.checked_mul(timeline)?;
2841 Some(Self { a, b, d })
2842 }
2843
2844 fn position(&self, sample: i64) -> Option<(i64, f64)> {
2846 let numerator = self
2847 .a
2848 .checked_add(i128::from(sample).checked_mul(self.b)?)?;
2849 let whole = i64::try_from(numerator.div_euclid(self.d)).ok()?;
2850 let remainder = numerator.rem_euclid(self.d);
2851 #[allow(clippy::cast_precision_loss)]
2852 let fraction = remainder as f64 / self.d as f64;
2853 Some((whole, fraction))
2854 }
2855
2856 fn interpolator(&self) -> Option<Interpolator> {
2858 if self.b.unsigned_abs() == self.d.unsigned_abs() && self.a.rem_euclid(self.d) == 0 {
2859 return None;
2860 }
2861 #[allow(clippy::cast_precision_loss)]
2862 let speed = self.b.unsigned_abs() as f64 / self.d.unsigned_abs() as f64;
2863 Some(Interpolator::new(speed))
2864 }
2865
2866 fn request(&self, first_sample: i64, count: usize) -> Option<(i64, i64)> {
2869 let last_sample = first_sample.checked_add(i64::try_from(count).ok()?.checked_sub(1)?)?;
2870 let (first, _) = self.position(first_sample)?;
2871 let (last, _) = self.position(last_sample)?;
2872 let (low, high) = (first.min(last), first.max(last));
2873 let Some(interpolator) = self.interpolator() else {
2874 return Some((low.max(0), high.saturating_add(1)));
2875 };
2876 let half = interpolator.half_taps();
2877 Some((
2878 low.saturating_sub(half - 1).max(0),
2879 high.saturating_add(half + 1),
2880 ))
2881 }
2882
2883 fn cursor(&self, sample: i64) -> Option<RationalCursor> {
2885 let numerator = self
2886 .a
2887 .checked_add(i128::from(sample).checked_mul(self.b)?)?;
2888 RationalCursor::new(numerator, self.b, self.d)
2889 }
2890
2891 fn fraction(&self, cursor: &RationalCursor) -> (i64, f64) {
2893 #[allow(clippy::cast_precision_loss)]
2895 let fraction = cursor.remainder as f64 / self.d as f64;
2896 (cursor.whole, fraction)
2897 }
2898}
2899
2900#[derive(Clone, Copy, Debug)]
2903struct RationalCursor {
2904 whole: i64,
2905 remainder: u64,
2906 step_whole: i64,
2907 step_remainder: u64,
2908 divisor: u64,
2909}
2910
2911impl RationalCursor {
2912 fn new(numerator: i128, step: i128, divisor: i128) -> Option<Self> {
2913 if divisor <= 0 || divisor > i128::from(i64::MAX) {
2915 return None;
2916 }
2917 Some(Self {
2918 whole: i64::try_from(numerator.div_euclid(divisor)).ok()?,
2919 remainder: u64::try_from(numerator.rem_euclid(divisor)).ok()?,
2920 step_whole: i64::try_from(step.div_euclid(divisor)).ok()?,
2921 step_remainder: u64::try_from(step.rem_euclid(divisor)).ok()?,
2922 divisor: u64::try_from(divisor).ok()?,
2923 })
2924 }
2925
2926 const fn period(&self) -> u64 {
2928 let (mut a, mut b) = (self.step_remainder, self.divisor);
2929 while b != 0 {
2930 (a, b) = (b, a % b);
2931 }
2932 self.divisor / a
2933 }
2934
2935 fn advance(&mut self) {
2936 self.whole = self.whole.wrapping_add(self.step_whole);
2937 self.remainder += self.step_remainder;
2938 if self.remainder >= self.divisor {
2939 self.remainder -= self.divisor;
2940 self.whole = self.whole.wrapping_add(1);
2941 }
2942 }
2943}
2944
2945fn tick_cursor(sample: i64, sample_rate: u32) -> RationalCursor {
2947 let ticks = i128::from(TICKS_PER_SECOND);
2948 RationalCursor::new(
2949 i128::from(sample) * ticks,
2950 ticks,
2951 i128::from(sample_rate.max(1)),
2952 )
2953 .unwrap_or(RationalCursor {
2955 whole: i64::MAX,
2956 remainder: 0,
2957 step_whole: 0,
2958 step_remainder: 0,
2959 divisor: 1,
2960 })
2961}
2962
2963fn gcd(mut a: i128, mut b: i128) -> i128 {
2964 while b != 0 {
2965 (a, b) = (b, a % b);
2966 }
2967 a.abs().max(1)
2968}
2969
2970const ENVELOPE_INTERVAL: i64 = 32;
2975
2976fn fill_envelope<const N: usize>(
2982 envelope: &mut [Vec<f32>],
2983 first: i64,
2984 count: usize,
2985 sample_rate: u32,
2986 next_knot: impl Fn(i64) -> Option<i64>,
2987 at: impl Fn(MediaTime) -> [f32; N],
2988) {
2989 #[allow(clippy::cast_precision_loss)]
2990 let fraction = 1.0 / ENVELOPE_INTERVAL as f32;
2991 let mut knot: Option<Option<i64>> = None;
2993 let mut point: Option<(i64, [f32; N])> = None;
2994 let mut written = 0;
2995 while written < count {
2996 let sample = first.saturating_add(i64::try_from(written).unwrap_or(i64::MAX));
2997 let start = sample.div_euclid(ENVELOPE_INTERVAL) * ENVELOPE_INTERVAL;
2998 let stop = start.saturating_add(ENVELOPE_INTERVAL);
2999 let run = usize::try_from(stop - sample)
3000 .unwrap_or(count)
3001 .clamp(1, count - written);
3002 let (from, to) = (ticks_at(start, sample_rate), ticks_at(stop, sample_rate));
3003 let next = match knot {
3004 Some(next) if next.is_none_or(|next| next > from) => next,
3005 _ => next_knot(from),
3006 };
3007 knot = Some(next);
3008 let outputs = written..written + run;
3009 if next.is_some_and(|next| next <= to) {
3010 let mut ticks = tick_cursor(sample, sample_rate);
3011 for index in outputs {
3012 let value = at(MediaTime::from_ticks(ticks.whole));
3013 ticks.advance();
3014 for (plane, value) in envelope.iter_mut().zip(value) {
3015 plane[index] = value;
3016 }
3017 }
3018 #[cfg(test)]
3019 ENVELOPE_POINTS.set(ENVELOPE_POINTS.get() + run);
3020 } else {
3021 let left = match point {
3022 Some((at_sample, value)) if at_sample == start => value,
3023 _ => {
3024 #[cfg(test)]
3025 ENVELOPE_POINTS.set(ENVELOPE_POINTS.get() + 1);
3026 at(MediaTime::from_ticks(from))
3027 }
3028 };
3029 let right = at(MediaTime::from_ticks(to));
3030 #[cfg(test)]
3031 ENVELOPE_POINTS.set(ENVELOPE_POINTS.get() + 1);
3032 point = Some((stop, right));
3033 #[allow(clippy::cast_precision_loss)]
3034 let along = (sample - start) as f32;
3035 for (plane, (left, right)) in envelope.iter_mut().zip(left.into_iter().zip(right)) {
3036 let slope = right - left;
3037 for (position, output) in plane[outputs.clone()].iter_mut().enumerate() {
3038 #[allow(clippy::cast_precision_loss)]
3039 let position = along + position as f32;
3040 *output = left + slope * (position * fraction);
3041 }
3042 }
3043 }
3044 written += run;
3045 }
3046}
3047
3048#[cfg(test)]
3049thread_local! {
3050 static ENVELOPE_POINTS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3052 static LANES_FILLED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3053 static BUS_PLANES_CLEARED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3055 static BUS_PLANES_SUMMED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
3056}
3057
3058fn earliest(left: Option<i64>, right: Option<i64>) -> Option<i64> {
3060 match (left, right) {
3061 (Some(left), Some(right)) => Some(left.min(right)),
3062 (left, right) => left.or(right),
3063 }
3064}
3065
3066fn next_fade_edge(clip: &ActiveAudioClip, ticks: i64) -> Option<i64> {
3068 let start = clip.timeline_range.start().ticks();
3069 let end = clip.timeline_range.end().ticks();
3070 let fade_in = clip.audio.fade_in.ticks();
3071 let fade_out = clip.audio.fade_out.ticks();
3072 let mut next = None;
3073 if fade_in > 0 {
3074 for edge in [start, start.saturating_add(fade_in)] {
3075 if edge > ticks {
3076 next = earliest(next, Some(edge));
3077 }
3078 }
3079 }
3080 if fade_out > 0 {
3081 for edge in [end.saturating_sub(fade_out), end] {
3082 if edge > ticks {
3083 next = earliest(next, Some(edge));
3084 }
3085 }
3086 }
3087 next
3088}
3089
3090fn constant_value(animation: &Animated<f32>) -> Option<f32> {
3092 match animation {
3093 Animated::Constant { value } => Some(*value),
3094 Animated::Data(_) | Animated::Split { .. } => None,
3095 Animated::Keyframes { keyframes, .. } => match keyframes.as_slice() {
3096 [only] => Some(only.value),
3097 _ => None,
3098 },
3099 }
3100}
3101
3102fn fades_reach(clip: &ActiveAudioClip, first: i64, count: usize, sample_rate: u32) -> bool {
3105 let fade_in = clip.audio.fade_in.ticks();
3106 let fade_out = clip.audio.fade_out.ticks();
3107 if fade_in <= 0 && fade_out <= 0 {
3108 return false;
3109 }
3110 let last = first.saturating_add(i64::try_from(count).unwrap_or(i64::MAX).saturating_sub(1));
3111 let elapsed = ticks_at(first, sample_rate).saturating_sub(clip.timeline_range.start().ticks());
3113 let remaining = clip
3114 .timeline_range
3115 .end()
3116 .ticks()
3117 .saturating_sub(ticks_at(last, sample_rate));
3118 (fade_in > 0 && elapsed < fade_in) || (fade_out > 0 && remaining < fade_out)
3119}
3120
3121fn fade_gain(clip: &ActiveAudioClip, time: MediaTime) -> f32 {
3123 let start = clip.timeline_range.start().ticks();
3124 let end = clip.timeline_range.end().ticks();
3125 let mut gain = 1.0_f32;
3126 let fade_in = clip.audio.fade_in.ticks();
3127 if fade_in > 0 {
3128 let elapsed = time.ticks().saturating_sub(start);
3129 if elapsed < fade_in {
3130 gain *= clip.audio.fade_in_shape.amplitude(ratio(elapsed, fade_in));
3131 }
3132 }
3133 let fade_out = clip.audio.fade_out.ticks();
3134 if fade_out > 0 {
3135 let remaining = end.saturating_sub(time.ticks());
3136 if remaining < fade_out {
3137 gain *= clip
3138 .audio
3139 .fade_out_shape
3140 .amplitude(ratio(remaining, fade_out));
3141 }
3142 }
3143 gain.clamp(0.0, 1.0)
3144}
3145
3146#[allow(clippy::cast_precision_loss)]
3147fn ratio(value: i64, span: i64) -> f32 {
3148 if span <= 0 {
3149 return 1.0;
3150 }
3151 (value.max(0) as f32 / span as f32).clamp(0.0, 1.0)
3152}
3153
3154fn pan_gains(pan: f32, channels: usize) -> [f32; 2] {
3158 if channels < 2 {
3159 return [1.0, 1.0];
3160 }
3161 let angle = (f64::from(pan.clamp(-1.0, 1.0)) + 1.0) * core::f64::consts::FRAC_PI_4;
3163 let normalize = core::f64::consts::SQRT_2;
3164 #[allow(clippy::cast_possible_truncation)]
3165 let weights = [
3166 (libm::cos(angle) * normalize) as f32,
3167 (libm::sin(angle) * normalize) as f32,
3168 ];
3169 weights
3170}
3171
3172#[cfg(test)]
3173mod tests;