feat: official crossfade, concurrent downloads, changelog, and 1-to-1 settings/EQ

This commit is contained in:
marwy 2026-11-27 19:29:32 +03:00
parent ee65d23b2a
commit 41c30f9c35
22 changed files with 3572 additions and 864 deletions

View file

@ -16,7 +16,7 @@ use symphonia::core::meta::MetadataOptions;
use symphonia::core::probe::Hint;
use symphonia::core::units::Time;
use crate::api::models::ResolvedStream;
use crate::api::models::{ResolvedStream, TrackFade};
use crate::api::signing::decrypt_encraw_at_offset;
use dsp::{AudioEnergyAnalyzer, Equalizer10Band};
@ -31,8 +31,21 @@ pub enum AudioCommand {
duration_ms: u64,
r128_i: Option<f32>,
r128_tp: Option<f32>,
fade: Option<TrackFade>,
seek_seq: u64,
},
PreloadNext {
track_id: String,
stream: ResolvedStream,
duration_ms: u64,
r128_i: Option<f32>,
r128_tp: Option<f32>,
fade: Option<TrackFade>,
preload_gen: u64,
},
ClearPreload {
preload_gen: u64,
},
Play,
Pause,
Stop {
@ -53,6 +66,7 @@ pub struct SharedAudioState {
pub muted: AtomicBool,
pub normalize_loudness: AtomicBool,
pub track_gain_bits: AtomicU32,
pub crossfade_enabled: AtomicBool,
pub crossfade_secs_bits: AtomicU32,
pub energy_bits: AtomicU32,
pub bass_bits: AtomicU32,
@ -61,6 +75,7 @@ pub struct SharedAudioState {
pub active_codec: Mutex<String>,
pub output_device_name: Mutex<String>,
pub last_error: Mutex<Option<String>>,
pub crossfaded_track_id: Mutex<Option<String>>,
}
impl SharedAudioState {
@ -70,6 +85,7 @@ impl SharedAudioState {
eq_enabled: bool,
eq_bands: [f32; 10],
normalize_loudness: bool,
crossfade_enabled: bool,
crossfade_secs: f32,
) -> Self {
Self {
@ -84,6 +100,7 @@ impl SharedAudioState {
muted: AtomicBool::new(muted),
normalize_loudness: AtomicBool::new(normalize_loudness),
track_gain_bits: AtomicU32::new(1.0f32.to_bits()),
crossfade_enabled: AtomicBool::new(crossfade_enabled),
crossfade_secs_bits: AtomicU32::new(crossfade_secs.clamp(0.0, 12.0).to_bits()),
energy_bits: AtomicU32::new(0.0f32.to_bits()),
bass_bits: AtomicU32::new(0.0f32.to_bits()),
@ -92,6 +109,7 @@ impl SharedAudioState {
active_codec: Mutex::new("FLAC / WASAPI".into()),
output_device_name: Mutex::new("Системное устройство (WASAPI)".into()),
last_error: Mutex::new(None),
crossfaded_track_id: Mutex::new(None),
}
}
@ -144,6 +162,7 @@ pub fn compute_r128_gain(
pub struct AudioEngine {
tx_cmd: Sender<AudioCommand>,
pub state: Arc<SharedAudioState>,
preload_gen: AtomicU64,
}
impl AudioEngine {
@ -153,6 +172,7 @@ impl AudioEngine {
eq_enabled: bool,
eq_bands: [f32; 10],
normalize_loudness: bool,
crossfade_enabled: bool,
crossfade_secs: f32,
) -> Self {
let state = Arc::new(SharedAudioState::new(
@ -161,6 +181,7 @@ impl AudioEngine {
eq_enabled,
eq_bands,
normalize_loudness,
crossfade_enabled,
crossfade_secs,
));
let (tx_cmd, rx_cmd) = unbounded();
@ -171,16 +192,24 @@ impl AudioEngine {
.spawn(move || run_audio_worker(rx_cmd, state_bg))
.expect("Failed to spawn audio thread");
Self { tx_cmd, state }
Self {
tx_cmd,
state,
preload_gen: AtomicU64::new(0),
}
}
/// Silent, thread-free audio engine for deterministic headless visual tests.
pub fn new_headless(volume: f32, muted: bool, eq_enabled: bool, eq_bands: [f32; 10]) -> Self {
let state = Arc::new(SharedAudioState::new(
volume, muted, eq_enabled, eq_bands, true, 0.0,
volume, muted, eq_enabled, eq_bands, true, false, 0.0,
));
let (tx_cmd, _rx_cmd) = unbounded();
Self { tx_cmd, state }
Self {
tx_cmd,
state,
preload_gen: AtomicU64::new(0),
}
}
pub fn load_stream(
@ -190,7 +219,10 @@ impl AudioEngine {
duration_ms: u64,
r128_i: Option<f32>,
r128_tp: Option<f32>,
fade: Option<TrackFade>,
) {
self.preload_gen.fetch_add(1, Ordering::SeqCst);
*self.state.crossfaded_track_id.lock() = None;
let seek_seq = {
let _guard = self.state.position_lock.lock();
let seq = self.state.seek_seq.fetch_add(1, Ordering::SeqCst) + 1;
@ -218,10 +250,39 @@ impl AudioEngine {
duration_ms,
r128_i,
r128_tp,
fade,
seek_seq,
});
}
pub fn preload_next(
&self,
track_id: String,
stream: ResolvedStream,
duration_ms: u64,
r128_i: Option<f32>,
r128_tp: Option<f32>,
fade: Option<TrackFade>,
) {
let gen = self.preload_gen.fetch_add(1, Ordering::SeqCst) + 1;
let _ = self.tx_cmd.send(AudioCommand::PreloadNext {
track_id,
stream,
duration_ms,
r128_i,
r128_tp,
fade,
preload_gen: gen,
});
}
pub fn clear_preload(&self) {
let gen = self.preload_gen.fetch_add(1, Ordering::SeqCst) + 1;
let _ = self
.tx_cmd
.send(AudioCommand::ClearPreload { preload_gen: gen });
}
pub fn play(&self) {
self.state.is_playing.store(true, Ordering::SeqCst);
let _ = self.tx_cmd.send(AudioCommand::Play);
@ -243,6 +304,8 @@ impl AudioEngine {
}
pub fn stop(&self) {
self.preload_gen.fetch_add(1, Ordering::SeqCst);
*self.state.crossfaded_track_id.lock() = None;
let seek_seq = {
let _guard = self.state.position_lock.lock();
let seq = self.state.seek_seq.fetch_add(1, Ordering::SeqCst) + 1;
@ -285,6 +348,10 @@ impl AudioEngine {
}
}
pub fn set_crossfade_enabled(&self, enabled: bool) {
self.state.crossfade_enabled.store(enabled, Ordering::Relaxed);
}
pub fn set_crossfade_secs(&self, secs: f32) {
self.state
.crossfade_secs_bits
@ -299,6 +366,10 @@ impl AudioEngine {
pub fn take_track_finished(&self) -> bool {
self.state.track_finished.swap(false, Ordering::SeqCst)
}
pub fn take_crossfaded_track_id(&self) -> Option<String> {
self.state.crossfaded_track_id.lock().take()
}
}
// =============================================================================
@ -437,6 +508,20 @@ struct ActiveStreamDecoder {
min_report_frames: u64,
total_frames: u64,
eof: bool,
meta_track_id: String,
duration_ms: u64,
codec_label: String,
r128_i: Option<f32>,
r128_tp: Option<f32>,
gain_applied: bool,
fade: Option<TrackFade>,
fade_in_window: Option<(u64, u64)>,
}
struct OutgoingCrossfade {
dec: ActiveStreamDecoder,
start_frame: u64,
stop_frame: u64,
}
impl ActiveStreamDecoder {
@ -734,9 +819,115 @@ fn open_streaming_decoder(
min_report_frames: 0,
total_frames,
eof: false,
meta_track_id: String::new(),
duration_ms: fallback_duration_ms,
codec_label: format!("{} {} kbps", stream.codec_label, stream.bitrate_kbps),
r128_i: None,
r128_tp: None,
gain_applied: stream.gain_applied,
fade: None,
fade_in_window: None,
})
}
#[inline]
fn deck_gain(dec: &ActiveStreamDecoder, normalize: bool) -> f32 {
compute_r128_gain(normalize, dec.gain_applied, dec.r128_i, dec.r128_tp)
}
#[inline]
fn fade_out_gain(t: f32) -> f32 {
(t.clamp(0.0, 1.0) * std::f32::consts::FRAC_PI_2).cos()
}
#[inline]
fn fade_in_gain(t: f32) -> f32 {
(t.clamp(0.0, 1.0) * std::f32::consts::FRAC_PI_2).sin()
}
pub(crate) fn compute_crossfade_out_window(
fade: Option<TrackFade>,
total_frames: u64,
device_rate: u32,
crossfade_enabled: bool,
crossfade_secs: f32,
) -> Option<(u64, u64)> {
let rate = device_rate.max(1) as u64;
if !crossfade_enabled || total_frames < rate * 4 {
return None;
}
if crossfade_secs > 0.1 {
let cf = ((crossfade_secs.clamp(0.5, 12.0) * rate as f32) as u64).min(total_frames / 3);
return Some((total_frames.saturating_sub(cf), total_frames));
}
if let Some(f) = fade.filter(|f| f.is_valid()) {
let min_start = total_frames / 2;
let out_start = ((f.out_start * rate as f32) as u64).clamp(min_start, total_frames);
let mut out_stop = ((f.out_stop * rate as f32) as u64).clamp(out_start, total_frames);
let min_dur = rate / 2;
let max_dur = rate * 12;
if out_stop.saturating_sub(out_start) < min_dur {
out_stop = (out_start + min_dur).min(total_frames);
}
if out_stop.saturating_sub(out_start) > max_dur {
out_stop = (out_start + max_dur).min(total_frames);
}
if out_stop > out_start + 100 {
return Some((out_start, out_stop));
}
}
let cf = ((3.5 * rate as f32) as u64).min(total_frames / 3);
Some((total_frames.saturating_sub(cf), total_frames))
}
pub(crate) fn compute_crossfade_in_window(
fade: Option<TrackFade>,
total_frames: u64,
device_rate: u32,
crossfade_enabled: bool,
crossfade_secs: f32,
) -> Option<(u64, u64)> {
let rate = device_rate.max(1) as u64;
if !crossfade_enabled || total_frames < rate * 4 {
return None;
}
if crossfade_secs > 0.1 {
let cf = ((crossfade_secs.clamp(0.5, 12.0) * rate as f32) as u64).min(total_frames / 3);
return Some((0, cf));
}
if let Some(f) = fade.filter(|f| f.is_valid()) {
let in_start = ((f.in_start * rate as f32) as u64).min(total_frames / 3);
let mut in_stop = ((f.in_stop * rate as f32) as u64).clamp(in_start, total_frames / 2);
let min_dur = rate / 2;
let max_dur = rate * 12;
if in_stop.saturating_sub(in_start) < min_dur {
in_stop = (in_start + rate * 3).min(total_frames / 2);
}
if in_stop.saturating_sub(in_start) > max_dur {
in_stop = (in_start + max_dur).min(total_frames / 2);
}
if in_stop > in_start + 100 {
return Some((in_start, in_stop));
}
}
let cf = ((3.5 * rate as f32) as u64).min(total_frames / 3);
Some((0, cf))
}
fn next_stereo_frame(dec: &mut ActiveStreamDecoder) -> Option<(f32, f32)> {
if dec.pending_idx + 1 >= dec.pending.len() && !dec.decode_next_packet() {
return None;
}
if dec.pending_idx + 1 >= dec.pending.len() {
return None;
}
let l = dec.pending[dec.pending_idx];
let r = dec.pending[dec.pending_idx + 1];
dec.pending_idx += 2;
dec.played_frames += 1;
Some((l, r))
}
/// Atomically publish decoder playback position ONLY if no newer `seek_ms` / `load_stream` / `stop`
/// has occurred since `applied_seek_seq`. Prevents stale decoder frames from teleporting the seek bar
/// back to the pre-seek position!
@ -831,8 +1022,7 @@ fn run_audio_worker(rx_cmd: Receiver<AudioCommand>, state: Arc<SharedAudioState>
0.0
}
};
let track_gain = state_cb.track_gain();
let gain = vol * track_gain;
let gain = vol;
let eq_on = state_cb.eq_enabled.load(Ordering::Relaxed);
if let Some(bands) = state_cb.eq_bands.try_lock() {
@ -898,10 +1088,25 @@ fn run_audio_worker(rx_cmd: Receiver<AudioCommand>, state: Arc<SharedAudioState>
.ok();
let mut active: Option<ActiveStreamDecoder> = None;
let mut outgoing: Option<OutgoingCrossfade> = None;
let mut preloaded: Option<ActiveStreamDecoder> = None;
let mut latest_preload_gen: u64 = 0;
let (tx_preloaded, rx_preloaded) =
crossbeam_channel::unbounded::<(u64, ActiveStreamDecoder)>();
let mut applied_seek_seq: u64 = 0;
let mut flush_wait_iters: u8 = 0;
loop {
while let Ok((gen, dec)) = rx_preloaded.try_recv() {
if gen == latest_preload_gen {
if let Some(old) = preloaded.replace(dec) {
old.abort();
}
} else {
dec.abort();
}
}
let mut raw_cmds = Vec::new();
while let Ok(cmd) = rx_cmd.try_recv() {
raw_cmds.push(cmd);
@ -911,15 +1116,24 @@ fn run_audio_worker(rx_cmd: Receiver<AudioCommand>, state: Arc<SharedAudioState>
for cmd in non_seeks {
match cmd {
AudioCommand::LoadStream {
track_id,
stream,
duration_ms,
r128_i,
r128_tp,
fade,
..
} => {
if let Some(old) = active.take() {
old.abort();
}
if let Some(old_out) = outgoing.take() {
old_out.dec.abort();
}
if let Some(old_pre) = preloaded.take() {
old_pre.abort();
}
latest_preload_gen = latest_preload_gen.wrapping_add(1);
flush_rb.store(true, Ordering::Release);
flush_wait_iters = 0;
state.is_buffering.store(true, Ordering::SeqCst);
@ -935,13 +1149,18 @@ fn run_audio_worker(rx_cmd: Receiver<AudioCommand>, state: Arc<SharedAudioState>
if let Some(ref rt) = rt {
match open_streaming_decoder(rt.handle(), &stream, device_rate, duration_ms)
{
Ok(dec) => {
Ok(mut dec) => {
if dec.total_frames > device_rate as u64 {
let ms = (dec.total_frames * 1000) / device_rate as u64;
state.duration_ms.store(ms, Ordering::SeqCst);
} else {
state.duration_ms.store(duration_ms, Ordering::SeqCst);
}
dec.meta_track_id = track_id;
dec.duration_ms = duration_ms;
dec.r128_i = r128_i;
dec.r128_tp = r128_tp;
dec.fade = fade;
active = Some(dec);
state.is_playing.store(true, Ordering::SeqCst);
}
@ -955,6 +1174,42 @@ fn run_audio_worker(rx_cmd: Receiver<AudioCommand>, state: Arc<SharedAudioState>
}
state.is_buffering.store(false, Ordering::SeqCst);
}
AudioCommand::PreloadNext {
track_id,
stream,
duration_ms,
r128_i,
r128_tp,
fade,
preload_gen,
} => {
latest_preload_gen = preload_gen;
if let Some(old_pre) = preloaded.take() {
old_pre.abort();
}
if let Some(ref rt) = rt {
let handle = rt.handle().clone();
let tx_p = tx_preloaded.clone();
rt.spawn_blocking(move || {
if let Ok(mut dec) =
open_streaming_decoder(&handle, &stream, device_rate, duration_ms)
{
dec.meta_track_id = track_id;
dec.duration_ms = duration_ms;
dec.r128_i = r128_i;
dec.r128_tp = r128_tp;
dec.fade = fade;
let _ = tx_p.send((preload_gen, dec));
}
});
}
}
AudioCommand::ClearPreload { preload_gen } => {
latest_preload_gen = preload_gen;
if let Some(old_pre) = preloaded.take() {
old_pre.abort();
}
}
AudioCommand::Play => {
state.is_playing.store(true, Ordering::SeqCst);
}
@ -966,6 +1221,13 @@ fn run_audio_worker(rx_cmd: Receiver<AudioCommand>, state: Arc<SharedAudioState>
if let Some(old) = active.take() {
old.abort();
}
if let Some(old_out) = outgoing.take() {
old_out.dec.abort();
}
if let Some(old_pre) = preloaded.take() {
old_pre.abort();
}
latest_preload_gen = latest_preload_gen.wrapping_add(1);
flush_rb.store(true, Ordering::Release);
flush_wait_iters = 0;
}
@ -976,7 +1238,11 @@ fn run_audio_worker(rx_cmd: Receiver<AudioCommand>, state: Arc<SharedAudioState>
if let Some((ms, seq)) = pending_seek {
flush_rb.store(true, Ordering::Release);
flush_wait_iters = 0;
if let Some(old_out) = outgoing.take() {
old_out.dec.abort();
}
if let Some(ref mut dec) = active {
dec.fade_in_window = None;
if dec.seek_ms(ms) {
dec.played_frames = (ms * device_rate as u64) / 1000;
dec.min_report_frames = dec.played_frames;
@ -1003,38 +1269,150 @@ fn run_audio_worker(rx_cmd: Receiver<AudioCommand>, state: Arc<SharedAudioState>
}
let mut pushed_any = false;
if let Some(ref mut dec) = active {
let cf_frames = (state.crossfade_secs() * device_rate as f32) as u64;
let cf_enabled = state.crossfade_enabled.load(Ordering::Relaxed);
let cf_secs = state.crossfade_secs();
let normalize = state.normalize_loudness.load(Ordering::Relaxed);
if active.is_some() {
while prod.vacant_len() >= 2048 {
// Bail immediately if a newer seek/load/stop arrived so we don't decode stale audio.
if applied_seek_seq != state.seek_seq.load(Ordering::Acquire) {
break;
}
if dec.pending_idx >= dec.pending.len() && !dec.decode_next_packet() {
break;
// Trigger overlapping crossfade if preloaded next deck is ready and we reached out_start
let should_crossfade = {
let dec = active.as_ref().unwrap();
preloaded.is_some()
&& outgoing.is_none()
&& compute_crossfade_out_window(
dec.fade,
dec.total_frames,
device_rate,
cf_enabled,
cf_secs,
)
.map_or(false, |(out_start, _)| dec.played_frames >= out_start)
};
if should_crossfade {
let old_dec = active.take().unwrap();
let (out_start, out_stop) = compute_crossfade_out_window(
old_dec.fade,
old_dec.total_frames,
device_rate,
cf_enabled,
cf_secs,
)
.unwrap_or((old_dec.played_frames, old_dec.total_frames));
let mut next_dec = preloaded.take().unwrap();
if let Some((in_start, in_stop)) = compute_crossfade_in_window(
next_dec.fade,
next_dec.total_frames,
device_rate,
cf_enabled,
cf_secs,
) {
if in_start > device_rate as u64 / 20 {
let seek_ms = (in_start * 1000) / device_rate as u64;
if next_dec.seek_ms(seek_ms) {
next_dec.played_frames = in_start;
next_dec.min_report_frames = in_start;
}
}
next_dec.fade_in_window = Some((in_start, in_stop));
}
let new_tid = next_dec.meta_track_id.clone();
let new_dur = if next_dec.total_frames > device_rate as u64 {
(next_dec.total_frames * 1000) / device_rate as u64
} else {
next_dec.duration_ms
};
state.duration_ms.store(new_dur, Ordering::SeqCst);
*state.active_codec.lock() = next_dec.codec_label.clone();
let new_pos_ms = (next_dec.played_frames * 1000) / device_rate as u64;
publish_decoder_position_ms(&state, applied_seek_seq, new_pos_ms);
*state.crossfaded_track_id.lock() = Some(new_tid);
outgoing = Some(OutgoingCrossfade {
dec: old_dec,
start_frame: out_start,
stop_frame: out_stop.max(out_start + 1),
});
active = Some(next_dec);
}
let avail = (dec.pending.len() - dec.pending_idx).min(2048) & !1;
if avail == 0 {
break;
}
for pair in dec.pending[dec.pending_idx..dec.pending_idx + avail].chunks_exact(2) {
// Smooth crossfade envelope (fade-in at start, fade-out near end when enabled)
let mut env = 1.0_f32;
if cf_frames > 0 {
if dec.played_frames < cf_frames {
env = (dec.played_frames as f32 / cf_frames as f32).clamp(0.0, 1.0);
} else if dec.total_frames > cf_frames
&& dec.played_frames + cf_frames > dec.total_frames
{
let rem = dec.total_frames.saturating_sub(dec.played_frames);
env = (rem as f32 / cf_frames as f32).clamp(0.0, 1.0);
// Decode up to 1024 stereo frames from active + optional outgoing crossfade deck
let mut frames_mixed = 0usize;
while frames_mixed < 1024 {
let dec = active.as_mut().unwrap();
let Some((al, ar)) = next_stereo_frame(dec) else {
break;
};
let mut in_gain = deck_gain(dec, normalize);
if let Some((in_start, in_stop)) = dec.fade_in_window {
let span = in_stop.saturating_sub(in_start).max(1) as f32;
let prog = (dec.played_frames.saturating_sub(in_start) as f32) / span;
in_gain *= fade_in_gain(prog);
if dec.played_frames >= in_stop {
dec.fade_in_window = None;
}
}
let _ = prod.try_push(pair[0] * env);
let _ = prod.try_push(pair[1] * env);
dec.played_frames += 1;
let mut mix_l = al * in_gain;
let mut mix_r = ar * in_gain;
if let Some(ref mut out) = outgoing {
if let Some((ol, or)) = next_stereo_frame(&mut out.dec) {
let span = out.stop_frame.saturating_sub(out.start_frame).max(1) as f32;
let prog = (out.dec.played_frames.saturating_sub(out.start_frame) as f32)
/ span;
let og = deck_gain(&out.dec, normalize) * fade_out_gain(prog);
mix_l = (mix_l + ol * og).clamp(-1.0, 1.0);
mix_r = (mix_r + or * og).clamp(-1.0, 1.0);
if out.dec.played_frames >= out.stop_frame {
if let Some(done) = outgoing.take() {
done.dec.abort();
}
}
} else if let Some(done) = outgoing.take() {
done.dec.abort();
}
}
let _ = prod.try_push(mix_l);
let _ = prod.try_push(mix_r);
frames_mixed += 1;
}
dec.pending_idx += avail;
if frames_mixed == 0 {
// Gapless handoff if active reached EOF and next track is preloaded!
let dec_eof = active.as_ref().map_or(false, |d| d.eof && d.pending_idx >= d.pending.len());
if dec_eof {
if let Some(mut next_dec) = preloaded.take() {
if let Some(old_done) = active.take() {
old_done.abort();
}
let new_tid = next_dec.meta_track_id.clone();
let new_dur = if next_dec.total_frames > device_rate as u64 {
(next_dec.total_frames * 1000) / device_rate as u64
} else {
next_dec.duration_ms
};
next_dec.fade_in_window = None;
state.duration_ms.store(new_dur, Ordering::SeqCst);
*state.active_codec.lock() = next_dec.codec_label.clone();
publish_decoder_position_ms(&state, applied_seek_seq, 0);
*state.crossfaded_track_id.lock() = Some(new_tid);
active = Some(next_dec);
continue;
}
}
break;
}
let dec = active.as_ref().unwrap();
let buffered_frames = if _cpal_stream.is_some() {
(prod.occupied_len() / 2) as u64
} else {
@ -1049,24 +1427,29 @@ fn run_audio_worker(rx_cmd: Receiver<AudioCommand>, state: Arc<SharedAudioState>
pushed_any = true;
}
// Keep audible playback position smoothly updating while CPAL drains the ring buffer.
if !pushed_any && _cpal_stream.is_some() && !flush_rb.load(Ordering::Acquire) {
let buffered_frames = (prod.occupied_len() / 2) as u64;
let audible_frames = dec
.played_frames
.saturating_sub(buffered_frames)
.max(dec.min_report_frames);
let pos_ms = (audible_frames * 1000) / device_rate as u64;
publish_decoder_position_ms(&state, applied_seek_seq, pos_ms);
if let Some(ref dec) = active {
let buffered_frames = (prod.occupied_len() / 2) as u64;
let audible_frames = dec
.played_frames
.saturating_sub(buffered_frames)
.max(dec.min_report_frames);
let pos_ms = (audible_frames * 1000) / device_rate as u64;
publish_decoder_position_ms(&state, applied_seek_seq, pos_ms);
}
}
if dec.eof
&& dec.pending_idx >= dec.pending.len()
&& applied_seek_seq == state.seek_seq.load(Ordering::Acquire)
{
if active.as_ref().map_or(false, |dec| {
dec.eof
&& dec.pending_idx >= dec.pending.len()
&& applied_seek_seq == state.seek_seq.load(Ordering::Acquire)
}) {
state.is_playing.store(false, Ordering::SeqCst);
state.track_finished.store(true, Ordering::SeqCst);
active = None;
if let Some(old_out) = outgoing.take() {
old_out.dec.abort();
}
}
}
@ -1149,4 +1532,36 @@ mod tests {
assert!(!publish_decoder_position_ms(&engine.state, 0, 45_200));
assert_eq!(engine.state.position_ms.load(Ordering::Acquire), 0);
}
#[test]
fn test_crossfade_windows_and_equal_power_curves() {
let rate = 48_000u32;
let total = 200 * rate as u64;
let smart = TrackFade {
in_start: 0.5,
in_stop: 4.5,
out_start: 194.0,
out_stop: 199.0,
};
assert_eq!(
compute_crossfade_out_window(Some(smart), total, rate, false, 0.0),
None
);
let out_auto = compute_crossfade_out_window(Some(smart), total, rate, true, 0.0).unwrap();
assert_eq!(out_auto, (194 * rate as u64, 199 * rate as u64));
let in_auto = compute_crossfade_in_window(Some(smart), total, rate, true, 0.0).unwrap();
assert_eq!(in_auto, (rate as u64 / 2, (4.5 * rate as f32) as u64));
// Fallback when track has no `fade` metadata
let out_fb = compute_crossfade_out_window(None, total, rate, true, 0.0).unwrap();
assert_eq!(out_fb.1 - out_fb.0, (3.5 * rate as f32) as u64);
// Manual duration override
let out_man = compute_crossfade_out_window(Some(smart), total, rate, true, 6.0).unwrap();
assert_eq!(out_man.1 - out_man.0, 6 * rate as u64);
// Equal-power crossfade preserves constant power at midpoint (0.5^2 + 0.5^2 -> 1.0)
let p_mid = fade_out_gain(0.5).powi(2) + fade_in_gain(0.5).powi(2);
assert!((p_mid - 1.0).abs() < 1e-5);
}
}