From e255636f3af774bda997a81914132b920440516c Mon Sep 17 00:00:00 2001 From: Keenan Tims Date: Thu, 5 Nov 2026 12:26:48 -0700 Subject: [PATCH] some refactoring and clippies --- Cargo.lock | 16 ++++- cli/Cargo.toml | 2 +- firmware/Cargo.toml | 4 +- firmware/src/dma.rs | 142 ++++++++++++++++++++++------------------- firmware/src/hw.rs | 14 ++-- firmware/src/main.rs | 31 ++++----- firmware/src/traits.rs | 1 + shared/src/lib.rs | 11 +--- 8 files changed, 119 insertions(+), 102 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 7d2c01e..49dd82c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -173,6 +173,17 @@ version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2d7e60934ceec538daadb9d8432424ed043a904d8e0243f3c6446bce549a46ac" +[[package]] +name = "bitfield-struct" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ca6739863c590881f038d033a146c51ddae239186a4327014839fd864f44ed5" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "bitflags" version = "1.3.2" @@ -325,7 +336,7 @@ checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9" [[package]] name = "cli" -version = "0.1.0" +version = "0.3.0" dependencies = [ "async-hid", "clap", @@ -756,10 +767,11 @@ dependencies = [ [[package]] name = "guac" -version = "0.2.0" +version = "0.3.0" dependencies = [ "atomic", "bbqueue", + "bitfield-struct", "cortex-m", "cortex-m-rt", "defmt 1.1.1", diff --git a/cli/Cargo.toml b/cli/Cargo.toml index c2572eb..8816947 100644 --- a/cli/Cargo.toml +++ b/cli/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "cli" -version = "0.1.0" +version = "0.3.0" edition = "2024" [dependencies] diff --git a/firmware/Cargo.toml b/firmware/Cargo.toml index 3967f35..aef0e2c 100644 --- a/firmware/Cargo.toml +++ b/firmware/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "guac" -version = "0.2.0" +version = "0.3.0" edition = "2024" [features] @@ -16,7 +16,6 @@ evk = ["wm8904"] shared = { path = "../shared" } atomic = "0.6.1" bbqueue = "0.7.0" -# bytemuck = { version = "1.25.0", features = ["derive"] } cortex-m = { version = "0.7.7", features = ["critical-section-single-core"] } cortex-m-rt = "0.7.5" defmt = "1.0.1" @@ -34,6 +33,7 @@ static_cell = "2.1.1" usb-device = { version = "0.3", features = ["control-buffer-256"] } usbd-hid = { version = "0.10.0", optional = true } usbd-uac2 = { version = "0.1.2", features = ["defmt"] } +bitfield-struct = "0.13.0" [profile.release] opt-level = "z" diff --git a/firmware/src/dma.rs b/firmware/src/dma.rs index ce2be7a..804cff5 100644 --- a/firmware/src/dma.rs +++ b/firmware/src/dma.rs @@ -1,3 +1,4 @@ +use bitfield_struct::bitfield; use hal::Syscon; use hal::peripherals::syscon::ClockControl; @@ -7,8 +8,6 @@ use core::convert::Infallible; use core::ptr::copy_nonoverlapping; use core::sync::atomic::{AtomicUsize, Ordering, compiler_fence}; -pub const DMA0_FLEXCOMM7_TX: u8 = 19; - #[repr(C)] #[derive(Copy, Clone)] pub struct DmaDescriptor { @@ -18,6 +17,56 @@ pub struct DmaDescriptor { pub next: *const DmaDescriptor, } +const fn encode_transfers(transfers: u32) -> u16 { + (transfers.saturating_sub(1) & 0x3ff) as u16 +} + +const fn decode_transfers(raw_bits: u16) -> u32 { + (raw_bits as u32) + 1 +} + +/// WIDTH code: 0 = 8-bit, 1 = 16-bit, 2 = 32-bit +const fn encode_width(width_bytes: u8) -> u8 { + match width_bytes { + 2 => 1, + 4 => 2, + _ => 0, + } +} + +const fn decode_width(raw_bits: u8) -> u8 { + match raw_bits { + 1 => 2, + 2 => 4, + _ => 1, + } +} + +#[bitfield(u32)] +#[derive(PartialEq, Eq)] +pub struct XferCfg { + pub cfgvalid: bool, // Bit 0 + pub reload: bool, // Bit 1 + pub swtrig: bool, // Bit 2 + pub clrtrig: bool, // Bit 3 + pub inta: bool, // Bit 4 + pub intb: bool, // Bit 5 + #[bits(2)] + _pad1: u8, // Bits 6-7 (unused padding) + #[bits(2, from = decode_width, into = encode_width)] + pub width: u8, // Bits 8-9, in bytes (1/2/4) + #[bits(2)] + _pad2: u8, // Bits 10-11 (unused padding) + #[bits(2)] + pub src_inc: u8, // Bits 12-13 + #[bits(2)] + pub dst_inc: u8, // Bits 14-15 + #[bits(10, from = decode_transfers, into = encode_transfers)] + pub transfers: u32, // Bits 16-25 (fits 0x3FF max) + #[bits(6)] + _pad3: u8, // Bits 26-31 (unused padding) +} + impl defmt::Format for DmaDescriptor { fn format(&self, fmt: defmt::Formatter) { defmt::write!( @@ -48,7 +97,7 @@ pub struct PushResult { pub dropped: usize, } -#[derive(Debug, Copy, Clone, Eq, PartialEq)] +#[derive(Debug, Copy, Clone, defmt::Format, Eq, PartialEq)] pub enum ConfigError { SlotTooLarge, SlotTooSmall, @@ -78,7 +127,7 @@ pub struct DmaRing { /// Effective bytes per slot (atomic for interior mutability) slot_bytes: AtomicUsize, - word_bytes: usize, + word_bytes: u8, write_slot: UnsafeCell, write_off: UnsafeCell, @@ -97,7 +146,7 @@ impl DmaRing { dma: pac::DMA0, syscon: &mut Syscon, dst_reg: *mut u32, - word_bytes: usize, + word_bytes: u8, ) -> Result { if word_bytes != 1 && word_bytes != 2 && word_bytes != 4 { return Err(ConfigError::UnsupportedWidth); @@ -107,7 +156,7 @@ impl DmaRing { Ok(Self { dma, - dst_reg: dst_reg, + dst_reg, channel_desc: UnsafeCell::new(DescriptorTable { d: [DmaDescriptor { xfercfg: 0, @@ -138,6 +187,7 @@ impl DmaRing { } /// Optional: adjust safety gap (defaults to 1 empty slot). + #[allow(dead_code)] pub fn set_safety_gap(&mut self, gap_slots: usize) { self.safety_gap = gap_slots.min(N); } @@ -152,7 +202,7 @@ impl DmaRing { if slot_bytes > MAX_SLOT_BYTES { return Err(ConfigError::SlotTooLarge); } - if slot_bytes % self.word_bytes != 0 { + if !slot_bytes.is_multiple_of(self.word_bytes as usize) { return Err(ConfigError::SlotNotAligned); } @@ -253,7 +303,7 @@ impl DmaRing { let remaining_bytes = if reg_1 == 0x3FF { 0 } else { - (reg_1 as usize + 1) * self.word_bytes + (reg_1 as usize + 1) * self.word_bytes as usize }; // Active slot consumed calculation accounts for dynamic slot size @@ -333,30 +383,30 @@ impl DmaRing { let chan_desc = unsafe { &mut *self.channel_desc.get() }; // Pre-fill active slot regions with silence - for i in 0..N { - slots[i][..slot_bytes].fill(0); + for slot in slots.iter_mut() { + slot.fill(0); } - let transfers = (slot_bytes / self.word_bytes) as u32; + let transfers = (slot_bytes / self.word_bytes as usize) as u32; - for i in 0..N { - let src_start = slots[i].as_ptr() as usize; - let src_end = (src_start + slot_bytes - self.word_bytes) as *const u8; + for (i, slot) in slots.iter().enumerate() { + let src_start = slot.as_ptr() as usize; + let src_end = (src_start + slot_bytes - self.word_bytes as usize) as *const u8; let next = &desc.d[(i + 1) % N] as *const DmaDescriptor; desc.d[i] = DmaDescriptor { - xfercfg: encode_xfercfg( - true, // valid - true, // reload - false, // swtrig - false, // clrtrig - true, // intA - false, // intB - self.word_bytes as u32, - 1, // src_inc - 0, // dst_inc - transfers, - ), + xfercfg: XferCfg::new() + .with_cfgvalid(true) // valid + .with_reload(true) // reload + .with_swtrig(false) // swtrig + .with_clrtrig(false) // clrtrig + .with_inta(true) // intA + .with_intb(false) // intB + .with_width(self.word_bytes) + .with_src_inc(1) // src_inc + .with_dst_inc(0) // dst_inc + .with_transfers(transfers) + .into_bits(), src_end, dst_end: self.dst_reg, next, @@ -374,43 +424,3 @@ impl DmaRing { } unsafe impl Sync for DmaRing {} - -/// XFERCFG encoding follows the common LPC DMA layout: -/// - SETINTA at bit4, SETINTB at bit5 -/// - WIDTH at bits 9:8 -/// - SRCINC at bits 13:12 -/// - DSTINC at bits 15:14 -/// - XFERCOUNT at bits 25:16 -/// This layout is shown in LPC DMA examples. [5](https://www.kernel.org/doc/html/latest/core-api/dma-api-howto.html) -fn encode_xfercfg( - cfgvalid: bool, - reload: bool, - swtrig: bool, - clrtrig: bool, - inta: bool, - intb: bool, - width_bytes: u32, - src_inc: u32, - dst_inc: u32, - transfers: u32, -) -> u32 { - let width_code = match width_bytes { - 1 => 0, - 2 => 1, - 4 => 2, - _ => 0, - }; - - let count_field = transfers.saturating_sub(1) & 0x3FF; - - ((cfgvalid as u32) << 0) - | ((reload as u32) << 1) - | ((swtrig as u32) << 2) - | ((clrtrig as u32) << 3) - | ((inta as u32) << 4) - | ((intb as u32) << 5) - | ((width_code & 0x3) << 8) - | ((src_inc & 0x3) << 12) - | ((dst_inc & 0x3) << 14) - | (count_field << 16) -} diff --git a/firmware/src/hw.rs b/firmware/src/hw.rs index 875d348..1ddee18 100644 --- a/firmware/src/hw.rs +++ b/firmware/src/hw.rs @@ -4,7 +4,7 @@ use core::mem::MaybeUninit; use crate::hal; use crate::pac; -use defmt::{debug, info}; +use defmt::debug; use hal::{ Enabled, Iocon, Pin, drivers::pins, @@ -124,13 +124,16 @@ pub(crate) fn init_sys_pll1() { syscon.mainclkselb.modify(|_, w| w.sel().enum_0x2()); // pll1 } -// Fo = M/(N*2*P) * Fin -// Fo = 3072/(125*2*8) * 16MHz = 24.576MHz -const AUDIO_PLL: PllConstants = PllConstants::new(125, 3072, 8); - // Set PLL0 to 24.576MHz, start, and wait for lock // This is not exposed by lpc55-hal, unfortunately. Copy their implementation here. +#[cfg(feature = "evk")] pub(crate) fn init_audio_pll() { + use defmt::info; + + // Fo = M/(N*2*P) * Fin + // Fo = 3072/(125*2*8) * 16MHz = 24.576MHz + const AUDIO_PLL: PllConstants = PllConstants::new(125, 3072, 8); + let syscon = unsafe { &*pac::SYSCON::ptr() }; let pmc = unsafe { &*pac::PMC::ptr() }; let anactrl = unsafe { &*pac::ANACTRL::ptr() }; @@ -200,6 +203,7 @@ pub struct SharedLed { inner: UnsafeCell, } unsafe impl Sync for SharedLed {} +#[allow(dead_code)] impl SharedLed { pub fn new(inner: T) -> Self { Self { diff --git a/firmware/src/main.rs b/firmware/src/main.rs index c1511d4..0b21e8a 100644 --- a/firmware/src/main.rs +++ b/firmware/src/main.rs @@ -12,7 +12,6 @@ use core::ptr; use core::sync::atomic::AtomicPtr; use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use cortex_m_rt::entry; -use defmt; use defmt::debug; use defmt_rtt as _; use hal::Pin; @@ -110,6 +109,7 @@ const HID_INTERVAL_MS: u8 = 10; const HID_CMD_INTERVAL_MS: u8 = 100; struct CodecPins { + #[allow(dead_code)] reset: Pin>, } @@ -221,7 +221,7 @@ pub struct FeedbackConfig { impl FeedbackConfig { pub fn new(nominal_rate: u32, target_fill_bytes: usize) -> Self { Self { - nominal_rate: nominal_rate, + nominal_rate, target_fill_bytes: target_fill_bytes as i32, deadband_bytes: 4, max_deviation_divider: 500, // 0.2% @@ -321,11 +321,6 @@ fn cur_fill() -> usize { produced_bytes.wrapping_sub(consumed_bytes) as usize } -/// current fill target (based on current slot size) -fn cur_fill_target() -> i32 { - (dma_ring().slot_size() * N_SLOTS) as i32 / 2 -} - /// frames per slot (based on current slot size) fn frames_per_slot() -> usize { dma_ring().slot_size() / BYTES_PER_FRAME @@ -572,7 +567,10 @@ impl, I> ClockSource for Audio<'_, D, I> { } self.cur_rate = sample_rate; let slot_bytes = bytes_per_slot(self.cur_rate); - dma_ring().set_slot_size(slot_bytes); + if let Err(e) = dma_ring().set_slot_size(slot_bytes) { + defmt::error!("Error configuring dma: {}", e); + return Err(UsbAudioClassError::Other); + } self.fb .update_config(FeedbackConfig::for_rate(self.cur_rate)); if 24_576_000u32.is_multiple_of(sample_rate) { @@ -669,7 +667,7 @@ impl, I, B: bus::UsbBus> AudioHandler<'_, B> for Audio<'_, D, I> { AudioState::Running => {} // If draining, check cur_fill, if it rises above QUEUE_RUNNING_UP, move back to running. If it drops to 0, move to NoData or Stopped AudioState::LowData => { - let fill = cur_fill() as usize; + let fill = cur_fill(); // Do we check alt setting here? We shouldn't be receiving data at all if we are not in altSetting 1 if fill >= queue_running_up_threshold() { self.transition(AudioState::Running); @@ -812,7 +810,7 @@ fn main() -> ! { pins::Pio1_20::take().unwrap().into_i2c4_scl_pin(&mut iocon), pins::Pio1_21::take().unwrap().into_i2c4_sda_pin(&mut iocon), ); - let codec_i2s_pins = ( + let _codec_i2s_pins = ( pins::Pio0_21::take().unwrap().into_spi7_sck_pin(&mut iocon), pins::Pio0_20::take().unwrap().into_i2s7_sda_pin(&mut iocon), pins::Pio0_19::take().unwrap().into_i2s7_ws_pin(&mut iocon), @@ -995,10 +993,10 @@ fn main() -> ! { if hid_update_timer.wait().is_ok() { let report = build_telemetry_report(&PERF, uac2.handler()); - if let Err(e) = hid.push_input(&report) { - if e != UsbError::WouldBlock { - defmt::error!("Failed to send HID report: {:?}", e); - } + if let Err(e) = hid.push_input(&report) + && e != UsbError::WouldBlock + { + defmt::error!("Failed to send HID report: {:?}", e); } // LPC55 CTIMER is not periodic; restart manually hid_update_timer.start(Microseconds::new(HID_INTERVAL_MS as u32 * 1000)); @@ -1008,10 +1006,9 @@ fn main() -> ! { Ok(len) => { if let Ok((_left, cmd)) = AudioDeviceCommandReport::from_bytes((&cmd_report_buf[0..len], 0)) + && let Ok(cmd) = cmd.try_into() { - if let Ok(cmd) = cmd.try_into() { - handle_cmd(cmd) - } + handle_cmd(cmd) } } Err(UsbError::WouldBlock) => {} diff --git a/firmware/src/traits.rs b/firmware/src/traits.rs index d7ccf94..6616b9e 100644 --- a/firmware/src/traits.rs +++ b/firmware/src/traits.rs @@ -5,6 +5,7 @@ pub trait Dac { fn init(&mut self); fn change_rate(&mut self, new_rate: u32); #[allow(unused_variables)] + #[allow(dead_code)] fn set_volume(&mut self, left: u8, right: u8) {} fn mute(&mut self); fn unmute(&mut self); diff --git a/shared/src/lib.rs b/shared/src/lib.rs index 294a990..5a0453e 100644 --- a/shared/src/lib.rs +++ b/shared/src/lib.rs @@ -9,13 +9,14 @@ use num_enum::TryFromPrimitive; #[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; -#[derive(Clone, Copy, Debug, NoUninit, Eq, PartialEq, TryFromPrimitive)] +#[derive(Clone, Copy, Debug, Default, NoUninit, Eq, PartialEq, TryFromPrimitive)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] #[repr(u8)] pub enum AudioState { /// Knowingly stopped, ie. AltSetting=0. DAC muted, I2S disabled. /// /// AltSetting = 1 -> ARMED + #[default] Stopped = 0, /// Waiting for data. DAC muted, I2S running sending 0s (FIFO not serviced). /// @@ -52,11 +53,6 @@ pub enum AudioState { Stopping = 6, } -impl Default for AudioState { - fn default() -> Self { - AudioState::Stopped - } -} impl defmt::Format for AudioState { fn format(&self, fmt: defmt::Formatter) { defmt::write!( @@ -125,9 +121,6 @@ pub mod hid { use deku::{DekuContainerWrite, DekuWrite}; use usbd_hid::descriptor::generator_prelude::*; - #[cfg(feature = "serde")] - use serde::{Deserialize, Serialize}; - use crate::{AudioDeviceCommand, AudioState, AudioTelemetrySnapshot}; /// HID usage IDs identifying each vendor interface. `gen_hid_descriptor` only accepts