yandex-music-rs/src/audio/mod.rs

1583 lines
58 KiB
Rust

pub mod dsp;
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
use crossbeam_channel::{unbounded, Receiver, Sender};
use parking_lot::{Condvar, Mutex};
use ringbuf::traits::{Consumer, Observer, Producer, Split};
use ringbuf::HeapRb;
use std::io::{self, Read, Seek, SeekFrom};
use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
use std::sync::Arc;
use symphonia::core::audio::SampleBuffer;
use symphonia::core::codecs::{Decoder, DecoderOptions};
use symphonia::core::formats::{FormatOptions, FormatReader, SeekMode, SeekTo};
use symphonia::core::io::{MediaSource, MediaSourceStream};
use symphonia::core::meta::MetadataOptions;
use symphonia::core::probe::Hint;
use symphonia::core::units::Time;
use crate::api::models::{ResolvedStream, TrackFade};
use crate::api::signing::decrypt_encraw_at_offset;
use dsp::{AudioEnergyAnalyzer, Equalizer10Band};
/// Target integrated loudness matching Yandex Music / EBU R128 streaming standard (-14 LUFS)
const TARGET_LOUDNESS_LUFS: f32 = -14.0;
#[derive(Debug, Clone)]
pub enum AudioCommand {
LoadStream {
track_id: String,
stream: ResolvedStream,
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 {
seek_seq: u64,
},
SeekMs(u64, u64),
}
pub struct SharedAudioState {
pub is_playing: AtomicBool,
pub is_buffering: AtomicBool,
pub track_finished: AtomicBool,
pub position_ms: AtomicU64,
pub seek_seq: AtomicU64,
position_lock: Mutex<()>,
pub duration_ms: AtomicU64,
pub volume_bits: AtomicU32,
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,
pub eq_enabled: AtomicBool,
pub eq_preamp_bits: AtomicU32,
pub eq_bands: Mutex<[f32; 10]>,
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 {
fn new(
volume: f32,
muted: bool,
eq_enabled: bool,
eq_preamp: f32,
eq_bands: [f32; 10],
normalize_loudness: bool,
crossfade_enabled: bool,
crossfade_secs: f32,
) -> Self {
Self {
is_playing: AtomicBool::new(false),
is_buffering: AtomicBool::new(false),
track_finished: AtomicBool::new(false),
position_ms: AtomicU64::new(0),
seek_seq: AtomicU64::new(0),
position_lock: Mutex::new(()),
duration_ms: AtomicU64::new(0),
volume_bits: AtomicU32::new(volume.to_bits()),
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()),
eq_enabled: AtomicBool::new(eq_enabled),
eq_preamp_bits: AtomicU32::new(eq_preamp.clamp(0.5, 1.5).to_bits()),
eq_bands: Mutex::new(eq_bands),
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),
}
}
pub fn volume(&self) -> f32 {
f32::from_bits(self.volume_bits.load(Ordering::Relaxed))
}
pub fn track_gain(&self) -> f32 {
f32::from_bits(self.track_gain_bits.load(Ordering::Relaxed))
}
pub fn crossfade_secs(&self) -> f32 {
f32::from_bits(self.crossfade_secs_bits.load(Ordering::Relaxed))
}
pub fn energy(&self) -> f32 {
f32::from_bits(self.energy_bits.load(Ordering::Relaxed))
}
pub fn bass(&self) -> f32 {
f32::from_bits(self.bass_bits.load(Ordering::Relaxed))
}
pub fn take_error(&self) -> Option<String> {
self.last_error.lock().take()
}
}
/// Compute EBU R128 linear gain multiplier from track loudness metadata (`r128.i`, `r128.tp`).
pub fn compute_r128_gain(
normalize_enabled: bool,
server_gain_applied: bool,
r128_i: Option<f32>,
r128_tp: Option<f32>,
) -> f32 {
if !normalize_enabled || server_gain_applied {
return 1.0;
}
let Some(integrated) = r128_i else {
return 1.0;
};
let mut gain_db = (TARGET_LOUDNESS_LUFS - integrated).clamp(-12.0, 6.0);
// True-peak ceiling protection at -1.0 dBTP to avoid digital clipping
if let Some(tp) = r128_tp {
gain_db = gain_db.min(-1.0 - tp);
}
10.0_f32.powf(gain_db / 20.0).clamp(0.15, 2.0)
}
pub struct AudioEngine {
tx_cmd: Sender<AudioCommand>,
pub state: Arc<SharedAudioState>,
preload_gen: AtomicU64,
}
impl AudioEngine {
pub fn new(
volume: f32,
muted: bool,
eq_enabled: bool,
eq_preamp: f32,
eq_bands: [f32; 10],
normalize_loudness: bool,
crossfade_enabled: bool,
crossfade_secs: f32,
) -> Self {
let state = Arc::new(SharedAudioState::new(
volume,
muted,
eq_enabled,
eq_preamp,
eq_bands,
normalize_loudness,
crossfade_enabled,
crossfade_secs,
));
let (tx_cmd, rx_cmd) = unbounded();
let state_bg = Arc::clone(&state);
std::thread::Builder::new()
.name("ym-audio-engine".into())
.spawn(move || run_audio_worker(rx_cmd, state_bg))
.expect("Failed to spawn audio thread");
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_preamp: f32,
eq_bands: [f32; 10],
) -> Self {
let state = Arc::new(SharedAudioState::new(
volume, muted, eq_enabled, eq_preamp, eq_bands, true, false, 0.0,
));
let (tx_cmd, _rx_cmd) = unbounded();
Self {
tx_cmd,
state,
preload_gen: AtomicU64::new(0),
}
}
pub fn load_stream(
&self,
track_id: String,
stream: ResolvedStream,
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;
self.state.position_ms.store(0, Ordering::SeqCst);
seq
};
self.state.track_finished.store(false, Ordering::SeqCst);
self.state.is_buffering.store(true, Ordering::SeqCst);
self.state.duration_ms.store(duration_ms, Ordering::SeqCst);
*self.state.last_error.lock() = None;
*self.state.active_codec.lock() =
format!("{} {} kbps", stream.codec_label, stream.bitrate_kbps);
let gain = compute_r128_gain(
self.state.normalize_loudness.load(Ordering::Relaxed),
stream.gain_applied,
r128_i,
r128_tp,
);
self.state
.track_gain_bits
.store(gain.to_bits(), Ordering::Relaxed);
let _ = self.tx_cmd.send(AudioCommand::LoadStream {
track_id,
stream,
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);
}
pub fn pause(&self) {
self.state.is_playing.store(false, Ordering::SeqCst);
let _ = self.tx_cmd.send(AudioCommand::Pause);
}
pub fn toggle_play(&self) -> bool {
let next = !self.state.is_playing.load(Ordering::SeqCst);
if next {
self.play();
} else {
self.pause();
}
next
}
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;
self.state.position_ms.store(0, Ordering::SeqCst);
seq
};
self.state.is_playing.store(false, Ordering::SeqCst);
self.state.is_buffering.store(false, Ordering::SeqCst);
let _ = self.tx_cmd.send(AudioCommand::Stop { seek_seq });
}
pub fn seek_ms(&self, ms: u64) {
let seq = {
let _guard = self.state.position_lock.lock();
let seq = self.state.seek_seq.fetch_add(1, Ordering::SeqCst) + 1;
self.state.position_ms.store(ms, Ordering::SeqCst);
seq
};
let _ = self.tx_cmd.send(AudioCommand::SeekMs(ms, seq));
}
pub fn set_volume(&self, vol: f32) {
self.state
.volume_bits
.store(vol.clamp(0.0, 1.0).to_bits(), Ordering::Relaxed);
}
pub fn set_muted(&self, muted: bool) {
self.state.muted.store(muted, Ordering::Relaxed);
}
pub fn set_normalize_loudness(&self, enabled: bool) {
self.state
.normalize_loudness
.store(enabled, Ordering::Relaxed);
if !enabled {
self.state
.track_gain_bits
.store(1.0f32.to_bits(), Ordering::Relaxed);
}
}
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
.store(secs.clamp(0.0, 12.0).to_bits(), Ordering::Relaxed);
}
pub fn set_eq(&self, enabled: bool, preamp: f32, bands: [f32; 10]) {
self.state.eq_enabled.store(enabled, Ordering::Relaxed);
self.state
.eq_preamp_bits
.store(preamp.clamp(0.5, 1.5).to_bits(), Ordering::Relaxed);
*self.state.eq_bands.lock() = bands;
}
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()
}
}
// =============================================================================
// Progressive HTTP Streaming + Chunked AES-128-CTR (`encraw`) MediaSource
// =============================================================================
struct StreamInner {
data: Vec<u8>,
total_len: Option<u64>,
finished: bool,
aborted: bool,
error: Option<String>,
}
struct SharedStream {
inner: Mutex<StreamInner>,
cv: Condvar,
}
impl SharedStream {
fn new() -> Arc<Self> {
Arc::new(Self {
inner: Mutex::new(StreamInner {
data: Vec::with_capacity(256 * 1024),
total_len: None,
finished: false,
aborted: false,
error: None,
}),
cv: Condvar::new(),
})
}
fn abort(&self) {
let mut g = self.inner.lock();
g.aborted = true;
self.cv.notify_all();
}
}
struct StreamingMediaSource {
shared: Arc<SharedStream>,
pos: u64,
}
impl Read for StreamingMediaSource {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
if buf.is_empty() {
return Ok(0);
}
let mut g = self.shared.inner.lock();
loop {
if g.aborted {
return Err(io::Error::new(io::ErrorKind::Interrupted, "Stream aborted"));
}
let pos = self.pos as usize;
if pos < g.data.len() {
let avail = (g.data.len() - pos).min(buf.len());
buf[..avail].copy_from_slice(&g.data[pos..pos + avail]);
self.pos += avail as u64;
return Ok(avail);
}
if let Some(ref err) = g.error {
return Err(io::Error::new(io::ErrorKind::Other, err.clone()));
}
if g.finished {
return Ok(0); // EOF
}
self.shared.cv.wait(&mut g);
}
}
}
impl Seek for StreamingMediaSource {
fn seek(&mut self, style: SeekFrom) -> io::Result<u64> {
let mut g = self.shared.inner.lock();
let new_pos: i64 = match style {
SeekFrom::Start(p) => p as i64,
SeekFrom::Current(delta) => self.pos as i64 + delta,
SeekFrom::End(delta) => {
// Wait for total_len or completion if seeking relative to end
while g.total_len.is_none() && !g.finished && !g.aborted && g.error.is_none() {
self.shared.cv.wait(&mut g);
}
if g.aborted {
return Err(io::Error::new(io::ErrorKind::Interrupted, "Stream aborted"));
}
let len = g.total_len.unwrap_or(g.data.len() as u64) as i64;
len + delta
}
};
if new_pos < 0 {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"Negative seek position",
));
}
self.pos = new_pos as u64;
Ok(self.pos)
}
}
impl MediaSource for StreamingMediaSource {
fn is_seekable(&self) -> bool {
true
}
fn byte_len(&self) -> Option<u64> {
let g = self.shared.inner.lock();
g.total_len.or_else(|| {
if g.finished {
Some(g.data.len() as u64)
} else {
None
}
})
}
}
/// Active incremental Symphonia streaming decoder (zero full-track PCM allocation!)
struct ActiveStreamDecoder {
shared: Arc<SharedStream>,
format: Box<dyn FormatReader>,
decoder: Box<dyn Decoder>,
track_id: u32,
src_rate: u32,
dst_rate: u32,
sample_buf: Option<SampleBuffer<f32>>,
/// Small leftover resampled stereo buffer (at most 1 packet, a few KB)
pending: Vec<f32>,
pending_idx: usize,
resample_phase: f64,
prev_l: f32,
prev_r: f32,
played_frames: u64,
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 {
fn abort(&self) {
self.shared.abort();
}
/// Decode next packet and append resampled stereo samples to `self.pending`.
fn decode_next_packet(&mut self) -> bool {
if self.eof {
return false;
}
self.pending.clear();
self.pending_idx = 0;
loop {
match self.format.next_packet() {
Ok(packet) => {
if packet.track_id() != self.track_id {
continue;
}
let decoded = match self.decoder.decode(&packet) {
Ok(d) => d,
Err(symphonia::core::errors::Error::DecodeError(_)) => continue,
Err(_) => {
self.eof = true;
return false;
}
};
let spec = *decoded.spec();
if spec.rate > 0 {
self.src_rate = spec.rate;
}
let channels = spec.channels.count();
let buf = self.sample_buf.get_or_insert_with(|| {
SampleBuffer::<f32>::new(decoded.capacity() as u64, spec)
});
if buf.capacity() < decoded.capacity() {
*buf = SampleBuffer::<f32>::new(decoded.capacity() as u64, spec);
}
buf.copy_interleaved_ref(decoded);
let samples = buf.samples();
if samples.is_empty() {
continue;
}
// Convert to interleaved stereo f32 and resample on-the-fly if needed
if self.src_rate == self.dst_rate {
if channels == 2 {
self.pending.extend_from_slice(samples);
} else if channels == 1 {
self.pending.reserve(samples.len() * 2);
for &s in samples {
self.pending.push(s);
self.pending.push(s);
}
} else {
for frame in samples.chunks_exact(channels) {
self.pending.push(frame[0]);
self.pending.push(frame[1]);
}
}
} else {
let src_frames = samples.len() / channels.max(1);
let step = self.src_rate as f64 / self.dst_rate as f64;
let est = ((src_frames as f64 / step).ceil() as usize + 4) * 2;
self.pending.reserve(est);
let sample_lr = |idx: usize| -> (f32, f32) {
if channels == 1 {
let v = samples[idx];
(v, v)
} else {
(samples[idx * channels], samples[idx * channels + 1])
}
};
while self.resample_phase < src_frames as f64 {
let i0 = self.resample_phase.floor() as isize;
let frac = (self.resample_phase - i0 as f64) as f32;
let (l0, r0) = if i0 < 0 {
(self.prev_l, self.prev_r)
} else {
sample_lr((i0 as usize).min(src_frames - 1))
};
let (l1, r1) = sample_lr(((i0 + 1).max(0) as usize).min(src_frames - 1));
self.pending.push(l0 + (l1 - l0) * frac);
self.pending.push(r0 + (r1 - r0) * frac);
self.resample_phase += step;
}
if src_frames > 0 {
let (ll, lr) = sample_lr(src_frames - 1);
self.prev_l = ll;
self.prev_r = lr;
}
self.resample_phase -= src_frames as f64;
}
return !self.pending.is_empty();
}
Err(symphonia::core::errors::Error::IoError(ref e))
if e.kind() == io::ErrorKind::UnexpectedEof =>
{
self.eof = true;
return false;
}
Err(_) => {
self.eof = true;
return false;
}
}
}
}
fn seek_ms(&mut self, ms: u64) -> bool {
let secs = ms / 1000;
let frac = (ms % 1000) as f64 / 1000.0;
let target = Time::new(secs, frac);
if self
.format
.seek(
SeekMode::Coarse,
SeekTo::Time {
time: target,
track_id: Some(self.track_id),
},
)
.is_ok()
{
self.decoder.reset();
self.pending.clear();
self.pending_idx = 0;
self.resample_phase = 0.0;
self.played_frames = (ms * self.dst_rate as u64) / 1000;
self.min_report_frames = self.played_frames;
self.eof = false;
true
} else {
false
}
}
}
fn open_streaming_decoder(
rt_handle: &tokio::runtime::Handle,
stream: &ResolvedStream,
device_rate: u32,
fallback_duration_ms: u64,
) -> anyhow::Result<ActiveStreamDecoder> {
let shared = SharedStream::new();
let shared_dl = Arc::clone(&shared);
let url = stream.url.clone();
let key_hex = stream.decrypt_key_hex.clone();
if let Some(local_path) = url.strip_prefix("file://") {
// Local offline cached audio file — read directly from disk with zero network latency!
let bytes = std::fs::read(local_path)?;
let len = bytes.len() as u64;
{
let mut g = shared.inner.lock();
g.data = bytes;
g.total_len = Some(len);
g.finished = true;
shared.cv.notify_all();
}
} else {
// Progressive chunked HTTP download + on-the-fly AES-128-CTR (`encraw`) decryption!
rt_handle.spawn(async move {
let client = match reqwest::Client::builder()
.timeout(std::time::Duration::from_secs(60))
.build()
{
Ok(c) => c,
Err(e) => {
let mut g = shared_dl.inner.lock();
g.error = Some(e.to_string());
shared_dl.cv.notify_all();
return;
}
};
let mut resp = match client.get(&url).send().await {
Ok(r) if r.status().is_success() => r,
Ok(r) => {
let mut g = shared_dl.inner.lock();
g.error = Some(format!("Audio stream HTTP {}", r.status().as_u16()));
shared_dl.cv.notify_all();
return;
}
Err(e) => {
let mut g = shared_dl.inner.lock();
g.error = Some(e.to_string());
shared_dl.cv.notify_all();
return;
}
};
if let Some(cl) = resp.content_length() {
let mut g = shared_dl.inner.lock();
g.total_len = Some(cl);
if cl <= 64 * 1024 * 1024 {
g.data.reserve(cl as usize);
}
}
let mut byte_offset: u64 = 0;
loop {
if shared_dl.inner.lock().aborted {
return;
}
match resp.chunk().await {
Ok(Some(chunk)) => {
let mut bytes = chunk.to_vec();
if let Some(ref key) = key_hex {
decrypt_encraw_at_offset(&mut bytes, key, byte_offset);
}
byte_offset += bytes.len() as u64;
let mut g = shared_dl.inner.lock();
if g.aborted {
return;
}
g.data.extend_from_slice(&bytes);
shared_dl.cv.notify_all();
}
Ok(None) => {
let mut g = shared_dl.inner.lock();
g.total_len = Some(g.data.len() as u64);
g.finished = true;
shared_dl.cv.notify_all();
return;
}
Err(e) => {
let mut g = shared_dl.inner.lock();
g.error = Some(e.to_string());
shared_dl.cv.notify_all();
return;
}
}
}
});
}
let source = StreamingMediaSource {
shared: Arc::clone(&shared),
pos: 0,
};
let mss = MediaSourceStream::new(Box::new(source), Default::default());
let mut hint = Hint::new();
let lc = stream.codec_label.to_lowercase();
if lc.contains("flac") && !lc.contains("mp4") {
hint.with_extension("flac");
} else if lc.contains("mp4") || lc.contains("aac") {
hint.with_extension("m4a");
} else {
hint.with_extension("mp3");
}
let probed = symphonia::default::get_probe().format(
&hint,
mss,
&FormatOptions {
enable_gapless: true,
..Default::default()
},
&MetadataOptions::default(),
)?;
let format = probed.format;
let track = format
.default_track()
.ok_or_else(|| anyhow::anyhow!("No audio track in stream"))?;
let track_id = track.id;
let src_rate = track.codec_params.sample_rate.unwrap_or(device_rate);
let total_frames = track
.codec_params
.n_frames
.map(|n| (n * device_rate as u64) / src_rate.max(1) as u64)
.unwrap_or_else(|| (fallback_duration_ms * device_rate as u64) / 1000);
let decoder =
symphonia::default::get_codecs().make(&track.codec_params, &DecoderOptions::default())?;
Ok(ActiveStreamDecoder {
shared,
format,
decoder,
track_id,
src_rate,
dst_rate: device_rate,
sample_buf: None,
pending: Vec::new(),
pending_idx: 0,
resample_phase: 0.0,
prev_l: 0.0,
prev_r: 0.0,
played_frames: 0,
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!
fn publish_decoder_position_ms(
state: &SharedAudioState,
applied_seek_seq: u64,
pos_ms: u64,
) -> bool {
if applied_seek_seq != state.seek_seq.load(Ordering::Acquire) {
return false;
}
let _guard = state.position_lock.lock();
if applied_seek_seq != state.seek_seq.load(Ordering::Acquire) {
return false;
}
state.position_ms.store(pos_ms, Ordering::Release);
true
}
/// Coalesce a batch of queued `AudioCommand`s so consecutive `SeekMs` commands collapse to ONLY the
/// latest `(ms, seq)` and any `SeekMs` superseded by a subsequent `LoadStream` or `Stop` is dropped
/// (while advancing `applied_seek_seq` past it).
fn coalesce_command_batch(
cmds: Vec<AudioCommand>,
applied_seek_seq: &mut u64,
) -> (Vec<AudioCommand>, Option<(u64, u64)>) {
let mut non_seeks = Vec::with_capacity(cmds.len());
let mut pending_seek: Option<(u64, u64)> = None;
for cmd in cmds {
match cmd {
AudioCommand::SeekMs(ms, seq) => {
pending_seek = Some((ms, seq));
}
AudioCommand::LoadStream { seek_seq, .. } | AudioCommand::Stop { seek_seq } => {
if let Some((_, prev_seq)) = pending_seek.take() {
*applied_seek_seq = (*applied_seek_seq).max(prev_seq);
}
*applied_seek_seq = (*applied_seek_seq).max(seek_seq);
non_seeks.push(cmd);
}
other => {
non_seeks.push(other);
}
}
}
(non_seeks, pending_seek)
}
fn run_audio_worker(rx_cmd: Receiver<AudioCommand>, state: Arc<SharedAudioState>) {
// 2 seconds stereo lock-free ring buffer (~768 KB total!)
let rb = HeapRb::<f32>::new(48_000 * 2 * 2);
let (mut prod, mut cons) = rb.split();
let flush_rb = Arc::new(AtomicBool::new(false));
let flush_rb_cb = Arc::clone(&flush_rb);
let host = cpal::default_host();
let device = host.default_output_device();
let (device_rate, _cpal_stream) = if let Some(dev) = device {
if let Ok(name) = dev.name() {
*state.output_device_name.lock() = name;
}
let cfg = dev
.default_output_config()
.expect("Default audio output config");
let rate = cfg.sample_rate().0;
let channels = cfg.channels() as usize;
let state_cb = Arc::clone(&state);
let mut eq = Equalizer10Band::new(rate as f32);
let mut analyzer = AudioEnergyAnalyzer::new();
let stream = dev
.build_output_stream(
&cfg.into(),
move |data: &mut [f32], _: &cpal::OutputCallbackInfo| {
if flush_rb_cb.swap(false, Ordering::AcqRel) {
while cons.try_pop().is_some() {}
}
let playing = state_cb.is_playing.load(Ordering::Relaxed);
let muted = state_cb.muted.load(Ordering::Relaxed);
// Exact Yandex Music Desktop perceptual volume curve:
// linear = expVol > 0.01 ? 0.01^(1 - expVol) : 0.0
let vol = if muted {
0.0
} else {
let exp_vol = state_cb.volume().clamp(0.0, 1.0);
if exp_vol > 0.01 {
0.01_f32.powf(1.0 - exp_vol)
} else {
0.0
}
};
let gain = vol;
let eq_on = state_cb.eq_enabled.load(Ordering::Relaxed);
let preamp = f32::from_bits(state_cb.eq_preamp_bits.load(Ordering::Relaxed))
.clamp(0.5, 1.5);
if let Some(bands) = state_cb.eq_bands.try_lock() {
eq.update(eq_on, preamp, *bands);
}
if !playing {
for s in data.iter_mut() {
*s = 0.0;
}
analyzer.push_sample(0.0);
state_cb
.energy_bits
.store((analyzer.energy() * 0.5).to_bits(), Ordering::Relaxed);
state_cb
.bass_bits
.store((analyzer.bass() * 0.5).to_bits(), Ordering::Relaxed);
return;
}
for frame in data.chunks_mut(channels) {
let l_raw = cons.try_pop().unwrap_or(0.0);
let r_raw = cons.try_pop().unwrap_or(l_raw);
// Tap analyzer PRE-VOLUME (like Yandex Music Web Audio AnalyserNode) so Vibe orb reacts at any volume!
analyzer.push_sample((l_raw + r_raw) * 0.5);
let (l, r) = eq.process((l_raw * gain).clamp(-1.0, 1.0), (r_raw * gain).clamp(-1.0, 1.0));
if channels >= 2 {
frame[0] = l;
frame[1] = r;
for ch in frame.iter_mut().skip(2) {
*ch = 0.0;
}
} else if channels == 1 {
frame[0] = (l + r) * 0.5;
}
}
state_cb
.energy_bits
.store(analyzer.energy().to_bits(), Ordering::Relaxed);
state_cb
.bass_bits
.store(analyzer.bass().to_bits(), Ordering::Relaxed);
},
|err| log::error!("CPAL output error: {}", err),
None,
)
.ok();
if let Some(ref s) = stream {
let _ = s.play();
}
(rate, stream)
} else {
(48_000, None)
};
let rt = tokio::runtime::Builder::new_multi_thread()
.worker_threads(1)
.thread_name("ym-audio-dl")
.enable_all()
.build()
.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);
}
let (non_seeks, pending_seek) = coalesce_command_batch(raw_cmds, &mut applied_seek_seq);
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);
let gain = compute_r128_gain(
state.normalize_loudness.load(Ordering::Relaxed),
stream.gain_applied,
r128_i,
r128_tp,
);
state.track_gain_bits.store(gain.to_bits(), Ordering::Relaxed);
if let Some(ref rt) = rt {
match open_streaming_decoder(rt.handle(), &stream, device_rate, duration_ms)
{
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);
}
Err(e) => {
log::error!("Audio stream open failed: {}", e);
*state.last_error.lock() =
Some(format!("Ошибка воспроизведения: {}", e));
state.is_playing.store(false, Ordering::SeqCst);
}
}
}
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);
}
AudioCommand::Pause => {
state.is_playing.store(false, Ordering::SeqCst);
}
AudioCommand::Stop { .. } => {
state.is_playing.store(false, Ordering::SeqCst);
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;
}
AudioCommand::SeekMs(_, _) => unreachable!(),
}
}
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;
}
}
applied_seek_seq = applied_seek_seq.max(seq);
publish_decoder_position_ms(&state, applied_seek_seq, ms);
}
if !state.is_playing.load(Ordering::Relaxed) {
std::thread::sleep(std::time::Duration::from_millis(12));
continue;
}
// Wait briefly for CPAL callback to drain pre-seek samples before pushing post-seek audio.
if _cpal_stream.is_some()
&& flush_rb.load(Ordering::Acquire)
&& flush_wait_iters < 15
&& applied_seek_seq == state.seek_seq.load(Ordering::Acquire)
{
flush_wait_iters += 1;
std::thread::sleep(std::time::Duration::from_millis(2));
continue;
}
let mut pushed_any = false;
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 {
if applied_seek_seq != state.seek_seq.load(Ordering::Acquire) {
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);
}
// 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 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;
}
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 {
0
};
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);
pushed_any = true;
}
if !pushed_any && _cpal_stream.is_some() && !flush_rb.load(Ordering::Acquire) {
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 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();
}
}
}
if !pushed_any {
std::thread::sleep(std::time::Duration::from_millis(6));
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn seek_seq_prevents_stale_decoder_position_overwrite() {
let engine = AudioEngine::new_headless(0.8, false, false, 1.0, [0.0; 10]);
// Initial playback at seq 0 publishes normally.
assert!(publish_decoder_position_ms(&engine.state, 0, 30_000));
assert_eq!(engine.state.position_ms.load(Ordering::Acquire), 30_000);
// User seeks to 90s: seek_seq advances to 1 and position_ms immediately updates.
engine.seek_ms(90_000);
assert_eq!(engine.state.seek_seq.load(Ordering::Acquire), 1);
assert_eq!(engine.state.position_ms.load(Ordering::Acquire), 90_000);
// Stale decoder still on seq 0 tries to write pre-seek 30.5s — MUST be rejected!
assert!(!publish_decoder_position_ms(&engine.state, 0, 30_500));
assert_eq!(engine.state.position_ms.load(Ordering::Acquire), 90_000);
// User drags/seeks again to 120s before decoder finished seq 1: seq advances to 2.
engine.seek_ms(120_000);
assert_eq!(engine.state.seek_seq.load(Ordering::Acquire), 2);
assert_eq!(engine.state.position_ms.load(Ordering::Acquire), 120_000);
// Stale seq 1 write is also rejected!
assert!(!publish_decoder_position_ms(&engine.state, 1, 90_100));
assert_eq!(engine.state.position_ms.load(Ordering::Acquire), 120_000);
// Once decoder applies seq 2, subsequent position writes succeed.
assert!(publish_decoder_position_ms(&engine.state, 2, 120_250));
assert_eq!(engine.state.position_ms.load(Ordering::Acquire), 120_250);
}
#[test]
fn coalesce_command_batch_keeps_latest_seek_and_respects_stop() {
let mut applied = 0;
let cmds = vec![
AudioCommand::SeekMs(10_000, 1),
AudioCommand::Play,
AudioCommand::SeekMs(25_000, 2),
AudioCommand::SeekMs(75_000, 3),
];
let (non_seeks, pending) = coalesce_command_batch(cmds, &mut applied);
assert_eq!(non_seeks.len(), 1);
assert!(matches!(non_seeks[0], AudioCommand::Play));
assert_eq!(pending, Some((75_000, 3)));
assert_eq!(applied, 0);
// A Stop after queued seeks supersedes them and advances applied_seek_seq.
let cmds2 = vec![
AudioCommand::SeekMs(40_000, 4),
AudioCommand::SeekMs(55_000, 5),
AudioCommand::Stop { seek_seq: 6 },
];
let (non_seeks2, pending2) = coalesce_command_batch(cmds2, &mut applied);
assert_eq!(non_seeks2.len(), 1);
assert!(matches!(non_seeks2[0], AudioCommand::Stop { seek_seq: 6 }));
assert_eq!(pending2, None);
assert_eq!(applied, 6);
}
#[test]
fn stop_bumps_seek_seq_preventing_old_decoder_overwrite() {
let engine = AudioEngine::new_headless(0.8, false, false, 1.0, [0.0; 10]);
assert!(publish_decoder_position_ms(&engine.state, 0, 45_000));
engine.stop();
assert_eq!(engine.state.position_ms.load(Ordering::Acquire), 0);
assert_eq!(engine.state.seek_seq.load(Ordering::Acquire), 1);
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);
}
}