Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 10 additions & 11 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 1 addition & 5 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,14 @@ debug = true
[features]
default = ["standalone"]
standalone = [
"dep:alsa",
"dep:maolan-engine",
"maolan-engine?/audio",
"maolan-engine?/plugins",
]
embedded = []

[dependencies]
maolan-engine = { version = "0.4.27", optional = true }
maolan-engine = { version = "0.4.28", optional = true }
maolan-widgets = "0.1.6"
rfd = "0.18.0"
serde = { version = "1.0", features = ["derive"] }
Expand All @@ -35,9 +34,6 @@ serde_json = "1.0.154"
toml = "1.2.1"
tokio = { version = "1.54.1", features = ["sync", "time"] }

[target.'cfg(target_os = "linux")'.dependencies]
alsa = { version = "0.12.1", optional = true }

[dev-dependencies]
tokio = { version = "1.54.1", features = ["rt", "macros"] }

Expand Down
235 changes: 18 additions & 217 deletions src/devices.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,20 @@ impl AudioDeviceOption {
}
}

#[cfg(all(feature = "standalone", target_os = "linux"))]
impl From<maolan_engine::audio_devices::AudioDeviceDescriptor> for AudioDeviceOption {
fn from(device: maolan_engine::audio_devices::AudioDeviceDescriptor) -> Self {
Self::with_supported_direction_caps(
device.id,
device.label,
device.supported_bits,
device.supported_sample_rates,
device.supports_input,
device.supports_output,
)
}
}

