Skip to content

Commit 8b9a91f

Browse files
committed
fix: 使用设备支持的最高采样率输出,修复 pipewire 默认 44100 导致高采样率音频被降采样 #106
1 parent 7e783d4 commit 8b9a91f

1 file changed

Lines changed: 58 additions & 20 deletions

File tree

‎native/audio-engine/src/audio_output.rs‎

Lines changed: 58 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ use crate::priority;
3737
/// ```
3838
pub struct AudioOutput {
3939
handle: OutputStreamHandle,
40-
/// 设备原生采样率
40+
/// 输出流采样率(设备支持的最高,封顶 192000)
4141
sample_rate: u32,
4242
/// drop 这个 sender 会让 owner 线程的 recv 返回 Err,从而退出并释放 Stream
4343
/// 包成 Option 是为了 Drop 里能 take() 出来显式 drop,从而在 join 前先关闭 channel
@@ -109,7 +109,7 @@ impl AudioOutput {
109109
&self.handle
110110
}
111111

112-
/// 设备原生采样率,作为播放重采样目标
112+
/// 输出流采样率,作为播放重采样目标
113113
pub fn sample_rate(&self) -> u32 {
114114
self.sample_rate
115115
}
@@ -130,11 +130,14 @@ impl Drop for AudioOutput {
130130
}
131131
}
132132

133+
/// 采样率上限:避免设备报告极高值(如 384000)导致无谓的 CPU/内存开销
134+
const SAMPLE_RATE_CAP: u32 = 192_000;
135+
133136
/// 构建 cpal/rodio 输出流;**仅在 `audio-output-owner` 线程内调用**,
134137
/// 保证 `OutputStream` 的创建、持有和 drop 都发生在同一线程上
135138
///
136-
/// 返回的采样率为设备 `default_output_config` 的采样率——正是 rodio 内部
137-
/// `try_from_device` / `try_default` 打开 stream 所用的值,用作播放重采样目标
139+
/// 返回的采样率为设备支持的最高采样率(封顶 192000),用作播放重采样目标。
140+
/// 避免 pipewire 等默认 44100 导致高采样率音频被降采样
138141
fn build_output_stream(
139142
device_name: Option<&str>,
140143
) -> Result<(OutputStream, OutputStreamHandle, u32)> {
@@ -146,44 +149,79 @@ fn build_output_stream(
146149
.context("Failed to enumerate output devices")?
147150
.find(|d| d.name().map(|got| got == name).unwrap_or(false))
148151
.with_context(|| format!("Output device '{}' not found", name))?;
149-
let sample_rate = device_sample_rate(&device);
150-
let (stream, handle) = OutputStream::try_from_device(&device)
151-
.context("Failed to open named output device")?;
152-
Ok((stream, handle, sample_rate))
152+
open_device_with_best_rate(&device)
153153
}
154154
None => open_default_stream(&host),
155155
}
156156
}
157157

158-
/// 记录到"打不开的默认设备"的采样率,导致 rodio 内部又按真实设备率重采样
159158
fn open_default_stream(host: &cpal::Host) -> Result<(OutputStream, OutputStreamHandle, u32)> {
160159
let default_device = host
161160
.default_output_device()
162161
.context("No default output device")?;
163-
if let Ok((stream, handle)) = OutputStream::try_from_device(&default_device) {
164-
let sample_rate = device_sample_rate(&default_device);
165-
return Ok((stream, handle, sample_rate));
162+
if let Ok(result) = open_device_with_best_rate(&default_device) {
163+
return Ok(result);
166164
}
167165

168166
// 默认设备打不开:遍历其它设备,打开成功的那个用它自身的采样率
169167
let devices = host
170168
.output_devices()
171169
.context("Failed to enumerate output devices")?;
172170
for device in devices {
173-
if let Ok((stream, handle)) = OutputStream::try_from_device(&device) {
174-
let sample_rate = device_sample_rate(&device);
175-
return Ok((stream, handle, sample_rate));
171+
if let Ok(result) = open_device_with_best_rate(&device) {
172+
return Ok(result);
176173
}
177174
}
178175
anyhow::bail!("No usable output device")
179176
}
180177

181-
/// 取设备默认输出配置的采样率,查询失败回退到 `TARGET_SAMPLE_RATE`
182-
fn device_sample_rate(device: &cpal::Device) -> u32 {
183-
device
178+
/// 用设备支持的最高采样率创建输出流
179+
fn open_device_with_best_rate(
180+
device: &cpal::Device,
181+
) -> Result<(OutputStream, OutputStreamHandle, u32)> {
182+
let config = pick_best_config(device)?;
183+
let sample_rate = config.sample_rate().0;
184+
let (stream, handle) = OutputStream::try_from_device_config(device, config)
185+
.context("Failed to open output device")?;
186+
Ok((stream, handle, sample_rate))
187+
}
188+
189+
/// 在设备支持的采样率范围内选取最高的,避免 pipewire 等默认 44100 导致高采样率音频被降采样
190+
///
191+
/// 从 `supported_output_configs` 中找与默认配置(声道/格式)匹配且 max_sample_rate 最高的范围,
192+
/// 用 `with_sample_rate` 构造具体配置。封顶 192000 避免极高值导致无谓开销。
193+
/// 查询失败或无更高速率时回退到默认配置
194+
fn pick_best_config(device: &cpal::Device) -> Result<cpal::SupportedStreamConfig> {
195+
let default_config = device
184196
.default_output_config()
185-
.map(|config| config.sample_rate().0)
186-
.unwrap_or(crate::decoder::TARGET_SAMPLE_RATE)
197+
.context("Failed to get default output config")?;
198+
let default_rate = default_config.sample_rate().0;
199+
200+
let target_channels = default_config.channels();
201+
let target_format = default_config.sample_format();
202+
203+
let ranges: Vec<_> = device
204+
.supported_output_configs()
205+
.context("Failed to enumerate supported output configs")?
206+
.collect();
207+
208+
// 在匹配声道/格式的范围中找 max_sample_rate 最高的,用其上限(封顶)创建配置
209+
let best = ranges
210+
.into_iter()
211+
.filter(|range| {
212+
range.channels() == target_channels && range.sample_format() == target_format
213+
})
214+
.max_by_key(|range| range.max_sample_rate().0)
215+
.filter(|range| range.max_sample_rate().0 > default_rate)
216+
.map(|range| {
217+
let rate = range.max_sample_rate().0.min(SAMPLE_RATE_CAP);
218+
range.with_sample_rate(cpal::SampleRate(rate))
219+
});
220+
221+
match best {
222+
Some(config) => Ok(config),
223+
None => Ok(default_config),
224+
}
187225
}
188226

189227
/// 枚举所有输出设备,返回 `(name, is_default)` 列表

0 commit comments

Comments
 (0)