1use std::collections::HashMap;
17
18use alpha2_audio::{
19 Biquad, BiquadKind, ChannelLayout, Compressor, Ducker, Interpolator, LoudnessMeter,
20 LoudnessReport, PeakLimiter, ProcessCtx, Processor, ProcessorChain, SchroederReverb, Stretch,
21 TransportState,
22};
23use alpha2_eval::{ActiveAudioClip, AudioSpanScratch, SampleContext, sample_scalar};
24use alpha2_media::{AudioBlock, AudioBlockProvider, SourceId, SpeakerLayout};
25use alpha2_model::{
26 Animated, AudioEffect, ClipId, EqBandKind, LOOP_FADE_SECONDS, LoopMode, MAX_GAIN, MasterAudio,
27 TimeMap, TrackAudio, TrackId,
28};
29use alpha2_time::{MediaTime, TICKS_PER_SECOND, TimeRange};
30
31use crate::downmix::{ChannelMix, Downmix};
32use crate::{EngineError, EngineProject};
33
34mod stretch_read;
35
36use stretch_read::{StretchSlot, stretched_request, stretches};
37
38const MAX_CACHED_WEIGHTS: usize = 1 << 15;
40
41pub const MAX_AUDIO_BLOCK: usize = 8_192;
43
44const _: () = {
47 let rate = *alpha2_model::SAMPLE_RATE_RANGE.start() as usize;
48 let samples = MAX_AUDIO_BLOCK + 2 + alpha2_model::MAX_CHAIN_EFFECTS;
49 assert!(
50 samples * 1_000 <= alpha2_model::AUDIO_EFFECT_STATE_MARGIN_MS as usize * rate,
51 "AUDIO_EFFECT_STATE_MARGIN_MS must hold a largest block at the lowest rate"
52 );
53};
54
55pub const MAX_SETTLING_SECONDS: u32 = 30;
61
62#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
65pub enum AudioContinuity {
66 #[default]
70 Exact,
71 ContinueSmallGaps,
77}
78
79#[derive(Clone, Debug, PartialEq, Eq)]
81pub struct AudioRenderStatus {
82 pub start_sample: i64,
84 pub frames: usize,
86 pub missing_sources: Vec<SourceId>,
93}
94
95impl AudioRenderStatus {
96 #[must_use]
98 pub fn is_complete(&self) -> bool {
99 self.missing_sources.is_empty()
100 }
101}
102
103#[derive(Clone, Debug, PartialEq, Eq)]
105pub struct AudioNeed {
106 pub source_id: SourceId,
108 pub stream: Option<u32>,
111 pub source_range: TimeRange,
113}
114
115struct TrackBus {
116 id: TrackId,
117 audio: TrackAudio,
118 chain: ProcessorChain,
119 ducker: Option<BusDucker>,
120 sidechain: Option<usize>,
121 output: [Vec<f32>; 2],
123 live: bool,
126 latency: i64,
128 clips: Vec<ClipSlot>,
130 chain_lead: i64,
132 ducker_lead: i64,
134 read: bool,
136}
137
138impl TrackBus {
139 fn active_sidechain(&self, index: usize) -> Option<usize> {
141 self.ducker.as_ref()?;
142 self.sidechain.filter(|&sidechain| sidechain != index)
143 }
144
145 fn make_live(&mut self, channels: usize, frames: usize) {
147 if self.live {
148 return;
149 }
150 for plane in self.output.iter_mut().take(channels) {
151 plane[..frames].fill(0.0);
152 }
153 self.live = true;
154 #[cfg(test)]
155 BUS_PLANES_CLEARED.set(BUS_PLANES_CLEARED.get() + channels);
156 }
157}
158
159struct BusDucker {
161 ducker: Ducker,
162 output: [Vec<f32>; 2],
163}
164
165struct ClipSlot {
166 id: ClipId,
167 chain: Option<ClipChain>,
168}
169
170struct ClipChain {
176 effects: Vec<AudioEffect>,
177 chain: Option<ProcessorChain>,
178 ran_in: u64,
180 latency: i64,
182 history: u32,
184 next_input: Option<i64>,
186 lead: i64,
188}
189
190pub struct AudioRenderer {
192 layout: ChannelLayout,
193 sample_rate: u32,
194 max_block: usize,
195 buses: Vec<TrackBus>,
197 bus_of_track: HashMap<TrackId, usize>,
199 slot_of_clip: HashMap<ClipId, (usize, usize)>,
201 span_scratch: AudioSpanScratch,
202 master_chain: ProcessorChain,
203 master_latency: i64,
205 lookahead: i64,
207 history: i64,
209 master_lead: i64,
211 limiter_lead: i64,
213 stage_leads: Vec<i64>,
216 master: MasterAudio,
217 limiter: Option<PeakLimiter>,
218 normalization_gain: f32,
220 hold_incomplete: bool,
221 continuity: AudioContinuity,
222 meter: Option<LoudnessMeter>,
224 output_meter: Option<LoudnessMeter>,
226 any_solo: bool,
227 clip_a: [Vec<f32>; 2],
228 clip_b: [Vec<f32>; 2],
229 bus_in: [Vec<f32>; 2],
230 mix: [Vec<f32>; 2],
231 output: [Vec<f32>; 2],
232 envelope: [Vec<f32>; 3],
234 next_sample: Option<i64>,
236 live_chains: Vec<(usize, usize)>,
238 blocks_mixed: u64,
239 weights: Vec<f64>,
241 phase_weights: Vec<f64>,
243 stretch: Stretch,
245 stretch_slots: HashMap<ClipId, StretchSlot>,
246 #[cfg(test)]
248 most_held: (usize, u64),
249 #[cfg(test)]
251 samples_read: usize,
252}
253
254#[derive(Clone, Copy, Debug, PartialEq, Eq)]
256enum Fill {
257 Samples,
259 Presence,
261}
262
263impl AudioRenderer {
264 pub fn new(
271 snapshot: &EngineProject,
272 channels: usize,
273 max_block: usize,
274 ) -> Result<Self, EngineError> {
275 let layout =
276 ChannelLayout::from_channels(channels).ok_or(EngineError::InvalidAudioConfiguration)?;
277 let project = snapshot.project();
278 let sample_rate = project.settings.sample_rate;
279 if sample_rate == 0 || max_block == 0 || max_block > MAX_AUDIO_BLOCK {
280 return Err(EngineError::InvalidAudioConfiguration);
281 }
282
283 let (mut buses, bus_of_track) = track_buses(project, layout, sample_rate, max_block);
284 resolve_sidechains(&mut buses, &bus_of_track);
285 let slot_of_clip = buses
286 .iter()
287 .enumerate()
288 .flat_map(|(bus, track)| {
289 track
290 .clips
291 .iter()
292 .enumerate()
293 .map(move |(position, slot)| (slot.id.clone(), (bus, position)))
294 })
295 .collect();
296
297 let mut master_chain = ProcessorChain::new(layout);
298 push_effects(&mut master_chain, &project.audio.effects);
299 master_chain.prepare(sample_rate, max_block);
300 let limiter = project.audio.limiter.map(|limiter| {
301 let mut peak = PeakLimiter::new(limiter.threshold, limiter.release_ms);
302 peak.prepare(sample_rate, max_block);
303 peak
304 });
305 let any_solo = project.timeline.any_solo();
306 read_buses(&mut buses, any_solo);
307 let master_latency = i64::from(master_chain.latency_samples());
308 let lookahead = master_latency + longest_path_latency(&buses);
309 let settling = Settling(i64::from(sample_rate) * i64::from(MAX_SETTLING_SECONDS));
310 let limiter_lead = settling.lead(0, limiter.as_ref().map_or(0, Processor::history_samples));
311 let master_lead = settling.lead(limiter_lead, master_chain.history_samples());
312 let history = assign_leads(&mut buses, master_lead, settling).max(master_lead);
313 let stage_leads = stage_leads(&buses, master_lead, limiter_lead);
314
315 Ok(Self {
316 layout,
317 sample_rate,
318 max_block,
319 buses,
320 bus_of_track,
321 slot_of_clip,
322 span_scratch: AudioSpanScratch::default(),
323 master_chain,
324 master_latency,
325 lookahead,
326 history,
327 master_lead,
328 limiter_lead,
329 stage_leads,
330 master: project.audio.clone(),
331 limiter,
332 normalization_gain: 1.0,
333 hold_incomplete: false,
334 continuity: AudioContinuity::Exact,
335 meter: None,
336 output_meter: None,
337 any_solo,
338 clip_a: buffers(max_block),
339 clip_b: buffers(max_block),
340 bus_in: buffers(max_block),
341 mix: buffers(max_block),
342 output: buffers(max_block),
343 envelope: [
344 vec![0.0; max_block],
345 vec![0.0; max_block],
346 vec![0.0; max_block],
347 ],
348 next_sample: None,
349 live_chains: Vec::new(),
350 blocks_mixed: 0,
351 weights: Vec::new(),
352 phase_weights: Vec::new(),
353 stretch: Stretch::new(sample_rate),
354 stretch_slots: HashMap::new(),
355 #[cfg(test)]
356 most_held: (0, 0),
357 #[cfg(test)]
358 samples_read: 0,
359 })
360 }
361
362 #[must_use]
364 pub const fn sample_rate(&self) -> u32 {
365 self.sample_rate
366 }
367
368 #[must_use]
370 pub const fn channels(&self) -> usize {
371 self.layout.channels()
372 }
373
374 #[must_use]
376 pub fn track_ids(&self) -> Vec<&TrackId> {
377 self.buses.iter().map(|bus| &bus.id).collect()
378 }
379
380 #[must_use]
382 pub const fn max_block(&self) -> usize {
383 self.max_block
384 }
385
386 #[must_use]
388 pub fn channel(&self, index: usize) -> &[f32] {
389 self.output.get(index).map_or(&[], Vec::as_slice)
390 }
391
392 #[must_use]
398 pub fn required_lookahead_samples(&self) -> u32 {
399 u32::try_from(self.lookahead).unwrap_or(u32::MAX)
400 }
401
402 pub fn audio_needs(
414 &self,
415 snapshot: &EngineProject,
416 start_sample: i64,
417 frames: usize,
418 ) -> Result<Vec<AudioNeed>, EngineError> {
419 self.check_block(start_sample, frames)?;
420 let mut needs = Vec::new();
421 let mut scratch = AudioSpanScratch::default();
422 if self.continues_at(start_sample).is_none() {
423 let mut position = self.preroll_start(start_sample)?;
424 while position < start_sample {
425 let count = self.replay_frames(position, start_sample);
426 self.block_needs(
427 snapshot,
428 position,
429 count,
430 Some(start_sample),
431 &mut scratch,
432 &mut needs,
433 )?;
434 position += i64::try_from(count).unwrap_or(i64::MAX);
435 }
436 }
437 self.block_needs(
438 snapshot,
439 start_sample,
440 frames,
441 None,
442 &mut scratch,
443 &mut needs,
444 )?;
445 Ok(needs)
446 }
447
448 fn block_needs(
450 &self,
451 snapshot: &EngineProject,
452 start: i64,
453 frames: usize,
454 replay_target: Option<i64>,
455 scratch: &mut AudioSpanScratch,
456 needs: &mut Vec<AudioNeed>,
457 ) -> Result<(), EngineError> {
458 let frames_i64 = i64::try_from(frames).map_err(|_| EngineError::OutOfRange)?;
459 let stages = Stages {
460 target: replay_target,
461 block_end: start + frames_i64,
462 lookahead: self.lookahead,
463 };
464 let span = self.block_span(start, frames_i64)?;
465 let described = snapshot
466 .evaluate_audio_in(span, scratch)
467 .map_err(EngineError::Evaluate)?;
468 let master_input = start + self.master_latency;
469 let rate = self.sample_rate;
470 for clip in described.iter() {
471 let Some(read) = self.clip_read(&clip, master_input, frames, stages) else {
472 continue;
473 };
474 source_requests(
475 &self.stretch,
476 &clip,
477 read.first,
478 read.window.content,
479 rate,
480 |from, to| {
481 let (Some(start), Some(end)) =
482 (checked_ticks_at(from, rate), ticks_at_or_after(to, rate))
483 else {
484 return;
485 };
486 if let Ok(range) =
487 TimeRange::new(MediaTime::from_ticks(start), MediaTime::from_ticks(end))
488 {
489 merge_need(needs, clip.source_id, clip.audio.stream, range);
490 }
491 },
492 );
493 }
494 Ok(())
495 }
496
497 fn check_block(&self, start_sample: i64, frames: usize) -> Result<(), EngineError> {
498 if start_sample < 0 || frames == 0 || frames > self.max_block {
499 return Err(EngineError::InvalidAudioConfiguration);
500 }
501 i64::try_from(frames)
503 .ok()
504 .and_then(|frames| start_sample.checked_add(frames))
505 .and_then(|end| end.checked_add(self.lookahead))
506 .and_then(|end| checked_ticks_at(end, self.sample_rate))
507 .map(|_| ())
508 .ok_or(EngineError::InvalidAudioConfiguration)
509 }
510
511 #[must_use]
514 pub const fn required_history_samples(&self) -> i64 {
515 self.history
516 }
517
518 fn preroll_start(&self, start: i64) -> Result<i64, EngineError> {
519 if start < 0 {
520 return Err(EngineError::InvalidAudioConfiguration);
521 }
522 let history = if self.continues_at(start).is_some() {
523 0
524 } else {
525 self.history
526 };
527 Ok(start
529 .saturating_sub(history)
530 .max(0)
531 .saturating_sub(self.lookahead))
532 }
533
534 fn replay_frames(&self, position: i64, target: i64) -> usize {
537 let room = i64::try_from(self.max_block).unwrap_or(i64::MAX);
538 let mut end = target.min(position.saturating_add(room));
539 let begun = self
541 .stage_leads
542 .partition_point(|&lead| Stages::start(target, lead, self.lookahead) <= position);
543 if let Some(&lead) = self.stage_leads.get(begun) {
544 end = end.min(Stages::start(target, lead, self.lookahead));
545 }
546 usize::try_from(end - position).unwrap_or(1)
547 }
548
549 fn continues_at(&self, start: i64) -> Option<i64> {
552 let step = start.checked_sub(self.next_sample?)?;
553 let room = i64::try_from(self.max_block).unwrap_or(i64::MAX);
554 let joins = self.continuity == AudioContinuity::ContinueSmallGaps && step.abs() <= room;
555 (step == 0 || joins).then_some(step)
556 }
557
558 fn step_live_chains(&mut self, step: i64) {
561 if step == 0 {
562 return;
563 }
564 for &(bus, position) in &self.live_chains {
565 if let Some(clip) = self.buses[bus].clips[position].chain.as_mut() {
566 clip.next_input = clip.next_input.and_then(|next| next.checked_add(step));
567 }
568 }
569 }
570
571 pub fn set_continuity(&mut self, continuity: AudioContinuity) {
574 if self.continuity != continuity {
575 self.reset();
576 self.continuity = continuity;
577 }
578 }
579
580 #[must_use]
582 pub const fn continuity(&self) -> AudioContinuity {
583 self.continuity
584 }
585
586 pub fn reset(&mut self) {
591 self.next_sample = None;
592 for &(bus, position) in &self.live_chains {
594 if let Some(clip) = self.buses[bus].clips[position].chain.as_mut() {
595 if let Some(chain) = clip.chain.as_mut() {
596 chain.reset();
597 }
598 clip.next_input = None;
599 }
600 }
601 for bus in &mut self.buses {
602 bus.chain.reset();
603 if let Some(ducking) = bus.ducker.as_mut() {
604 ducking.ducker.reset();
605 }
606 }
607 self.master_chain.reset();
608 if let Some(limiter) = self.limiter.as_mut() {
609 limiter.reset();
610 }
611 }
612
613 pub fn render(
629 &mut self,
630 snapshot: &EngineProject,
631 start_sample: i64,
632 frames: usize,
633 provider: &dyn AudioBlockProvider,
634 transport: TransportState,
635 ) -> Result<AudioRenderStatus, EngineError> {
636 self.check_block(start_sample, frames)?;
637 let end_sample = start_sample + i64::try_from(frames).unwrap_or(i64::MAX);
638 if self.hold_incomplete {
639 let missing_sources = self.unready_sources(snapshot, start_sample, frames, provider)?;
640 if !missing_sources.is_empty() {
641 for channel in 0..self.layout.channels() {
642 self.output[channel][..frames].fill(0.0);
643 }
644 return Ok(AudioRenderStatus {
645 start_sample,
646 frames,
647 missing_sources,
648 });
649 }
650 }
651 let mut missing_sources: Vec<SourceId> = Vec::new();
652 if let Some(step) = self.continues_at(start_sample) {
653 self.step_live_chains(step);
654 } else {
655 let mut position = self.preroll_start(start_sample)?;
656 self.reset();
657 while position < start_sample {
658 let count = self.replay_frames(position, start_sample);
659 self.mix_block(
660 snapshot,
661 position,
662 count,
663 provider,
664 transport,
665 Some(start_sample),
666 &mut missing_sources,
667 )?;
668 position += i64::try_from(count).unwrap_or(i64::MAX);
669 }
670 }
671 self.mix_block(
672 snapshot,
673 start_sample,
674 frames,
675 provider,
676 transport,
677 None,
678 &mut missing_sources,
679 )?;
680 self.next_sample = Some(end_sample);
681
682 Ok(AudioRenderStatus {
683 start_sample,
684 frames,
685 missing_sources,
686 })
687 }
688
689 fn unready_sources(
692 &mut self,
693 snapshot: &EngineProject,
694 start_sample: i64,
695 frames: usize,
696 provider: &dyn AudioBlockProvider,
697 ) -> Result<Vec<SourceId>, EngineError> {
698 let mut missing = Vec::new();
699 let mut position = if self.continues_at(start_sample).is_some() {
700 start_sample
701 } else {
702 self.preroll_start(start_sample)?
703 };
704 while position < start_sample {
705 let count = self.replay_frames(position, start_sample);
706 self.read_block(
707 snapshot,
708 position,
709 count,
710 provider,
711 Some(start_sample),
712 &mut missing,
713 )?;
714 position += i64::try_from(count).unwrap_or(i64::MAX);
715 }
716 self.read_block(snapshot, start_sample, frames, provider, None, &mut missing)?;
717 Ok(missing)
718 }
719
720 fn read_block(
722 &mut self,
723 snapshot: &EngineProject,
724 start: i64,
725 frames: usize,
726 provider: &dyn AudioBlockProvider,
727 replay_target: Option<i64>,
728 missing: &mut Vec<SourceId>,
729 ) -> Result<(), EngineError> {
730 let frames_i64 = i64::try_from(frames).map_err(|_| EngineError::OutOfRange)?;
731 let stages = Stages {
732 target: replay_target,
733 block_end: start + frames_i64,
734 lookahead: self.lookahead,
735 };
736 let span = self.block_span(start, frames_i64)?;
737 let mut scratch = std::mem::take(&mut self.span_scratch);
738 let described = match snapshot.evaluate_audio_in(span, &mut scratch) {
739 Ok(described) => described,
740 Err(error) => {
741 self.span_scratch = scratch;
742 return Err(EngineError::Evaluate(error));
743 }
744 };
745 let master_input = start + self.master_latency;
746 for clip in described.iter() {
747 let Some(read) = self.clip_read(&clip, master_input, frames, stages) else {
748 continue;
749 };
750 let window = read.window;
751 let complete = self.fill_clip(
752 &clip,
753 read.first,
754 window.count,
755 window.content,
756 provider,
757 Fill::Presence,
758 );
759 if !complete && !missing.contains(clip.source_id) {
760 missing.push(clip.source_id.clone());
761 }
762 }
763 self.span_scratch = scratch;
764 Ok(())
765 }
766
767 #[allow(clippy::too_many_arguments)]
774 fn mix_block(
775 &mut self,
776 snapshot: &EngineProject,
777 start: i64,
778 frames: usize,
779 provider: &dyn AudioBlockProvider,
780 transport: TransportState,
781 replay_target: Option<i64>,
782 missing_sources: &mut Vec<SourceId>,
783 ) -> Result<(), EngineError> {
784 let channels = self.layout.channels();
785 let context = snapshot.sample_context();
786 let frames_i64 = i64::try_from(frames).map_err(|_| EngineError::OutOfRange)?;
787 let stages = Stages {
788 target: replay_target,
789 block_end: start + frames_i64,
790 lookahead: self.lookahead,
791 };
792 let span = self.block_span(start, frames_i64)?;
793 let mut scratch = std::mem::take(&mut self.span_scratch);
795 let described = match snapshot.evaluate_audio_in(span, &mut scratch) {
796 Ok(described) => described,
797 Err(error) => {
798 self.span_scratch = scratch;
799 return Err(EngineError::Evaluate(error));
800 }
801 };
802
803 for channel in 0..channels {
804 self.mix[channel][..frames].fill(0.0);
805 }
806 for bus in &mut self.buses {
807 bus.live = false;
808 }
809
810 let master_input = start + self.master_latency;
811 self.keep_mixed_chains(&described, master_input, frames, stages);
812 let mut complete_block = true;
813 for clip in described.iter() {
814 let clip = &clip;
815 let Some(read) = self.clip_read(clip, master_input, frames, stages) else {
816 continue;
817 };
818 let window = read.window;
819 let complete = self.fill_clip(
820 clip,
821 read.first,
822 window.count,
823 window.content,
824 provider,
825 Fill::Samples,
826 );
827 complete_block &= complete;
828 if !complete && !missing_sources.contains(clip.source_id) {
829 missing_sources.push(clip.source_id.clone());
830 }
831 if let Some(slot) = read.slot {
832 self.apply_clip_chain(slot, read.first, transport, window.count);
833 }
834 self.mix_clip_into_bus(
835 clip,
836 read.bus,
837 read.bus_input,
838 window.offset,
839 window.count,
840 frames,
841 &context,
842 );
843 }
844 self.span_scratch = scratch;
845 let block = self.blocks_mixed;
847 self.stretch_slots.retain(|_, slot| slot.used_in == block);
848
849 self.process_buses(master_input, transport, frames, stages);
850 self.apply_ducking(&self.ctx(master_input, transport), frames, stages);
851 if stages.run(self.master_lead) {
852 self.sum_buses(master_input, frames, &context);
853 self.finish_master(
854 start,
855 master_input,
856 transport,
857 frames,
858 stages,
859 complete_block,
860 &context,
861 );
862 }
863 self.blocks_mixed += 1;
864 Ok(())
865 }
866
867 fn keep_mixed_chains(
871 &mut self,
872 described: &alpha2_eval::AudioSpan<'_, '_>,
873 master_input: i64,
874 frames: usize,
875 stages: Stages,
876 ) {
877 let block = self.blocks_mixed;
878 for clip in described.iter() {
879 let Some((bus, position)) = self
880 .clip_read(&clip, master_input, frames, stages)
881 .and_then(|read| read.slot)
882 else {
883 continue;
884 };
885 if let Some(chain) = self.buses[bus].clips[position].chain.as_mut() {
886 chain.ran_in = block;
887 }
888 }
889 let buses = &mut self.buses;
890 self.live_chains.retain(|&(bus, position)| {
891 let Some(clip) = buses[bus].clips[position].chain.as_mut() else {
892 return false;
893 };
894 if clip.ran_in == block {
895 return true;
896 }
897 clip.chain = None;
898 clip.next_input = None;
899 false
900 });
901 }
902
903 fn ctx(&self, sample: i64, transport: TransportState) -> ProcessCtx {
904 ProcessCtx {
905 position: MediaTime::from_ticks(ticks_at(sample, self.sample_rate)),
906 sample_position: sample,
907 sample_rate: self.sample_rate,
908 transport,
909 }
910 }
911
912 pub fn set_normalization_gain_db(&mut self, gain_db: f64) -> Result<(), EngineError> {
919 #[allow(clippy::cast_possible_truncation)]
920 let gain = libm::pow(10.0, gain_db / 20.0) as f32;
921 if !gain_db.is_finite() || !gain.is_normal() {
922 return Err(EngineError::InvalidNormalizationGain);
923 }
924 self.normalization_gain = gain;
925 Ok(())
926 }
927
928 pub const fn set_hold_incomplete_blocks(&mut self, hold: bool) {
932 self.hold_incomplete = hold;
933 }
934
935 pub fn set_loudness_metering(&mut self, enabled: bool) -> Result<(), EngineError> {
944 if enabled {
945 self.normalization_gain = 1.0;
946 }
947 self.meter = if enabled {
948 Some(
949 LoudnessMeter::new(self.sample_rate, self.layout.channels())
950 .map_err(|_| EngineError::InvalidAudioConfiguration)?,
951 )
952 } else {
953 None
954 };
955 Ok(())
956 }
957
958 #[must_use]
960 pub fn loudness_report(&self) -> Option<LoudnessReport> {
961 self.meter.as_ref().map(LoudnessMeter::report)
962 }
963
964 #[must_use]
967 pub fn limiter_threshold(&self) -> Option<f64> {
968 self.master
969 .limiter
970 .map(|limiter| f64::from(limiter.threshold))
971 }
972
973 pub fn set_output_loudness_metering(&mut self, enabled: bool) -> Result<(), EngineError> {
980 self.output_meter = if enabled {
981 Some(
982 LoudnessMeter::new(self.sample_rate, self.layout.channels())
983 .map_err(|_| EngineError::InvalidAudioConfiguration)?,
984 )
985 } else {
986 None
987 };
988 Ok(())
989 }
990
991 #[must_use]
993 pub fn output_loudness_report(&self) -> Option<LoudnessReport> {
994 self.output_meter.as_ref().map(LoudnessMeter::report)
995 }
996
997 #[must_use]
999 pub fn block(&self, status: &AudioRenderStatus) -> AudioBlock {
1000 AudioBlock {
1001 start_sample: status.start_sample,
1002 sample_rate: self.sample_rate,
1003 speakers: match self.layout {
1004 ChannelLayout::Mono => SpeakerLayout::MONO,
1005 ChannelLayout::Stereo => SpeakerLayout::STEREO,
1006 },
1007 channels: (0..self.layout.channels())
1008 .map(|channel| self.output[channel][..status.frames].to_vec())
1009 .collect(),
1010 }
1011 }
1012
1013 fn bus_of(&self, clip: &ActiveAudioClip) -> Option<usize> {
1015 match self.buses.get(clip.track_order) {
1016 Some(bus) if bus.id == *clip.track_id => Some(clip.track_order),
1017 _ => self.bus_of_track.get(clip.track_id).copied(),
1018 }
1019 }
1020
1021 fn slot_of(&self, clip: &ActiveAudioClip) -> Option<(usize, usize)> {
1023 let slot = (clip.track_order, clip.clip_order);
1024 let matches = self
1025 .buses
1026 .get(slot.0)
1027 .and_then(|bus| bus.clips.get(slot.1))
1028 .is_some_and(|found| found.id == *clip.clip_id);
1029 if matches {
1030 Some(slot)
1031 } else {
1032 self.slot_of_clip.get(clip.clip_id).copied()
1033 }
1034 }
1035
1036 fn clip_chain(&self, (bus, position): (usize, usize)) -> Option<&ClipChain> {
1037 self.buses[bus].clips[position].chain.as_ref()
1038 }
1039
1040 fn is_silent_bus(&self, index: usize) -> bool {
1042 self.buses[index].audio.is_silenced(self.any_solo)
1043 }
1044
1045 fn block_span(&self, start: i64, frames: i64) -> Result<TimeRange, EngineError> {
1048 let invalid = EngineError::InvalidAudioConfiguration;
1049 let span_end = start
1050 .checked_add(frames)
1051 .and_then(|end| end.checked_add(self.lookahead))
1052 .ok_or(invalid.clone())?;
1053 let start_ticks = checked_ticks_at(start, self.sample_rate).ok_or(invalid.clone())?;
1054 let end_ticks = checked_ticks_at(span_end, self.sample_rate)
1055 .zip(start_ticks.checked_add(1))
1056 .map(|(end, after_start)| end.max(after_start))
1057 .ok_or(invalid.clone())?;
1058 TimeRange::new(
1059 MediaTime::from_ticks(start_ticks),
1060 MediaTime::from_ticks(end_ticks),
1061 )
1062 .map_err(|_| invalid)
1063 }
1064
1065 fn clip_read(
1068 &self,
1069 clip: &ActiveAudioClip,
1070 master_input: i64,
1071 frames: usize,
1072 stages: Stages,
1073 ) -> Option<ClipRead> {
1074 let bus = self.bus_of(clip)?;
1075 if !clip.audio.is_audible() || !self.buses[bus].read {
1076 return None;
1077 }
1078 let bus_input = master_input + self.buses[bus].latency;
1079 let slot = self.slot_of(clip);
1080 let chain = slot.and_then(|slot| self.clip_chain(slot));
1081 let lead = chain.map_or(self.buses[bus].chain_lead, |chain| chain.lead);
1082 if !stages.run(lead) {
1083 return None;
1084 }
1085 let clip_latency = chain.map_or(0, |chain| chain.latency);
1086 let chain_input = bus_input + clip_latency;
1087 let window = self.clip_window(clip, chain_input, frames, clip_latency)?;
1088 Some(ClipRead {
1089 bus,
1090 bus_input,
1091 slot,
1092 first: chain_input + i64::try_from(window.offset).ok()?,
1093 window,
1094 })
1095 }
1096
1097 fn clip_window(
1100 &self,
1101 clip: &ActiveAudioClip,
1102 input: i64,
1103 frames: usize,
1104 latency: i64,
1105 ) -> Option<ClipWindow> {
1106 let first = sample_at_or_after(clip.timeline_range.start().ticks(), self.sample_rate);
1107 let last = sample_at_or_after(clip.timeline_range.end().ticks(), self.sample_rate);
1108 let block_end = input.checked_add(i64::try_from(frames).ok()?)?;
1109 let begin = first.max(input);
1110 let end = last.saturating_add(latency).min(block_end);
1111 if end <= begin {
1112 return None;
1113 }
1114 Some(ClipWindow {
1115 offset: usize::try_from(begin - input).ok()?,
1116 count: usize::try_from(end - begin).ok()?,
1117 content: usize::try_from((last.min(end) - begin).max(0)).ok()?,
1118 })
1119 }
1120
1121 fn fill_clip(
1124 &mut self,
1125 clip: &ActiveAudioClip,
1126 first_sample: i64,
1127 count: usize,
1128 content: usize,
1129 provider: &dyn AudioBlockProvider,
1130 fill: Fill,
1131 ) -> bool {
1132 if fill == Fill::Samples {
1133 for channel in 0..self.layout.channels() {
1134 self.clip_a[channel][..count].fill(0.0);
1135 }
1136 }
1137 let count = content;
1139 if count == 0 {
1140 return true;
1141 }
1142 let rate = self.sample_rate;
1143 match clip.time_map {
1144 TimeMap::Freeze { .. } => true,
1146 TimeMap::Forward | TimeMap::Reverse if stretches(clip) => {
1147 self.read_stretched(clip, first_sample, count, provider, fill)
1148 }
1149 TimeMap::Forward | TimeMap::Reverse => {
1150 let reversed = clip.time_map == TimeMap::Reverse;
1151 SourceMap::stretched(clip, reversed, rate).is_some_and(|map| {
1152 self.read_source(clip, &map, first_sample, 0, count, provider, fill)
1153 })
1154 }
1155 TimeMap::Loop { mode } => {
1156 self.fill_loop(clip, mode, first_sample, count, provider, fill)
1157 }
1158 }
1159 }
1160
1161 fn fill_loop(
1163 &mut self,
1164 clip: &ActiveAudioClip,
1165 mode: LoopMode,
1166 first_sample: i64,
1167 count: usize,
1168 provider: &dyn AudioBlockProvider,
1169 fill: Fill,
1170 ) -> bool {
1171 let rate = self.sample_rate;
1172 let end = clip.timeline_range.end().ticks();
1173 #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
1174 let fade = ((f64::from(rate) * LOOP_FADE_SECONDS).round() as i64).max(1);
1175 let mut complete = true;
1176 let mapped = loop_pieces(clip, mode, first_sample, count, rate, |piece| {
1177 complete &= self.read_source(
1178 clip,
1179 &piece.map,
1180 piece.sample,
1181 piece.index,
1182 piece.length,
1183 provider,
1184 fill,
1185 );
1186 if mode == LoopMode::Repeat && fill == Fill::Samples {
1187 let fade_in = (piece.pass > 0).then(|| sample_at_or_after(piece.pass_start, rate));
1189 let fade_out = (piece.pass_end < end).then_some(piece.piece_end);
1190 self.fade_wraps(
1191 piece.sample,
1192 piece.index,
1193 piece.length,
1194 fade_in,
1195 fade_out,
1196 fade,
1197 );
1198 }
1199 });
1200 mapped && complete
1201 }
1202
1203 fn fade_wraps(
1206 &mut self,
1207 first_sample: i64,
1208 offset: usize,
1209 count: usize,
1210 fade_in: Option<i64>,
1211 fade_out: Option<i64>,
1212 fade: i64,
1213 ) {
1214 #[allow(clippy::cast_precision_loss)]
1215 let fade = fade as f64;
1216 for index in 0..count {
1217 let sample = first_sample + i64::try_from(index).unwrap_or(i64::MAX);
1218 #[allow(clippy::cast_precision_loss)]
1219 let after = fade_in.map_or(f64::INFINITY, |wrap| (sample - wrap) as f64 + 0.5);
1220 #[allow(clippy::cast_precision_loss)]
1221 let before = fade_out.map_or(f64::INFINITY, |wrap| (wrap - sample) as f64 - 0.5);
1222 let distance = after.min(before);
1223 if distance >= fade {
1224 continue;
1225 }
1226 #[allow(clippy::cast_possible_truncation)]
1227 let gain = (distance / fade).clamp(0.0, 1.0) as f32;
1228 for channel in 0..self.layout.channels() {
1229 self.clip_a[channel][offset + index] *= gain;
1230 }
1231 }
1232 }
1233
1234 #[allow(clippy::too_many_arguments)]
1237 fn read_source(
1238 &mut self,
1239 clip: &ActiveAudioClip,
1240 map: &SourceMap,
1241 first_sample: i64,
1242 offset: usize,
1243 count: usize,
1244 provider: &dyn AudioBlockProvider,
1245 fill: Fill,
1246 ) -> bool {
1247 let Some((request_start, request_end)) = map.request(first_sample, count) else {
1249 return false;
1250 };
1251 let request_frames =
1252 usize::try_from(request_end.saturating_sub(request_start)).unwrap_or(0);
1253 let Some(span) = provider.block(
1254 clip.source_id,
1255 clip.audio.stream,
1256 request_start,
1257 request_frames,
1258 ) else {
1259 return false;
1260 };
1261 if !span.covers(request_start, request_end) {
1263 return false;
1264 }
1265 let source = span.block;
1266 if source.sample_rate != self.sample_rate {
1267 return false;
1268 }
1269
1270 let Some(downmix) = clip_downmix(clip, source, self.layout) else {
1271 return false;
1272 };
1273 if fill == Fill::Presence {
1274 return true;
1275 }
1276 #[cfg(test)]
1277 {
1278 self.samples_read += count;
1279 }
1280 let read = SourceRead {
1281 planes: source.channels.as_slice(),
1282 downmix: &downmix,
1283 start: source.start_sample,
1284 offset,
1285 count,
1286 };
1287 match (map.cursor(first_sample), map.interpolator()) {
1288 (None, interpolator) => self.read_divided(&read, map, first_sample, interpolator),
1290 (Some(cursor), None) => self.read_copied(&read, cursor),
1291 (Some(cursor), Some(interpolator)) => {
1292 self.read_filtered(&read, map, cursor, interpolator);
1293 }
1294 }
1295 true
1296 }
1297
1298 fn read_copied(&mut self, read: &SourceRead<'_>, cursor: RationalCursor) {
1300 let Some(first) = cursor.whole.checked_sub(read.start) else {
1301 return;
1302 };
1303 for channel in 0..self.layout.channels() {
1304 let mix = read.downmix.channel(channel);
1305 let mut at = first;
1306 let outputs = &mut self.clip_a[channel][read.offset..read.offset + read.count];
1307 if let Some(plane) = mix.unity() {
1308 let plane = read.planes[plane].as_slice();
1309 for output in outputs {
1310 *output = copied(plane, at);
1311 at = at.wrapping_add(cursor.step_whole);
1312 }
1313 } else {
1314 for output in outputs {
1315 *output = mixed_sample(mix, read.planes, at);
1316 at = at.wrapping_add(cursor.step_whole);
1317 }
1318 }
1319 }
1320 }
1321
1322 fn read_filtered(
1325 &mut self,
1326 read: &SourceRead<'_>,
1327 map: &SourceMap,
1328 mut cursor: RationalCursor,
1329 interpolator: Interpolator,
1330 ) {
1331 let mut weights = std::mem::take(&mut self.weights);
1332 let reach = interpolator.half_taps() - 1;
1333 let taps = usize::try_from(2 * interpolator.half_taps()).unwrap_or(0);
1334 let phases = usize::try_from(cursor.period())
1335 .ok()
1336 .filter(|&period| period <= read.count / 2 && period * taps <= MAX_CACHED_WEIGHTS);
1337 if let Some(phases) = phases {
1338 weights.resize(phases * taps, 0.0);
1339 let mut scratch = std::mem::take(&mut self.phase_weights);
1340 let mut walk = cursor;
1341 for row in weights.chunks_exact_mut(taps) {
1342 interpolator.weights(map.fraction(&walk).1, &mut scratch);
1343 row.copy_from_slice(&scratch);
1344 walk.advance();
1345 }
1346 self.phase_weights = scratch;
1347 }
1348 let mut phase = 0;
1349 for index in 0..read.count {
1350 let (whole, fraction) = map.fraction(&cursor);
1351 cursor.advance();
1352 let row = if let Some(phases) = phases {
1353 let row = phase;
1354 phase = if phase + 1 == phases { 0 } else { phase + 1 };
1355 &weights[row * taps..(row + 1) * taps]
1356 } else {
1357 interpolator.weights(fraction, &mut weights);
1358 &weights[..]
1359 };
1360 let Some(first) = whole
1361 .checked_sub(read.start)
1362 .and_then(|at| at.checked_sub(reach))
1363 else {
1364 continue;
1365 };
1366 for channel in 0..self.layout.channels() {
1367 self.clip_a[channel][read.offset + index] =
1368 filtered_sample(read.downmix.channel(channel), read.planes, first, row);
1369 }
1370 }
1371 self.weights = weights;
1372 }
1373
1374 fn read_divided(
1376 &mut self,
1377 read: &SourceRead<'_>,
1378 map: &SourceMap,
1379 first_sample: i64,
1380 interpolator: Option<Interpolator>,
1381 ) {
1382 let mut weights = std::mem::take(&mut self.weights);
1383 for index in 0..read.count {
1384 let sample = first_sample + i64::try_from(index).unwrap_or(0);
1385 let Some((whole, fraction)) = map.position(sample) else {
1386 continue;
1387 };
1388 let Some(at) = whole.checked_sub(read.start) else {
1389 continue;
1390 };
1391 if let Some(interpolator) = interpolator {
1392 interpolator.weights(fraction, &mut weights);
1393 }
1394 for channel in 0..self.layout.channels() {
1395 let mix = read.downmix.channel(channel);
1396 self.clip_a[channel][read.offset + index] = match interpolator {
1397 None => mixed_sample(mix, read.planes, at),
1398 Some(interpolator) => filtered_sample(
1399 mix,
1400 read.planes,
1401 at - interpolator.half_taps() + 1,
1402 &weights,
1403 ),
1404 };
1405 }
1406 }
1407 self.weights = weights;
1408 }
1409
1410 fn apply_clip_chain(
1413 &mut self,
1414 (bus, position): (usize, usize),
1415 input: i64,
1416 transport: TransportState,
1417 count: usize,
1418 ) {
1419 let ctx = self.ctx(input, transport);
1420 let (layout, sample_rate, max_block) = (self.layout, self.sample_rate, self.max_block);
1421 let Some(clip_chain) = self.buses[bus].clips[position].chain.as_mut() else {
1422 return;
1423 };
1424 if clip_chain.chain.is_none() {
1425 self.live_chains.push((bus, position));
1426 }
1427 let effects = &clip_chain.effects;
1428 let chain = clip_chain
1429 .chain
1430 .get_or_insert_with(|| clip_processors(effects, layout, sample_rate, max_block));
1431 clip_chain.ran_in = self.blocks_mixed;
1432 if clip_chain.next_input != Some(input) {
1433 chain.reset();
1434 }
1435 clip_chain.next_input = Some(input + i64::try_from(count).unwrap_or(0));
1436 chain.process_in_place(&ctx, &mut self.clip_a, &mut self.clip_b, count);
1437 #[cfg(test)]
1438 self.note_held();
1439 }
1440
1441 #[cfg(test)]
1443 fn note_held(&mut self) {
1444 let held = self
1445 .live_chains
1446 .iter()
1447 .filter_map(|&(bus, position)| self.buses[bus].clips[position].chain.as_ref())
1448 .filter(|clip| clip.chain.is_some())
1449 .fold((0, 0), |(effects, delay), clip| {
1450 (
1451 effects + clip.effects.len(),
1452 delay
1453 + clip
1454 .effects
1455 .iter()
1456 .map(AudioEffect::delay_ticks)
1457 .sum::<u64>(),
1458 )
1459 });
1460 self.most_held = (self.most_held.0.max(held.0), self.most_held.1.max(held.1));
1461 }
1462
1463 #[allow(clippy::too_many_arguments)]
1466 fn mix_clip_into_bus(
1467 &mut self,
1468 clip: &ActiveAudioClip,
1469 bus_index: usize,
1470 start_sample: i64,
1471 offset: usize,
1472 count: usize,
1473 frames: usize,
1474 context: &SampleContext<'_>,
1475 ) {
1476 let channels = self.layout.channels();
1477 let sample_rate = self.sample_rate;
1478 let bus = &mut self.buses[bus_index];
1479 let first = start_sample + i64::try_from(offset).unwrap_or(0);
1480 bus.make_live(channels, frames);
1481 let gain = constant_value(&clip.audio.gain).map(|gain| gain.clamp(0.0, MAX_GAIN));
1482 let weights =
1483 constant_value(&clip.audio.pan).map(|pan| pan_gains(pan.clamp(-1.0, 1.0), channels));
1484 if let (Some(gain), Some(weights), false) =
1485 (gain, weights, fades_reach(clip, first, count, sample_rate))
1486 {
1487 for (channel, weight) in weights.iter().enumerate().take(channels) {
1488 let input = &self.clip_a[channel][..count];
1489 let output = &mut bus.output[channel][offset..offset + count];
1490 for (output, sample) in output.iter_mut().zip(input) {
1491 *output += sample * gain * weight;
1492 }
1493 }
1494 return;
1495 }
1496 let audio = clip.audio;
1497 fill_envelope(
1498 &mut self.envelope[..],
1499 first,
1500 count,
1501 sample_rate,
1502 |ticks| {
1503 earliest(
1504 earliest(
1505 next_keyframe(&audio.gain, ticks, context),
1506 next_keyframe(&audio.pan, ticks, context),
1507 ),
1508 next_fade_edge(clip, ticks),
1509 )
1510 },
1511 |time| {
1512 let gain = sample_scalar(&audio.gain, time, context).clamp(0.0, MAX_GAIN)
1513 * fade_gain(clip, time);
1514 let [left, right] = pan_gains(sample_scalar(&audio.pan, time, context), channels);
1515 [gain, left, right]
1516 },
1517 );
1518 let [gains, left, right] = &self.envelope;
1519 for (channel, weights) in [left, right].into_iter().enumerate().take(channels) {
1520 let input = &self.clip_a[channel][..count];
1521 let output = &mut bus.output[channel][offset..offset + count];
1522 for (((output, sample), gain), weight) in
1523 output.iter_mut().zip(input).zip(gains).zip(weights)
1524 {
1525 *output += sample * gain * weight;
1526 }
1527 }
1528 }
1529
1530 fn process_buses(
1531 &mut self,
1532 master_input: i64,
1533 transport: TransportState,
1534 frames: usize,
1535 stages: Stages,
1536 ) {
1537 let channels = self.layout.channels();
1538 let sample_rate = self.sample_rate;
1539 for bus in &mut self.buses {
1540 if !stages.run(bus.chain_lead) || bus.chain.passes_through() {
1541 continue;
1542 }
1543 let input = master_input + bus.latency;
1544 let ctx = &ProcessCtx {
1545 position: MediaTime::from_ticks(ticks_at(input, sample_rate)),
1546 sample_position: input,
1547 sample_rate,
1548 transport,
1549 };
1550 bus.make_live(channels, frames);
1551 for channel in 0..channels {
1552 self.bus_in[channel][..frames].copy_from_slice(&bus.output[channel][..frames]);
1553 }
1554 match channels {
1555 1 => bus.chain.process(
1556 ctx,
1557 &[&self.bus_in[0][..frames]],
1558 &mut [&mut bus.output[0][..frames]],
1559 ),
1560 2 => {
1561 let (left, right) = bus.output.split_at_mut(1);
1562 bus.chain.process(
1563 ctx,
1564 &[&self.bus_in[0][..frames], &self.bus_in[1][..frames]],
1565 &mut [&mut left[0][..frames], &mut right[0][..frames]],
1566 );
1567 }
1568 _ => {}
1569 }
1570 }
1571 }
1572
1573 fn apply_ducking(&mut self, ctx: &ProcessCtx, frames: usize, stages: Stages) {
1578 let channels = self.layout.channels();
1579 let ducks = |bus: &TrackBus, index: usize| {
1580 bus.active_sidechain(index).is_some() && stages.run(bus.ducker_lead)
1581 };
1582 for index in 0..self.buses.len() {
1583 if !ducks(&self.buses[index], index) {
1584 continue;
1585 }
1586 let Some(sidechain) = self.buses[index].active_sidechain(index) else {
1587 continue;
1588 };
1589 self.buses[sidechain].make_live(channels, frames);
1591 for channel in 0..channels {
1592 self.bus_in[channel][..frames]
1593 .copy_from_slice(&self.buses[sidechain].output[channel][..frames]);
1594 }
1595 let bus = &mut self.buses[index];
1596 bus.make_live(channels, frames);
1597 let Some(BusDucker { ducker, output }) = bus.ducker.as_mut() else {
1598 continue;
1599 };
1600 match channels {
1601 1 => ducker.process(
1602 ctx,
1603 &[&bus.output[0][..frames], &self.bus_in[0][..frames]],
1604 &mut [&mut output[0][..frames]],
1605 ),
1606 2 => {
1607 let (left, right) = output.split_at_mut(1);
1608 ducker.process(
1609 ctx,
1610 &[
1611 &bus.output[0][..frames],
1612 &bus.output[1][..frames],
1613 &self.bus_in[0][..frames],
1614 &self.bus_in[1][..frames],
1615 ],
1616 &mut [&mut left[0][..frames], &mut right[0][..frames]],
1617 );
1618 }
1619 _ => {}
1620 }
1621 }
1622 for (index, bus) in self.buses.iter_mut().enumerate() {
1623 if ducks(bus, index)
1624 && let Some(ducking) = bus.ducker.as_mut()
1625 {
1626 std::mem::swap(&mut bus.output, &mut ducking.output);
1627 }
1628 }
1629 }
1630
1631 fn sum_buses(&mut self, start_sample: i64, frames: usize, context: &SampleContext<'_>) {
1632 let channels = self.layout.channels();
1633 for bus_index in 0..self.buses.len() {
1634 if self.is_silent_bus(bus_index) || !self.buses[bus_index].live {
1636 continue;
1637 }
1638 let bus = &self.buses[bus_index];
1639 #[cfg(test)]
1640 BUS_PLANES_SUMMED.set(BUS_PLANES_SUMMED.get() + channels);
1641 let gain = constant_value(&bus.audio.gain).map(|gain| gain.clamp(0.0, MAX_GAIN));
1642 let weights =
1643 constant_value(&bus.audio.pan).map(|pan| pan_gains(pan.clamp(-1.0, 1.0), channels));
1644 if let (Some(gain), Some(weights)) = (gain, weights) {
1645 for (channel, weight) in weights.iter().enumerate().take(channels) {
1646 let input = &bus.output[channel][..frames];
1647 let output = &mut self.mix[channel][..frames];
1648 for (output, sample) in output.iter_mut().zip(input) {
1649 *output += sample * gain * weight;
1650 }
1651 }
1652 continue;
1653 }
1654 let audio = &bus.audio;
1655 fill_envelope(
1656 &mut self.envelope[..],
1657 start_sample,
1658 frames,
1659 self.sample_rate,
1660 |ticks| {
1661 earliest(
1662 next_keyframe(&audio.gain, ticks, context),
1663 next_keyframe(&audio.pan, ticks, context),
1664 )
1665 },
1666 |time| {
1667 let gain = sample_scalar(&audio.gain, time, context).clamp(0.0, MAX_GAIN);
1668 let [left, right] =
1669 pan_gains(sample_scalar(&audio.pan, time, context), channels);
1670 [gain, left, right]
1671 },
1672 );
1673 let [gains, left, right] = &self.envelope;
1674 for (channel, weights) in [left, right].into_iter().enumerate().take(channels) {
1675 let input = &bus.output[channel][..frames];
1676 let output = &mut self.mix[channel][..frames];
1677 for (((output, sample), gain), weight) in
1678 output.iter_mut().zip(input).zip(gains).zip(weights)
1679 {
1680 *output += sample * gain * weight;
1681 }
1682 }
1683 }
1684 }
1685
1686 #[allow(clippy::too_many_arguments)]
1687 fn finish_master(
1688 &mut self,
1689 start_sample: i64,
1690 master_input: i64,
1691 transport: TransportState,
1692 frames: usize,
1693 stages: Stages,
1694 complete: bool,
1695 context: &SampleContext<'_>,
1696 ) {
1697 let channels = self.layout.channels();
1698 let input_ctx = self.ctx(master_input, transport);
1699 let ctx = &self.ctx(start_sample, transport);
1700 match channels {
1701 1 => self.master_chain.process(
1702 &input_ctx,
1703 &[&self.mix[0][..frames]],
1704 &mut [&mut self.output[0][..frames]],
1705 ),
1706 2 => {
1707 let (left, right) = self.output.split_at_mut(1);
1708 self.master_chain.process(
1709 &input_ctx,
1710 &[&self.mix[0][..frames], &self.mix[1][..frames]],
1711 &mut [&mut left[0][..frames], &mut right[0][..frames]],
1712 );
1713 }
1714 _ => {}
1715 }
1716 if let Some(gain) = constant_value(&self.master.gain) {
1717 let gain = gain.clamp(0.0, MAX_GAIN);
1718 for channel in 0..channels {
1719 for sample in &mut self.output[channel][..frames] {
1720 *sample *= gain;
1721 }
1722 }
1723 } else {
1724 let gain = &self.master.gain;
1725 fill_envelope(
1726 &mut self.envelope[..],
1727 start_sample,
1728 frames,
1729 self.sample_rate,
1730 |ticks| next_keyframe(gain, ticks, context),
1731 |time| [sample_scalar(gain, time, context).clamp(0.0, MAX_GAIN)],
1732 );
1733 for channel in 0..channels {
1734 let envelope = &self.envelope[0][..frames];
1735 for (sample, gain) in self.output[channel][..frames].iter_mut().zip(envelope) {
1736 *sample *= gain;
1737 }
1738 }
1739 }
1740 if self.normalization_gain.to_bits() != 1.0_f32.to_bits() {
1741 for channel in 0..channels {
1742 for sample in &mut self.output[channel][..frames] {
1743 *sample *= self.normalization_gain;
1744 }
1745 }
1746 }
1747 let measured = stages.target.is_none() && complete;
1749 if measured && let Some(meter) = self.meter.as_mut() {
1750 let planes = [&self.output[0][..frames], &self.output[1][..frames]];
1751 let _ = meter.push(&planes[..channels]);
1753 }
1754 if let Some(limiter) = self
1755 .limiter
1756 .as_mut()
1757 .filter(|_| stages.run(self.limiter_lead))
1758 {
1759 for channel in 0..channels {
1760 self.mix[channel][..frames].copy_from_slice(&self.output[channel][..frames]);
1761 }
1762 match channels {
1763 1 => limiter.process(
1764 ctx,
1765 &[&self.mix[0][..frames]],
1766 &mut [&mut self.output[0][..frames]],
1767 ),
1768 2 => {
1769 let (left, right) = self.output.split_at_mut(1);
1770 limiter.process(
1771 ctx,
1772 &[&self.mix[0][..frames], &self.mix[1][..frames]],
1773 &mut [&mut left[0][..frames], &mut right[0][..frames]],
1774 );
1775 }
1776 _ => {}
1777 }
1778 }
1779 if measured && let Some(meter) = self.output_meter.as_mut() {
1780 let planes = [&self.output[0][..frames], &self.output[1][..frames]];
1781 let _ = meter.push(&planes[..channels]);
1782 }
1783 }
1784}
1785
1786fn track_buses(
1787 project: &alpha2_model::Project,
1788 layout: ChannelLayout,
1789 sample_rate: u32,
1790 max_block: usize,
1791) -> (Vec<TrackBus>, HashMap<TrackId, usize>) {
1792 let mut buses = Vec::new();
1793 let mut bus_of_track = HashMap::new();
1794 for track in &project.timeline.tracks {
1796 let mut chain = ProcessorChain::new(layout);
1797 push_effects(&mut chain, &track.audio.effects);
1798 chain.prepare(sample_rate, max_block);
1799 let chain_latency = chain.latency_samples();
1800 let ducker = track.audio.ducking.as_ref().map(|ducking| {
1801 let mut ducker = Ducker::new(
1802 ducking.threshold,
1803 ducking.depth_db,
1804 ducking.attack_ms,
1805 ducking.release_ms,
1806 );
1807 ducker.prepare(sample_rate, max_block);
1808 BusDucker {
1809 ducker,
1810 output: buffers(max_block),
1811 }
1812 });
1813 bus_of_track.insert(track.id.clone(), buses.len());
1814 buses.push(TrackBus {
1815 id: track.id.clone(),
1816 audio: track.audio.clone(),
1817 chain,
1818 ducker,
1819 sidechain: None,
1820 output: buffers(max_block),
1821 live: false,
1822 latency: i64::from(chain_latency),
1823 clips: clip_slots(&track.clips, layout, sample_rate, max_block),
1824 chain_lead: 0,
1825 ducker_lead: 0,
1826 read: false,
1827 });
1828 }
1829 (buses, bus_of_track)
1830}
1831
1832fn clip_slots(
1834 clips: &[alpha2_model::Clip],
1835 layout: ChannelLayout,
1836 sample_rate: u32,
1837 max_block: usize,
1838) -> Vec<ClipSlot> {
1839 clips
1840 .iter()
1841 .map(|clip| ClipSlot {
1842 id: clip.id.clone(),
1843 chain: (!clip.audio.effects.is_empty()).then(|| {
1844 let chain = clip_processors(&clip.audio.effects, layout, sample_rate, max_block);
1846 ClipChain {
1847 effects: clip.audio.effects.clone(),
1848 chain: None,
1849 ran_in: 0,
1850 latency: i64::from(chain.latency_samples()),
1851 history: chain.history_samples(),
1852 next_input: None,
1853 lead: 0,
1854 }
1855 }),
1856 })
1857 .collect()
1858}
1859
1860fn clip_processors(
1861 effects: &[AudioEffect],
1862 layout: ChannelLayout,
1863 sample_rate: u32,
1864 max_block: usize,
1865) -> ProcessorChain {
1866 let mut chain = ProcessorChain::new(layout);
1867 push_effects(&mut chain, effects);
1868 chain.prepare_nodes(sample_rate, max_block);
1869 chain
1870}
1871
1872fn longest_path_latency(buses: &[TrackBus]) -> i64 {
1874 buses
1875 .iter()
1876 .map(|bus| {
1877 bus.latency
1878 + bus
1879 .clips
1880 .iter()
1881 .filter_map(|slot| slot.chain.as_ref())
1882 .map(|chain| chain.latency)
1883 .max()
1884 .unwrap_or(0)
1885 })
1886 .max()
1887 .unwrap_or(0)
1888}
1889
1890fn assign_leads(buses: &mut [TrackBus], master_lead: i64, settling: Settling) -> i64 {
1895 let ducker_leads: Vec<Option<i64>> = buses
1896 .iter()
1897 .enumerate()
1898 .map(|(index, bus)| {
1899 let ducking = bus.ducker.as_ref()?;
1900 bus.active_sidechain(index)?;
1901 Some(settling.lead(master_lead, ducking.ducker.history_samples()))
1902 })
1903 .collect();
1904 let mut longest = master_lead;
1905 for index in 0..buses.len() {
1906 let sidechained = buses
1907 .iter()
1908 .enumerate()
1909 .filter(|&(user, bus)| bus.active_sidechain(user) == Some(index))
1910 .filter_map(|(user, _)| ducker_leads[user]);
1911 let settled_from = sidechained
1912 .chain(ducker_leads[index])
1913 .fold(master_lead, i64::max);
1914 let bus = &mut buses[index];
1915 bus.ducker_lead = ducker_leads[index].unwrap_or(0);
1916 bus.chain_lead = settling.lead(settled_from, bus.chain.history_samples());
1917 longest = longest.max(bus.chain_lead);
1918 for clip in bus.clips.iter_mut().filter_map(|slot| slot.chain.as_mut()) {
1919 clip.lead = settling.lead(bus.chain_lead, clip.history);
1920 longest = longest.max(clip.lead);
1921 }
1922 }
1923 longest
1924}
1925
1926#[derive(Clone, Copy)]
1928struct Settling(i64);
1929
1930impl Settling {
1931 fn lead(self, downstream: i64, history: u32) -> i64 {
1934 downstream
1935 .saturating_add(i64::from(history))
1936 .min(self.0.max(downstream))
1937 }
1938}
1939
1940#[derive(Clone, Copy)]
1943struct Stages {
1944 target: Option<i64>,
1945 block_end: i64,
1946 lookahead: i64,
1947}
1948
1949impl Stages {
1950 fn run(self, lead: i64) -> bool {
1951 self.target
1952 .is_none_or(|target| self.block_end > Self::start(target, lead, self.lookahead))
1953 }
1954
1955 fn start(target: i64, lead: i64, lookahead: i64) -> i64 {
1958 (target - lead).max(0).saturating_sub(lookahead)
1959 }
1960}
1961
1962fn stage_leads(buses: &[TrackBus], master_lead: i64, limiter_lead: i64) -> Vec<i64> {
1964 let mut leads = vec![master_lead, limiter_lead];
1965 for (index, bus) in buses.iter().enumerate() {
1966 leads.push(bus.chain_lead);
1967 if bus.active_sidechain(index).is_some() {
1968 leads.push(bus.ducker_lead);
1969 }
1970 leads.extend(
1971 bus.clips
1972 .iter()
1973 .filter_map(|slot| slot.chain.as_ref())
1974 .map(|chain| chain.lead),
1975 );
1976 }
1977 leads.sort_unstable_by(|a, b| b.cmp(a));
1978 leads.dedup();
1979 leads
1980}
1981
1982fn read_buses(buses: &mut [TrackBus], any_solo: bool) {
1986 let heard: Vec<bool> = buses
1987 .iter()
1988 .map(|bus| !bus.audio.is_silenced(any_solo))
1989 .collect();
1990 let keys: Vec<Option<usize>> = buses
1991 .iter()
1992 .enumerate()
1993 .map(|(index, bus)| heard[index].then(|| bus.active_sidechain(index)).flatten())
1994 .collect();
1995 for (index, bus) in buses.iter_mut().enumerate() {
1996 bus.read = heard[index] || (!bus.audio.muted && keys.contains(&Some(index)));
1997 }
1998}
1999
2000fn resolve_sidechains(buses: &mut [TrackBus], bus_of_track: &HashMap<TrackId, usize>) {
2001 for bus in buses {
2002 bus.sidechain = bus
2003 .audio
2004 .ducking
2005 .as_ref()
2006 .and_then(|ducking| bus_of_track.get(&ducking.sidechain_track).copied());
2007 }
2008}
2009
2010fn buffers(max_block: usize) -> [Vec<f32>; 2] {
2011 [vec![0.0; max_block], vec![0.0; max_block]]
2012}
2013
2014fn push_effects(chain: &mut ProcessorChain, effects: &[AudioEffect]) {
2015 for effect in effects {
2016 match effect {
2017 AudioEffect::Eq { bands } => {
2018 for band in bands {
2019 push_effect(
2020 chain,
2021 Biquad::new(
2022 match band.kind {
2023 EqBandKind::Peaking => BiquadKind::Peaking,
2024 EqBandKind::LowPass => BiquadKind::LowPass,
2025 EqBandKind::HighPass => BiquadKind::HighPass,
2026 },
2027 band.frequency_hz,
2028 band.q,
2029 band.gain_db,
2030 ),
2031 );
2032 }
2033 }
2034 AudioEffect::Compressor {
2035 threshold_db,
2036 ratio,
2037 attack_ms,
2038 release_ms,
2039 lookahead_ms,
2040 } => push_effect(
2041 chain,
2042 Compressor::new(
2043 *threshold_db,
2044 *ratio,
2045 *attack_ms,
2046 *release_ms,
2047 *lookahead_ms,
2048 ),
2049 ),
2050 AudioEffect::Reverb {
2051 room_size,
2052 damping,
2053 mix,
2054 } => push_effect(chain, SchroederReverb::new(*room_size, *damping, *mix)),
2055 }
2056 }
2057}
2058
2059fn push_effect(chain: &mut ProcessorChain, effect: impl Processor + 'static) {
2060 chain
2061 .push(effect)
2062 .expect("a model effect reads one input per output");
2063}
2064
2065fn ticks_at(sample: i64, sample_rate: u32) -> i64 {
2066 checked_ticks_at(sample, sample_rate).unwrap_or(i64::MAX)
2067}
2068
2069fn checked_ticks_at(sample: i64, sample_rate: u32) -> Option<i64> {
2071 let rate = i128::from(sample_rate.max(1));
2072 i64::try_from((i128::from(sample) * i128::from(TICKS_PER_SECOND)).div_euclid(rate)).ok()
2073}
2074
2075struct SourceRead<'a> {
2077 planes: &'a [Vec<f32>],
2078 downmix: &'a Downmix,
2079 start: i64,
2081 offset: usize,
2082 count: usize,
2083}
2084
2085struct ClipRead {
2087 bus: usize,
2088 bus_input: i64,
2089 slot: Option<(usize, usize)>,
2090 first: i64,
2092 window: ClipWindow,
2093}
2094
2095#[derive(Clone, Copy)]
2097struct ClipWindow {
2098 offset: usize,
2100 count: usize,
2102 content: usize,
2104}
2105
2106fn ticks_at_or_after(sample: i64, sample_rate: u32) -> Option<i64> {
2108 let rate = i128::from(sample_rate.max(1));
2109 let numerator = i128::from(sample) * i128::from(TICKS_PER_SECOND);
2110 i64::try_from(numerator.div_euclid(rate) + i128::from(numerator.rem_euclid(rate) != 0)).ok()
2111}
2112
2113pub(crate) fn clip_downmix(
2117 clip: &ActiveAudioClip,
2118 source: &AudioBlock,
2119 layout: ChannelLayout,
2120) -> Option<Downmix> {
2121 if source.speakers.channels() != source.channels.len() {
2122 return None;
2123 }
2124 match clip.audio.channels.as_deref() {
2125 Some(selection) => Downmix::selected(selection, source.channels.len(), layout),
2126 None => Downmix::new(source.speakers.speakers(), layout),
2127 }
2128}
2129
2130fn merge_need(
2133 needs: &mut Vec<AudioNeed>,
2134 source_id: &SourceId,
2135 stream: Option<u32>,
2136 mut source_range: TimeRange,
2137) {
2138 while let Some(index) = needs.iter().position(|need| {
2140 need.source_id == *source_id
2141 && need.stream == stream
2142 && need.source_range.start() <= source_range.end()
2143 && source_range.start() <= need.source_range.end()
2144 }) {
2145 let existing = needs.remove(index).source_range;
2146 let merged_start = existing.start().min(source_range.start());
2147 let merged_end = existing.end().max(source_range.end());
2148 if let Ok(merged) = TimeRange::new(merged_start, merged_end) {
2149 source_range = merged;
2150 }
2151 }
2152 needs.push(AudioNeed {
2153 source_id: source_id.clone(),
2154 stream,
2155 source_range,
2156 });
2157}
2158
2159fn source_requests(
2162 stretch: &Stretch,
2163 clip: &ActiveAudioClip,
2164 first_sample: i64,
2165 count: usize,
2166 rate: u32,
2167 mut request: impl FnMut(i64, i64),
2168) {
2169 if count == 0 {
2170 return;
2171 }
2172 match clip.time_map {
2173 TimeMap::Freeze { .. } => {}
2174 TimeMap::Forward | TimeMap::Reverse if stretches(clip) => {
2175 if let Some((from, to)) = stretched_request(stretch, clip, first_sample, count, rate) {
2176 request(from, to);
2177 }
2178 }
2179 TimeMap::Forward | TimeMap::Reverse => {
2180 let reversed = clip.time_map == TimeMap::Reverse;
2181 if let Some((from, to)) = SourceMap::stretched(clip, reversed, rate)
2182 .and_then(|map| map.request(first_sample, count))
2183 {
2184 request(from, to);
2185 }
2186 }
2187 TimeMap::Loop { mode } => {
2188 loop_pieces(clip, mode, first_sample, count, rate, |piece| {
2189 if let Some((from, to)) = piece.map.request(piece.sample, piece.length) {
2190 request(from, to);
2191 }
2192 });
2193 }
2194 }
2195}
2196
2197struct LoopPiece {
2199 sample: i64,
2201 index: usize,
2202 length: usize,
2203 pass: i64,
2205 pass_start: i64,
2206 pass_end: i64,
2207 piece_end: i64,
2209 map: SourceMap,
2210}
2211
2212fn loop_pieces(
2215 clip: &ActiveAudioClip,
2216 mode: LoopMode,
2217 first_sample: i64,
2218 count: usize,
2219 rate: u32,
2220 mut piece: impl FnMut(LoopPiece),
2221) -> bool {
2222 let Some(period) = clip.source_range.duration().map(MediaTime::ticks) else {
2223 return false;
2224 };
2225 if period <= 0 {
2226 return false;
2227 }
2228 let start = clip.timeline_range.start().ticks();
2229 let mut index = 0;
2230 while index < count {
2231 let sample = first_sample + i64::try_from(index).unwrap_or(i64::MAX);
2232 let pass = (ticks_at(sample, rate) - start).div_euclid(period);
2233 let Some(pass_start) = pass
2234 .checked_mul(period)
2235 .and_then(|ticks| ticks.checked_add(start))
2236 else {
2237 return false;
2238 };
2239 let pass_end = pass_start.saturating_add(period);
2240 let piece_end = sample_at_or_after(pass_end, rate);
2241 let length = usize::try_from(piece_end.saturating_sub(sample))
2242 .unwrap_or(usize::MAX)
2243 .clamp(1, count - index);
2244 let reversed = mode == LoopMode::PingPong && pass.rem_euclid(2) == 1;
2245 let Some(map) = SourceMap::pass(clip, pass_start, reversed, rate) else {
2246 return false;
2247 };
2248 piece(LoopPiece {
2249 sample,
2250 index,
2251 length,
2252 pass,
2253 pass_start,
2254 pass_end,
2255 piece_end,
2256 map,
2257 });
2258 index += length;
2259 }
2260 true
2261}
2262
2263fn sample_at_or_after(ticks: i64, sample_rate: u32) -> i64 {
2264 let rate = i128::from(sample_rate.max(1));
2265 let numerator = i128::from(ticks) * rate;
2266 let denominator = i128::from(TICKS_PER_SECOND);
2267 let value =
2268 numerator.div_euclid(denominator) + i128::from(numerator.rem_euclid(denominator) != 0);
2269 i64::try_from(value).unwrap_or(i64::MAX)
2270}
2271
2272fn mixed_sample(mix: &ChannelMix, planes: &[Vec<f32>], index: i64) -> f32 {
2275 if let Some(plane) = mix.unity() {
2276 return copied(&planes[plane], index);
2277 }
2278 let mut sum = 0.0;
2279 for &(plane, weight) in mix.terms() {
2280 sum += weight * copied(&planes[plane], index);
2281 }
2282 sum
2283}
2284
2285fn filtered_sample(mix: &ChannelMix, planes: &[Vec<f32>], first: i64, weights: &[f64]) -> f32 {
2287 if let Some(plane) = mix.unity() {
2288 return filtered(&planes[plane], first, weights);
2289 }
2290 let mut sum = 0.0;
2291 for &(plane, weight) in mix.terms() {
2292 sum += weight * filtered(&planes[plane], first, weights);
2293 }
2294 sum
2295}
2296
2297fn copied(plane: &[f32], index: i64) -> f32 {
2300 let value = usize::try_from(index)
2301 .ok()
2302 .and_then(|index| plane.get(index).copied())
2303 .unwrap_or(0.0);
2304 if value.is_finite() { value } else { 0.0 }
2305}
2306
2307fn filtered(plane: &[f32], first: i64, weights: &[f64]) -> f32 {
2309 let mut sum = weighed(plane, first, weights, false);
2310 if !sum.is_finite() {
2311 sum = weighed(plane, first, weights, true);
2312 }
2313 #[allow(clippy::cast_possible_truncation)]
2314 let value = sum as f32;
2315 if value.is_finite() { value } else { 0.0 }
2316}
2317
2318fn weighed(plane: &[f32], first: i64, weights: &[f64], finite_only: bool) -> f64 {
2321 let inside = usize::try_from(first).ok().filter(|&from| {
2322 from.checked_add(weights.len())
2323 .is_some_and(|end| end <= plane.len())
2324 });
2325 let mut sums = [0.0_f64; 4];
2326 match inside {
2327 Some(from) if !finite_only => {
2328 let (weight_quads, weight_rest) = weights.as_chunks::<4>();
2329 let (sample_quads, sample_rest) = plane[from..from + weights.len()].as_chunks::<4>();
2330 for (weight, value) in weight_quads.iter().zip(sample_quads) {
2331 for lane in 0..4 {
2332 sums[lane] += weight[lane] * f64::from(value[lane]);
2333 }
2334 }
2335 for (lane, (weight, value)) in weight_rest.iter().zip(sample_rest).enumerate() {
2336 sums[lane] += weight * f64::from(*value);
2337 }
2338 }
2339 _ => {
2340 for (index, (at, weight)) in (first..).zip(weights).enumerate() {
2341 let value = usize::try_from(at)
2342 .ok()
2343 .and_then(|at| plane.get(at).copied())
2344 .unwrap_or(0.0);
2345 if value.is_finite() {
2346 sums[index % 4] += weight * f64::from(value);
2347 }
2348 }
2349 }
2350 }
2351 (sums[0] + sums[1]) + (sums[2] + sums[3])
2352}
2353
2354struct SourceMap {
2359 a: i128,
2360 b: i128,
2361 d: i128,
2362}
2363
2364impl SourceMap {
2365 fn stretched(clip: &ActiveAudioClip, reversed: bool, rate: u32) -> Option<Self> {
2368 let timeline = clip.timeline_range;
2369 let forward = Self::line(
2370 i128::from(timeline.start().ticks()),
2371 i128::from(clip.source_range.start().ticks()),
2372 i128::from(timeline.duration()?.ticks()),
2373 i128::from(clip.source_range.duration()?.ticks()),
2374 rate,
2375 )?;
2376 if !reversed {
2377 return Some(forward);
2378 }
2379 forward.mirrored(
2380 sample_at_or_after(timeline.start().ticks(), rate),
2381 sample_at_or_after(timeline.end().ticks(), rate),
2382 )
2383 }
2384
2385 fn pass(clip: &ActiveAudioClip, pass_start: i64, reversed: bool, rate: u32) -> Option<Self> {
2387 let period = clip.source_range.duration()?.ticks();
2388 let forward = Self::line(
2389 i128::from(pass_start),
2390 i128::from(clip.source_range.start().ticks()),
2391 i128::from(period),
2392 i128::from(period),
2393 rate,
2394 )?;
2395 if !reversed {
2396 return Some(forward);
2397 }
2398 forward.mirrored(
2399 sample_at_or_after(pass_start, rate),
2400 sample_at_or_after(pass_start.checked_add(period)?, rate),
2401 )
2402 }
2403
2404 fn mirrored(&self, first: i64, last: i64) -> Option<Self> {
2406 let pivot = i128::from(first)
2407 .checked_add(i128::from(last))?
2408 .checked_sub(1)?;
2409 Some(Self {
2410 a: self.a.checked_add(pivot.checked_mul(self.b)?)?,
2411 b: self.b.checked_neg()?,
2412 d: self.d,
2413 })
2414 }
2415
2416 fn line(t0: i128, s0: i128, timeline: i128, source: i128, rate: u32) -> Option<Self> {
2419 if timeline <= 0 || source <= 0 {
2420 return None;
2421 }
2422 let divisor = gcd(timeline, source);
2423 let (timeline, source) = (timeline / divisor, source / divisor);
2424 let rate = i128::from(rate);
2425 let ticks = i128::from(TICKS_PER_SECOND);
2426 let a = rate.checked_mul(
2428 s0.checked_mul(timeline)?
2429 .checked_sub(t0.checked_mul(source)?)?,
2430 )?;
2431 let b = ticks.checked_mul(source)?;
2432 let d = ticks.checked_mul(timeline)?;
2433 Some(Self { a, b, d })
2434 }
2435
2436 fn position(&self, sample: i64) -> Option<(i64, f64)> {
2438 let numerator = self
2439 .a
2440 .checked_add(i128::from(sample).checked_mul(self.b)?)?;
2441 let whole = i64::try_from(numerator.div_euclid(self.d)).ok()?;
2442 let remainder = numerator.rem_euclid(self.d);
2443 #[allow(clippy::cast_precision_loss)]
2444 let fraction = remainder as f64 / self.d as f64;
2445 Some((whole, fraction))
2446 }
2447
2448 fn interpolator(&self) -> Option<Interpolator> {
2450 if self.b.unsigned_abs() == self.d.unsigned_abs() && self.a.rem_euclid(self.d) == 0 {
2451 return None;
2452 }
2453 #[allow(clippy::cast_precision_loss)]
2454 let speed = self.b.unsigned_abs() as f64 / self.d.unsigned_abs() as f64;
2455 Some(Interpolator::new(speed))
2456 }
2457
2458 fn request(&self, first_sample: i64, count: usize) -> Option<(i64, i64)> {
2461 let last_sample = first_sample.checked_add(i64::try_from(count).ok()?.checked_sub(1)?)?;
2462 let (first, _) = self.position(first_sample)?;
2463 let (last, _) = self.position(last_sample)?;
2464 let (low, high) = (first.min(last), first.max(last));
2465 let Some(interpolator) = self.interpolator() else {
2466 return Some((low.max(0), high.saturating_add(1)));
2467 };
2468 let half = interpolator.half_taps();
2469 Some((
2470 low.saturating_sub(half - 1).max(0),
2471 high.saturating_add(half + 1),
2472 ))
2473 }
2474
2475 fn cursor(&self, sample: i64) -> Option<RationalCursor> {
2477 let numerator = self
2478 .a
2479 .checked_add(i128::from(sample).checked_mul(self.b)?)?;
2480 RationalCursor::new(numerator, self.b, self.d)
2481 }
2482
2483 fn fraction(&self, cursor: &RationalCursor) -> (i64, f64) {
2485 #[allow(clippy::cast_precision_loss)]
2487 let fraction = cursor.remainder as f64 / self.d as f64;
2488 (cursor.whole, fraction)
2489 }
2490}
2491
2492#[derive(Clone, Copy, Debug)]
2495struct RationalCursor {
2496 whole: i64,
2497 remainder: u64,
2498 step_whole: i64,
2499 step_remainder: u64,
2500 divisor: u64,
2501}
2502
2503impl RationalCursor {
2504 fn new(numerator: i128, step: i128, divisor: i128) -> Option<Self> {
2505 if divisor <= 0 || divisor > i128::from(i64::MAX) {
2507 return None;
2508 }
2509 Some(Self {
2510 whole: i64::try_from(numerator.div_euclid(divisor)).ok()?,
2511 remainder: u64::try_from(numerator.rem_euclid(divisor)).ok()?,
2512 step_whole: i64::try_from(step.div_euclid(divisor)).ok()?,
2513 step_remainder: u64::try_from(step.rem_euclid(divisor)).ok()?,
2514 divisor: u64::try_from(divisor).ok()?,
2515 })
2516 }
2517
2518 const fn period(&self) -> u64 {
2520 let (mut a, mut b) = (self.step_remainder, self.divisor);
2521 while b != 0 {
2522 (a, b) = (b, a % b);
2523 }
2524 self.divisor / a
2525 }
2526
2527 fn advance(&mut self) {
2528 self.whole = self.whole.wrapping_add(self.step_whole);
2529 self.remainder += self.step_remainder;
2530 if self.remainder >= self.divisor {
2531 self.remainder -= self.divisor;
2532 self.whole = self.whole.wrapping_add(1);
2533 }
2534 }
2535}
2536
2537fn tick_cursor(sample: i64, sample_rate: u32) -> RationalCursor {
2539 let ticks = i128::from(TICKS_PER_SECOND);
2540 RationalCursor::new(
2541 i128::from(sample) * ticks,
2542 ticks,
2543 i128::from(sample_rate.max(1)),
2544 )
2545 .unwrap_or(RationalCursor {
2547 whole: i64::MAX,
2548 remainder: 0,
2549 step_whole: 0,
2550 step_remainder: 0,
2551 divisor: 1,
2552 })
2553}
2554
2555fn gcd(mut a: i128, mut b: i128) -> i128 {
2556 while b != 0 {
2557 (a, b) = (b, a % b);
2558 }
2559 a.abs().max(1)
2560}
2561
2562const ENVELOPE_INTERVAL: i64 = 32;
2567
2568fn fill_envelope<const N: usize>(
2574 envelope: &mut [Vec<f32>],
2575 first: i64,
2576 count: usize,
2577 sample_rate: u32,
2578 next_knot: impl Fn(i64) -> Option<i64>,
2579 at: impl Fn(MediaTime) -> [f32; N],
2580) {
2581 #[allow(clippy::cast_precision_loss)]
2582 let fraction = 1.0 / ENVELOPE_INTERVAL as f32;
2583 let mut knot: Option<Option<i64>> = None;
2585 let mut point: Option<(i64, [f32; N])> = None;
2586 let mut written = 0;
2587 while written < count {
2588 let sample = first.saturating_add(i64::try_from(written).unwrap_or(i64::MAX));
2589 let start = sample.div_euclid(ENVELOPE_INTERVAL) * ENVELOPE_INTERVAL;
2590 let stop = start.saturating_add(ENVELOPE_INTERVAL);
2591 let run = usize::try_from(stop - sample)
2592 .unwrap_or(count)
2593 .clamp(1, count - written);
2594 let (from, to) = (ticks_at(start, sample_rate), ticks_at(stop, sample_rate));
2595 let next = match knot {
2596 Some(next) if next.is_none_or(|next| next > from) => next,
2597 _ => next_knot(from),
2598 };
2599 knot = Some(next);
2600 let outputs = written..written + run;
2601 if next.is_some_and(|next| next <= to) {
2602 let mut ticks = tick_cursor(sample, sample_rate);
2603 for index in outputs {
2604 let value = at(MediaTime::from_ticks(ticks.whole));
2605 ticks.advance();
2606 for (plane, value) in envelope.iter_mut().zip(value) {
2607 plane[index] = value;
2608 }
2609 }
2610 #[cfg(test)]
2611 ENVELOPE_POINTS.set(ENVELOPE_POINTS.get() + run);
2612 } else {
2613 let left = match point {
2614 Some((at_sample, value)) if at_sample == start => value,
2615 _ => {
2616 #[cfg(test)]
2617 ENVELOPE_POINTS.set(ENVELOPE_POINTS.get() + 1);
2618 at(MediaTime::from_ticks(from))
2619 }
2620 };
2621 let right = at(MediaTime::from_ticks(to));
2622 #[cfg(test)]
2623 ENVELOPE_POINTS.set(ENVELOPE_POINTS.get() + 1);
2624 point = Some((stop, right));
2625 #[allow(clippy::cast_precision_loss)]
2626 let along = (sample - start) as f32;
2627 for (plane, (left, right)) in envelope.iter_mut().zip(left.into_iter().zip(right)) {
2628 let slope = right - left;
2629 for (position, output) in plane[outputs.clone()].iter_mut().enumerate() {
2630 #[allow(clippy::cast_precision_loss)]
2631 let position = along + position as f32;
2632 *output = left + slope * (position * fraction);
2633 }
2634 }
2635 }
2636 written += run;
2637 }
2638}
2639
2640#[cfg(test)]
2641thread_local! {
2642 static ENVELOPE_POINTS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2644 static BUS_PLANES_CLEARED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2646 static BUS_PLANES_SUMMED: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
2647}
2648
2649fn earliest(left: Option<i64>, right: Option<i64>) -> Option<i64> {
2651 match (left, right) {
2652 (Some(left), Some(right)) => Some(left.min(right)),
2653 (left, right) => left.or(right),
2654 }
2655}
2656
2657fn next_keyframe(
2659 animation: &Animated<f32>,
2660 ticks: i64,
2661 context: &SampleContext<'_>,
2662) -> Option<i64> {
2663 match animation {
2664 Animated::Data(binding) => {
2665 alpha2_eval::next_data_change(binding, MediaTime(ticks), context).map(MediaTime::ticks)
2666 }
2667 Animated::Keyframes { keyframes } if keyframes.len() > 1 => {
2668 let next = keyframes.partition_point(|keyframe| keyframe.time.ticks() <= ticks);
2669 keyframes.get(next).map(|keyframe| keyframe.time.ticks())
2670 }
2671 _ => None,
2672 }
2673}
2674
2675fn next_fade_edge(clip: &ActiveAudioClip, ticks: i64) -> Option<i64> {
2677 let start = clip.timeline_range.start().ticks();
2678 let end = clip.timeline_range.end().ticks();
2679 let fade_in = clip.audio.fade_in.ticks();
2680 let fade_out = clip.audio.fade_out.ticks();
2681 let mut next = None;
2682 if fade_in > 0 {
2683 for edge in [start, start.saturating_add(fade_in)] {
2684 if edge > ticks {
2685 next = earliest(next, Some(edge));
2686 }
2687 }
2688 }
2689 if fade_out > 0 {
2690 for edge in [end.saturating_sub(fade_out), end] {
2691 if edge > ticks {
2692 next = earliest(next, Some(edge));
2693 }
2694 }
2695 }
2696 next
2697}
2698
2699fn constant_value(animation: &Animated<f32>) -> Option<f32> {
2701 match animation {
2702 Animated::Constant { value } => Some(*value),
2703 Animated::Data(_) => None,
2704 Animated::Keyframes { keyframes } => match keyframes.as_slice() {
2705 [only] => Some(only.value),
2706 _ => None,
2707 },
2708 }
2709}
2710
2711fn fades_reach(clip: &ActiveAudioClip, first: i64, count: usize, sample_rate: u32) -> bool {
2714 let fade_in = clip.audio.fade_in.ticks();
2715 let fade_out = clip.audio.fade_out.ticks();
2716 if fade_in <= 0 && fade_out <= 0 {
2717 return false;
2718 }
2719 let last = first.saturating_add(i64::try_from(count).unwrap_or(i64::MAX).saturating_sub(1));
2720 let elapsed = ticks_at(first, sample_rate).saturating_sub(clip.timeline_range.start().ticks());
2722 let remaining = clip
2723 .timeline_range
2724 .end()
2725 .ticks()
2726 .saturating_sub(ticks_at(last, sample_rate));
2727 (fade_in > 0 && elapsed < fade_in) || (fade_out > 0 && remaining < fade_out)
2728}
2729
2730fn fade_gain(clip: &ActiveAudioClip, time: MediaTime) -> f32 {
2732 let start = clip.timeline_range.start().ticks();
2733 let end = clip.timeline_range.end().ticks();
2734 let shape = clip.audio.fade_shape;
2735 let mut gain = 1.0_f32;
2736 let fade_in = clip.audio.fade_in.ticks();
2737 if fade_in > 0 {
2738 let elapsed = time.ticks().saturating_sub(start);
2739 if elapsed < fade_in {
2740 gain *= shape.amplitude(ratio(elapsed, fade_in));
2741 }
2742 }
2743 let fade_out = clip.audio.fade_out.ticks();
2744 if fade_out > 0 {
2745 let remaining = end.saturating_sub(time.ticks());
2746 if remaining < fade_out {
2747 gain *= shape.amplitude(ratio(remaining, fade_out));
2748 }
2749 }
2750 gain.clamp(0.0, 1.0)
2751}
2752
2753#[allow(clippy::cast_precision_loss)]
2754fn ratio(value: i64, span: i64) -> f32 {
2755 if span <= 0 {
2756 return 1.0;
2757 }
2758 (value.max(0) as f32 / span as f32).clamp(0.0, 1.0)
2759}
2760
2761fn pan_gains(pan: f32, channels: usize) -> [f32; 2] {
2765 if channels < 2 {
2766 return [1.0, 1.0];
2767 }
2768 let angle = (f64::from(pan.clamp(-1.0, 1.0)) + 1.0) * core::f64::consts::FRAC_PI_4;
2770 let normalize = core::f64::consts::SQRT_2;
2771 #[allow(clippy::cast_possible_truncation)]
2772 let weights = [
2773 (libm::cos(angle) * normalize) as f32,
2774 (libm::sin(angle) * normalize) as f32,
2775 ];
2776 weights
2777}
2778
2779#[cfg(test)]
2780mod tests;