#[cfg(all(feature = "standalone", target_os = "freebsd"))]
impl From<maolan_engine::audio_devices::AudioDeviceDescriptor> for AudioDeviceOption {
fn from(device: maolan_engine::audio_devices::AudioDeviceDescriptor) -> Self {
Expand Down Expand Up @@ -348,12 +362,10 @@ fn platform_audio_devices() -> Vec<AudioDeviceOption> {
}
#[cfg(target_os = "linux")]
{
let mut output_devices = platform_linux::discover_alsa_output_devices();
let mut input_devices = platform_linux::discover_alsa_input_devices();
output_devices.append(&mut input_devices);
output_devices.sort_by_key(|device| device.label.to_lowercase());
output_devices.dedup_by(|a, b| a.id == b.id);
output_devices
maolan_engine::audio_devices::discover_alsa_audio_devices()
.into_iter()
.map(AudioDeviceOption::from)
.collect()
}
#[cfg(target_os = "openbsd")]
{
Expand All @@ -379,217 +391,6 @@ fn platform_audio_devices() -> Vec<AudioDeviceOption> {
vec![simple_audio_device("default")]
}

#[cfg(all(feature = "standalone", target_os = "linux"))]
mod platform_linux {
use alsa::{
Direction,
pcm::{Access, Format, HwParams, PCM},
};

const SAMPLE_RATE_CANDIDATES: [u32; 12] = [
8_000, 11_025, 16_000, 22_050, 32_000, 44_100, 48_000, 88_200, 96_000, 176_400, 192_000,
384_000,
];

fn read_alsa_card_labels() -> std::collections::HashMap<u32, String> {
let mut labels = std::collections::HashMap::new();
let Ok(contents) = std::fs::read_to_string("/proc/asound/cards") else {
return labels;
};
for line in contents.lines() {
let line = line.trim_start();
let Some((num_str, rest)) = line.split_once(' ') else {
continue;
};
let Ok(card) = num_str.parse::<u32>() else {
continue;
};
let Some((_, desc)) = rest.split_once("]:") else {
continue;
};
let desc = desc.trim();
if !desc.is_empty() {
labels.insert(card, desc.to_string());
}
}
labels
}

fn probe_alsa_supported_bits(device: &str, direction: Direction) -> Vec<usize> {
let Ok(pcm) = PCM::new(device, direction, false) else {
return Vec::new();
};
let Ok(hwp) = HwParams::any(&pcm) else {
return Vec::new();
};
if hwp.set_access(Access::RWInterleaved).is_err() {
return Vec::new();
}

fn supports(hwp: &HwParams<'_>, fmt: Format) -> bool {
hwp.test_format(fmt).is_ok()
}

let candidates: Vec<(usize, Vec<Format>)> = vec![
(32, vec![native_s32(), foreign_s32()]),
(24, vec![native_s24(), foreign_s24()]),
(16, vec![native_s16(), foreign_s16()]),
(8, vec![Format::S8]),
];

let mut supported = Vec::new();
for (bits, formats) in candidates {
if formats.iter().any(|f| supports(&hwp, *f)) {
supported.push(bits);
}
}
supported
}

fn probe_alsa_supported_sample_rates(device: &str, direction: Direction) -> Vec<i32> {
let Ok(pcm) = PCM::new(device, direction, false) else {
return Vec::new();
};
let Ok(hwp) = HwParams::any(&pcm) else {
return Vec::new();
};
if hwp.set_access(Access::RWInterleaved).is_err() {
return Vec::new();
}

let mut supported = Vec::new();
for rate in SAMPLE_RATE_CANDIDATES {
if hwp.test_rate(rate).is_ok() {
supported.push(rate as i32);
}
}
supported
}

#[cfg(target_endian = "little")]
fn native_s16() -> Format {
Format::S16LE
}
#[cfg(target_endian = "big")]
fn native_s16() -> Format {
Format::S16BE
}
#[cfg(target_endian = "little")]
fn foreign_s16() -> Format {
Format::S16BE
}
#[cfg(target_endian = "big")]
fn foreign_s16() -> Format {
Format::S16LE
}

#[cfg(target_endian = "little")]
fn native_s24() -> Format {
Format::S24LE
}
#[cfg(target_endian = "big")]
fn native_s24() -> Format {
Format::S24BE
}
#[cfg(target_endian = "little")]
fn foreign_s24() -> Format {
Format::S24BE
}
#[cfg(target_endian = "big")]
fn foreign_s24() -> Format {
Format::S24LE
}

#[cfg(target_endian = "little")]
fn native_s32() -> Format {
Format::S32LE
}
#[cfg(target_endian = "big")]
fn native_s32() -> Format {
Format::S32BE
}
#[cfg(target_endian = "little")]
fn foreign_s32() -> Format {
Format::S32BE
}
#[cfg(target_endian = "big")]
fn foreign_s32() -> Format {
Format::S32LE
}

fn discover_alsa_devices(
direction_marker: &str,
direction: Direction,
) -> Vec<super::AudioDeviceOption> {
let mut devices = Vec::new();
let card_labels = read_alsa_card_labels();
if let Ok(contents) = std::fs::read_to_string("/proc/asound/pcm") {
for line in contents.lines() {
let Some((card_dev, rest)) = line.split_once(':') else {
continue;
};
if !rest.contains(direction_marker) {
continue;
}
let mut parts = card_dev.trim().split('-');
let (Some(card), Some(dev)) = (parts.next(), parts.next()) else {
continue;
};
let Ok(card) = card.parse::<u32>() else {
continue;
};
let Ok(dev) = dev.parse::<u32>() else {
continue;
};
let device_name = rest.split(':').next().unwrap_or("").trim();
let card_label = card_labels
.get(&card)
.cloned()
.unwrap_or_else(|| format!("Card {card}"));
let base_label = if device_name.is_empty() {
card_label
} else {
format!("{card_label} - {device_name}")
};
let id = format!("hw:{card},{dev}");
let label = format!("{base_label} (hw:{card},{dev})");
let supported_bits = probe_alsa_supported_bits(&id, direction);
let supported_sample_rates = {
let rates = probe_alsa_supported_sample_rates(&id, direction);
if rates.is_empty() {
super::fallback_sample_rates()
} else {
rates
}
};
let (supports_input, supports_output) = match direction {
Direction::Playback => (false, true),
Direction::Capture => (true, false),
};
devices.push(super::AudioDeviceOption::with_supported_direction_caps(
id,
label,
supported_bits,
supported_sample_rates,
supports_input,
supports_output,
));
}
}
devices.sort_by_key(|a| a.label.to_lowercase());
devices.dedup_by(|a, b| a.id == b.id);
devices
}

pub(crate) fn discover_alsa_output_devices() -> Vec<super::AudioDeviceOption> {
discover_alsa_devices("playback", Direction::Playback)
}

pub(crate) fn discover_alsa_input_devices() -> Vec<super::AudioDeviceOption> {
discover_alsa_devices("capture", Direction::Capture)
}
}

fn simple_audio_device(id: impl Into<String>) -> AudioDeviceOption {
let id = id.into();
AudioDeviceOption::with_supported_caps(
Expand Down
Loading