Compare commits

...
3 Commits
Author SHA1 Message Date
ktims 7b49f116d4 cli: add more options, refactor, switch to smol runtime 2026-11-05 17:04:37 -07:00
ktims fabacf0a04 update workflow with correct target definition, add cli
Build and Release Firmware / firmware (ak4490) (push) Successful in 13s
Build and Release Firmware / firmware (cs4398) (push) Successful in 14s
Build and Release Firmware / firmware (evk) (push) Successful in 13s
Build and Release Firmware / cli (aarch64-unknown-linux-musl) (push) Successful in 1m11s
Build and Release Firmware / cli (x86_64-pc-windows-gnu) (push) Successful in 1m24s
Build and Release Firmware / cli (x86_64-unknown-linux-musl) (push) Successful in 1m14s
Build and Release Firmware / release (push) Successful in 6s
2026-11-05 13:37:31 -07:00
ktims e255636f3a some refactoring and clippies
Build and Release Firmware / build-and-release (push) Failing after 48s
2026-11-05 12:26:48 -07:00
11 changed files with 985 additions and 442 deletions

No files matched your search

+123 -34
View File
@@ -7,60 +7,149 @@ on:
env: env:
TARGET: thumbv8m.main-none-eabihf TARGET: thumbv8m.main-none-eabihf
# The catthehacker image installs rust here and only symlinks ~/.rustup and ~/.cargo to it.
# actions/cache archives the symlink, not its contents, so point at the real paths.
RUSTUP_HOME: /usr/share/rust/.rustup
CARGO_HOME: /usr/share/rust/.cargo
jobs: jobs:
build-and-release: firmware:
runs-on: ubuntu-latest runs-on: ubuntu-latest
container: container:
image: catthehacker/ubuntu:act-latest image: catthehacker/ubuntu:rust-latest
defaults: strategy:
run: fail-fast: true
shell: bash matrix:
variant: [cs4398, ak4490, evk]
env:
FEATURES: ${{ matrix.variant }},hid
steps: steps:
- name: Checkout repository - name: Checkout repository
uses: actions/checkout@v4 uses: actions/checkout@v4
- name: Cache rustup
uses: actions/cache@v4
with:
path: ${{ env.RUSTUP_HOME }}
key: rustup-firmware-${{ env.TARGET }}-${{ runner.os }}
- name: Install Rust Toolchain - name: Install Rust Toolchain
uses: dtolnay/rust-toolchain@stable
- name: Install cargo-binutils
run: cargo install cargo-binutils
- name: Build Firmware Binaries
run: | run: |
cd firmware rustup target install ${{ env.TARGET }}
rustup component add llvm-tools
# Array of "variant_name:features" - name: Cache cargo
VARIANTS=( uses: Swatinem/rust-cache@v2
"cs4398:cs4398,hid" with:
"ak4490:ak4490,hid" shared-key: firmware-${{ matrix.variant }}
"evk:evk,hid"
)
mkdir -p ../dist - name: Install cargo-binutils
run: cargo binstall -y --locked cargo-binutils
for entry in "${VARIANTS[@]}"; do - name: Build firmware (${{ matrix.variant }})
IFS=":" read -r name features <<< "$entry" working-directory: firmware
echo "Building variant: $name with features: $features" run: cargo build --release --target ${{ env.TARGET }} --no-default-features --features "${{ env.FEATURES }}"
# 1. Compile release binary - name: Create hex file
cargo build --release --target ${{ env.TARGET }} --no-default-features --features "$features" working-directory: firmware
run: cargo objcopy --release --target ${{ env.TARGET }} --no-default-features --features "${{ env.FEATURES }}" -- -O ihex ../target/${{ env.TARGET }}/release/guac-${{ matrix.variant }}.hex
# 2. Paths setup - name: Package
ELF_PATH="../target/${{ env.TARGET }}/release/guac" run: |
HEX_PATH="../target/${{ env.TARGET }}/release/guac-${name}.hex" out=target/${{ env.TARGET }}/release
RENAMED_ELF="../target/${{ env.TARGET }}/release/guac-${name}.elf" cp "$out/guac" "$out/guac-${{ matrix.variant }}.elf"
mkdir -p dist
zip -j "dist/guac-firmware-${{ matrix.variant }}.zip" "$out/guac-${{ matrix.variant }}.elf" "$out/guac-${{ matrix.variant }}.hex"
# 3. Create .hex file via rust-objcopy - name: Upload artifact
cargo objcopy --release --target ${{ env.TARGET }} --no-default-features --features "$features" -- -O ihex "$HEX_PATH" uses: actions/upload-artifact@v3
cp "$ELF_PATH" "$RENAMED_ELF" with:
name: firmware-${{ matrix.variant }}
path: dist/*.zip
# 4. Package ELF and HEX into target-specific ZIP cli:
ZIP_NAME="guac-firmware-${name}.zip" runs-on: ubuntu-latest
zip -j "../dist/${ZIP_NAME}" "$RENAMED_ELF" "$HEX_PATH" container:
done image: catthehacker/ubuntu:rust-latest
strategy:
fail-fast: true
matrix:
target:
- aarch64-unknown-linux-musl
- x86_64-pc-windows-gnu
- x86_64-unknown-linux-musl
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Cache rustup
uses: actions/cache@v4
with:
path: ${{ env.RUSTUP_HOME }}
key: rustup-cli-${{ matrix.target }}-${{ runner.os }}
- name: Install Rust Toolchain
run: rustup target install ${{ matrix.target }}
- name: Cache cargo
uses: Swatinem/rust-cache@v2
with:
shared-key: cli-${{ matrix.target }}
- name: Cache zigbuild install
uses: actions/cache@v4
with:
path: /opt/zigvenv
key: zigbuild-venv-${{ runner.os }}
# compiled libc/compiler-rt are per target, so these stay keyed on it
- name: Cache zig build artifacts
uses: actions/cache@v4
with:
path: |
~/.cache/zig
~/.cache/cargo-zigbuild
key: zigbuild-cache-${{ matrix.target }}-${{ runner.os }}
- name: Install cargo-zigbuild Toolchain
run: |
# venv keeps cargo-zigbuild and ziglang in one relocatable-by-path directory we can cache
[ -d /opt/zigvenv ] || python3 -m venv /opt/zigvenv
/opt/zigvenv/bin/pip install cargo-zigbuild
echo /opt/zigvenv/bin >> "$GITHUB_PATH"
- name: Build cli (${{ matrix.target }})
working-directory: cli
run: cargo zigbuild --release --target ${{ matrix.target }}
- name: Package
run: |
bin=guac-cli
[[ "${{ matrix.target }}" == *windows* ]] && bin=guac-cli.exe
mkdir -p dist
zip -j "dist/guac-cli-${{ matrix.target }}.zip" "target/${{ matrix.target }}/release/$bin"
shell: bash
- name: Upload artifact
uses: actions/upload-artifact@v3
with:
name: cli-${{ matrix.target }}
path: dist/*.zip
release:
needs: [firmware, cli]
runs-on: ubuntu-latest
container:
image: catthehacker/ubuntu:act-latest
steps:
- name: Download artifacts
uses: actions/download-artifact@v3
with:
path: dist
- name: Create Gitea Release - name: Create Gitea Release
uses: akkuman/gitea-release-action@v1 uses: akkuman/gitea-release-action@v1
with: with:
files: dist/*.zip files: dist/**/*.zip
draft: false draft: false
prerelease: false prerelease: false
+1 -1
View File
@@ -3,7 +3,7 @@ repos:
hooks: hooks:
- id: cargo-check-host - id: cargo-check-host
name: Cargo check (host) name: Cargo check (host)
entry: cargo check -p cli -p shared entry: cargo check -p guac-cli -p shared
pass_filenames: false pass_filenames: false
types: [file, rust] types: [file, rust]
language: system language: system
Generated
+572 -276
View File
File diff suppressed because it is too large. Load diff
+7 -3
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "cli" name = "guac-cli"
version = "0.1.0" version = "0.3.1"
edition = "2024" edition = "2024"
[dependencies] [dependencies]
@@ -8,8 +8,12 @@ async-hid = "0.5.1"
clap = { version = "4.6.1", features = ["derive"] } clap = { version = "4.6.1", features = ["derive"] }
colog = "1.4.0" colog = "1.4.0"
csv = "1.4.0" csv = "1.4.0"
ctrlc = "3.5.2"
deku = "0.20.3" deku = "0.20.3"
futures-lite = "2.6.1" futures-lite = "2.6.1"
log = { version = "0.4.29", features = ["std"] } log = { version = "0.4.29", features = ["std"] }
pollster = { version = "0.4.0", features = ["macro"] } serde_json = "1.0.154"
shared = { path = "../shared", features = ["serde", "std"] } shared = { path = "../shared", features = ["serde", "std"] }
smol = "2.0.2"
smol-macros = "0.1.1"
smol-timeout = "0.6.1"
+180 -31
View File
@@ -1,6 +1,17 @@
use std::io; use smol_macros::main;
use std::{
io,
str::FromStr,
sync::{
Arc,
atomic::{AtomicBool, Ordering},
},
time::Duration,
};
use async_hid::{AsyncHidRead, AsyncHidWrite, Device, HidBackend, HidResult}; use async_hid::{
AsyncHidRead, AsyncHidWrite, Device, DeviceReader, HidBackend, HidError, HidResult,
};
use clap::{Parser, Subcommand, ValueEnum}; use clap::{Parser, Subcommand, ValueEnum};
use deku::DekuContainerRead; use deku::DekuContainerRead;
use futures_lite::StreamExt; use futures_lite::StreamExt;
@@ -8,16 +19,53 @@ use shared::{
AudioDeviceCommand, AudioTelemetrySnapshot, AudioDeviceCommand, AudioTelemetrySnapshot,
hid::{AudioDeviceCommandReport, AudioTelemetryReport, USAGE_COMMAND, USAGE_TELEMETRY}, hid::{AudioDeviceCommandReport, AudioTelemetryReport, USAGE_COMMAND, USAGE_TELEMETRY},
}; };
use smol_timeout::TimeoutExt;
#[derive(Clone, Copy, Debug, ValueEnum)] #[derive(Clone, Copy, Debug, ValueEnum)]
enum Format { enum Format {
Debug, Debug,
Csv, Csv,
Json,
}
#[derive(Clone, Copy, Debug)]
struct UsbVidPid {
vid: u16,
pid: u16,
}
impl FromStr for UsbVidPid {
type Err = clap::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let invalid = || {
clap::Error::raw(
clap::error::ErrorKind::ValueValidation,
"Format of USB device ID is `12ab:cd34` (vendor:product, hex)",
)
};
let (vid, pid) = s.split_once(':').ok_or_else(invalid)?;
Ok(Self {
vid: u16::from_str_radix(vid, 16).map_err(|_| invalid())?,
pid: u16::from_str_radix(pid, 16).map_err(|_| invalid())?,
})
}
} }
#[derive(Subcommand, Clone, Copy, Debug)] #[derive(Subcommand, Clone, Copy, Debug)]
enum Command { enum Command {
Monitor, /// Continuously print statistics from the connected device
Monitor {
#[arg(short, long, default_value = "debug")]
format: Format,
#[arg(short, long, default_value = None)]
count: Option<usize>,
},
/// Print the current state of the connected device
Status {
#[arg(short, long, default_value = "debug")]
format: Format,
},
/// Reset the connected device or boot to bootloader for firmware upgrade
Reset { Reset {
#[arg(short, long, default_value_t = false)] #[arg(short, long, default_value_t = false)]
bootloader: bool, bootloader: bool,
@@ -25,29 +73,35 @@ enum Command {
} }
#[derive(Parser, Debug)] #[derive(Parser, Debug)]
#[command(version, about)] #[command(
version,
about = "Interact with GUAC UAC2 devices",
arg_required_else_help = true
)]
struct Args { struct Args {
#[arg(short, long, default_value = "debug")] #[arg(short, long, default_value = "1209:cc1d")]
format: Format, /// USB device ID to operate on, format `1209:cc1d` (vendor:product, hex)
device: UsbVidPid,
#[command(subcommand)] #[command(subcommand)]
command: Option<Command>, command: Option<Command>,
} }
trait StateEmitter<W: io::Write> { trait StateEmitter {
fn from_writer(writer: W) -> Self
where
Self: Sized;
fn emit(&mut self, r: &AudioTelemetrySnapshot); fn emit(&mut self, r: &AudioTelemetrySnapshot);
fn close(&mut self) {}
} }
struct DebugEmitter<T: io::Write> { struct DebugEmitter<T: io::Write> {
writer: T, writer: T,
} }
impl<W: io::Write> StateEmitter<W> for DebugEmitter<W> { impl<W: io::Write> DebugEmitter<W> {
fn from_writer(writer: W) -> Self { fn new(writer: W) -> Self {
Self { writer } Self { writer }
} }
}
impl<W: io::Write> StateEmitter for DebugEmitter<W> {
fn emit(&mut self, r: &AudioTelemetrySnapshot) { fn emit(&mut self, r: &AudioTelemetrySnapshot) {
writeln!(self.writer, "{r:?}").ok(); writeln!(self.writer, "{r:?}").ok();
} }
@@ -57,12 +111,15 @@ struct CsvEmitter<W: io::Write> {
csv: csv::Writer<W>, csv: csv::Writer<W>,
} }
impl<W: io::Write> StateEmitter<W> for CsvEmitter<W> { impl<W: io::Write> CsvEmitter<W> {
fn from_writer(writer: W) -> Self { fn new(writer: W) -> Self {
Self { Self {
csv: csv::Writer::from_writer(writer), csv: csv::Writer::from_writer(writer),
} }
} }
}
impl<W: io::Write> StateEmitter for CsvEmitter<W> {
fn emit(&mut self, r: &AudioTelemetrySnapshot) { fn emit(&mut self, r: &AudioTelemetrySnapshot) {
if let Err(e) = self.csv.serialize(r) { if let Err(e) = self.csv.serialize(r) {
eprintln!("Serialization error: {e:?}"); eprintln!("Serialization error: {e:?}");
@@ -72,42 +129,133 @@ impl<W: io::Write> StateEmitter<W> for CsvEmitter<W> {
} }
} }
struct JsonEmitter<W: io::Write> {
writer: W,
first: bool,
}
impl<W: io::Write> JsonEmitter<W> {
fn new(mut writer: W) -> Self {
if let Err(e) = write!(writer, "[") {
eprintln!("Write error: {e:?}")
}
Self {
writer,
first: true,
}
}
}
impl<W: io::Write> StateEmitter for JsonEmitter<W> {
fn emit(&mut self, r: &AudioTelemetrySnapshot) {
if !self.first
&& let Err(e) = write!(&mut self.writer, ",")
{
eprintln!("Write error: {e:?}")
} else {
self.first = false
}
if let Err(e) = serde_json::to_writer(&mut self.writer, r) {
eprintln!("Serialization error: {e:?}")
}
self.writer.flush().ok();
}
fn close(&mut self) {
if let Err(e) = write!(&mut self.writer, "]") {
eprintln!("Write error: {e:?}")
}
}
}
impl<W: io::Write> Drop for JsonEmitter<W> {
fn drop(&mut self) {
self.close()
}
}
/// The device exposes one vendor HID interface per usage; pick the one we need. /// The device exposes one vendor HID interface per usage; pick the one we need.
async fn find_device(usage_id: u16) -> HidResult<Device> { async fn find_device(vidpid: &UsbVidPid, usage_id: u16) -> HidResult<Device> {
Ok(HidBackend::default() Ok(HidBackend::default()
.enumerate() .enumerate()
.await? .await?
.find(|d| d.product_id == 0xcc1d && d.vendor_id == 0x1209 && d.usage_id == usage_id) .find(|d| d.product_id == vidpid.pid && d.vendor_id == vidpid.vid && d.usage_id == usage_id)
.await .await
.expect("GUAC device not found or not accessible (try as root?)")) .expect("GUAC device not found or not accessible (try as root?)"))
} }
#[pollster::main] async fn read_telemetry_report(
reader: &mut DeviceReader,
) -> Result<AudioTelemetryReport, HidError> {
let mut buf = [0u8; core::mem::size_of::<AudioTelemetryReport>()];
let r = reader
.read_input_report(&mut buf)
.timeout(Duration::from_secs(1))
.await
.ok_or(HidError::Other("Timeout".into()))??;
log::debug!("read {}: {:?}", r, &buf[..r]);
let buf = &buf[..r];
match AudioTelemetryReport::from_bytes((buf, 0)) {
Ok((_, r)) => Ok(r),
Err(e) => {
eprintln!("Unable to parse report: {:?}", e);
Err(HidError::Message("Unable to parse report".into()))
}
}
}
async fn emit_telemetry_reports(
mut reader: DeviceReader,
mut writer: Box<dyn StateEmitter>,
count: &Option<usize>,
stop: &AtomicBool,
) {
let c = count.unwrap_or(1);
let mut i = 0;
while i < c && !stop.load(Ordering::Relaxed) {
let Ok(r) = read_telemetry_report(&mut reader).await else {
break;
};
writer.emit(&r.into());
i += count.map_or(0, |_| 1)
}
}
main! {
async fn main() -> HidResult<()> { async fn main() -> HidResult<()> {
colog::init(); colog::init();
let args = Args::parse(); let args = Args::parse();
match &args.command { match &args.command {
Some(Command::Monitor) => { Some(Command::Monitor { format, count }) => {
let dev = find_device(USAGE_TELEMETRY).await?; let dev = find_device(&args.device, USAGE_TELEMETRY).await?;
let mut reader = dev.open_readable().await?; let reader = dev.open_readable().await?;
let mut writer: Box<dyn StateEmitter<_>> = match args.format { let writer: Box<dyn StateEmitter> = match format {
Format::Debug => Box::new(DebugEmitter::from_writer(io::stdout())), Format::Debug => Box::new(DebugEmitter::new(io::stdout())),
Format::Csv => Box::new(CsvEmitter::from_writer(io::stdout())), Format::Csv => Box::new(CsvEmitter::new(io::stdout())),
Format::Json => Box::new(JsonEmitter::new(io::stdout())),
}; };
let mut buf = [0u8; core::mem::size_of::<AudioTelemetryReport>()]; let stop = Arc::new(AtomicBool::new(false));
while let Ok(r) = reader.read_input_report(&mut buf).await { let handler_stop = Arc::clone(&stop);
log::debug!("read {}: {:?}", r, &buf[..r]); if let Err(e) = ctrlc::set_handler(move || handler_stop.store(true, Ordering::Relaxed))
let buf = &buf[..r]; {
match AudioTelemetryReport::from_bytes((buf, 0)) { eprintln!("Unable to install Ctrl-C handler: {e}");
Ok((_, r)) => writer.emit(&r.into()),
Err(e) => eprintln!("Unable to parse report: {:?}", e),
} }
emit_telemetry_reports(reader, writer, count, &stop).await
} }
Some(Command::Status { format }) => {
let dev = find_device(&args.device, USAGE_TELEMETRY).await?;
let reader = dev.open_readable().await?;
let writer: Box<dyn StateEmitter> = match format {
Format::Debug => Box::new(DebugEmitter::new(io::stdout())),
Format::Csv => Box::new(CsvEmitter::new(io::stdout())),
Format::Json => Box::new(JsonEmitter::new(io::stdout())),
};
emit_telemetry_reports(reader, writer, &Some(1), &AtomicBool::new(false)).await
} }
Some(Command::Reset { bootloader }) => { Some(Command::Reset { bootloader }) => {
let dev = find_device(USAGE_COMMAND).await?; let dev = find_device(&args.device, USAGE_COMMAND).await?;
let mut dev_writer = dev.open_writeable().await?; let mut dev_writer = dev.open_writeable().await?;
let cmd = if *bootloader { let cmd = if *bootloader {
print!("Rebooting into bootloader..."); print!("Rebooting into bootloader...");
@@ -132,3 +280,4 @@ async fn main() -> HidResult<()> {
Ok(()) Ok(())
} }
}
+2 -2
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "guac" name = "guac"
version = "0.2.0" version = "0.3.1"
edition = "2024" edition = "2024"
[features] [features]
@@ -16,7 +16,6 @@ evk = ["wm8904"]
shared = { path = "../shared" } shared = { path = "../shared" }
atomic = "0.6.1" atomic = "0.6.1"
bbqueue = "0.7.0" bbqueue = "0.7.0"
# bytemuck = { version = "1.25.0", features = ["derive"] }
cortex-m = { version = "0.7.7", features = ["critical-section-single-core"] } cortex-m = { version = "0.7.7", features = ["critical-section-single-core"] }
cortex-m-rt = "0.7.5" cortex-m-rt = "0.7.5"
defmt = "1.0.1" defmt = "1.0.1"
@@ -34,6 +33,7 @@ static_cell = "2.1.1"
usb-device = { version = "0.3", features = ["control-buffer-256"] } usb-device = { version = "0.3", features = ["control-buffer-256"] }
usbd-hid = { version = "0.10.0", optional = true } usbd-hid = { version = "0.10.0", optional = true }
usbd-uac2 = { version = "0.1.2", features = ["defmt"] } usbd-uac2 = { version = "0.1.2", features = ["defmt"] }
bitfield-struct = "0.13.0"
[profile.release] [profile.release]
opt-level = "z" opt-level = "z"
+76 -66
View File
@@ -1,3 +1,4 @@
use bitfield_struct::bitfield;
use hal::Syscon; use hal::Syscon;
use hal::peripherals::syscon::ClockControl; use hal::peripherals::syscon::ClockControl;
@@ -7,8 +8,6 @@ use core::convert::Infallible;
use core::ptr::copy_nonoverlapping; use core::ptr::copy_nonoverlapping;
use core::sync::atomic::{AtomicUsize, Ordering, compiler_fence}; use core::sync::atomic::{AtomicUsize, Ordering, compiler_fence};
pub const DMA0_FLEXCOMM7_TX: u8 = 19;
#[repr(C)] #[repr(C)]
#[derive(Copy, Clone)] #[derive(Copy, Clone)]
pub struct DmaDescriptor { pub struct DmaDescriptor {
@@ -18,6 +17,56 @@ pub struct DmaDescriptor {
pub next: *const 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 { impl defmt::Format for DmaDescriptor {
fn format(&self, fmt: defmt::Formatter) { fn format(&self, fmt: defmt::Formatter) {
defmt::write!( defmt::write!(
@@ -48,7 +97,7 @@ pub struct PushResult {
pub dropped: usize, pub dropped: usize,
} }
#[derive(Debug, Copy, Clone, Eq, PartialEq)] #[derive(Debug, Copy, Clone, defmt::Format, Eq, PartialEq)]
pub enum ConfigError { pub enum ConfigError {
SlotTooLarge, SlotTooLarge,
SlotTooSmall, SlotTooSmall,
@@ -78,7 +127,7 @@ pub struct DmaRing<const N: usize, const MAX_SLOT_BYTES: usize> {
/// Effective bytes per slot (atomic for interior mutability) /// Effective bytes per slot (atomic for interior mutability)
slot_bytes: AtomicUsize, slot_bytes: AtomicUsize,
word_bytes: usize, word_bytes: u8,
write_slot: UnsafeCell<usize>, write_slot: UnsafeCell<usize>,
write_off: UnsafeCell<usize>, write_off: UnsafeCell<usize>,
@@ -97,7 +146,7 @@ impl<const N: usize, const MAX_SLOT_BYTES: usize> DmaRing<N, MAX_SLOT_BYTES> {
dma: pac::DMA0, dma: pac::DMA0,
syscon: &mut Syscon, syscon: &mut Syscon,
dst_reg: *mut u32, dst_reg: *mut u32,
word_bytes: usize, word_bytes: u8,
) -> Result<Self, ConfigError> { ) -> Result<Self, ConfigError> {
if word_bytes != 1 && word_bytes != 2 && word_bytes != 4 { if word_bytes != 1 && word_bytes != 2 && word_bytes != 4 {
return Err(ConfigError::UnsupportedWidth); return Err(ConfigError::UnsupportedWidth);
@@ -107,7 +156,7 @@ impl<const N: usize, const MAX_SLOT_BYTES: usize> DmaRing<N, MAX_SLOT_BYTES> {
Ok(Self { Ok(Self {
dma, dma,
dst_reg: dst_reg, dst_reg,
channel_desc: UnsafeCell::new(DescriptorTable { channel_desc: UnsafeCell::new(DescriptorTable {
d: [DmaDescriptor { d: [DmaDescriptor {
xfercfg: 0, xfercfg: 0,
@@ -138,6 +187,7 @@ impl<const N: usize, const MAX_SLOT_BYTES: usize> DmaRing<N, MAX_SLOT_BYTES> {
} }
/// Optional: adjust safety gap (defaults to 1 empty slot). /// Optional: adjust safety gap (defaults to 1 empty slot).
#[allow(dead_code)]
pub fn set_safety_gap(&mut self, gap_slots: usize) { pub fn set_safety_gap(&mut self, gap_slots: usize) {
self.safety_gap = gap_slots.min(N); self.safety_gap = gap_slots.min(N);
} }
@@ -152,7 +202,7 @@ impl<const N: usize, const MAX_SLOT_BYTES: usize> DmaRing<N, MAX_SLOT_BYTES> {
if slot_bytes > MAX_SLOT_BYTES { if slot_bytes > MAX_SLOT_BYTES {
return Err(ConfigError::SlotTooLarge); 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); return Err(ConfigError::SlotNotAligned);
} }
@@ -253,7 +303,7 @@ impl<const N: usize, const MAX_SLOT_BYTES: usize> DmaRing<N, MAX_SLOT_BYTES> {
let remaining_bytes = if reg_1 == 0x3FF { let remaining_bytes = if reg_1 == 0x3FF {
0 0
} else { } 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 // Active slot consumed calculation accounts for dynamic slot size
@@ -333,30 +383,30 @@ impl<const N: usize, const MAX_SLOT_BYTES: usize> DmaRing<N, MAX_SLOT_BYTES> {
let chan_desc = unsafe { &mut *self.channel_desc.get() }; let chan_desc = unsafe { &mut *self.channel_desc.get() };
// Pre-fill active slot regions with silence // Pre-fill active slot regions with silence
for i in 0..N { for slot in slots.iter_mut() {
slots[i][..slot_bytes].fill(0); 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 { for (i, slot) in slots.iter().enumerate() {
let src_start = slots[i].as_ptr() as usize; let src_start = slot.as_ptr() as usize;
let src_end = (src_start + slot_bytes - self.word_bytes) as *const u8; 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; let next = &desc.d[(i + 1) % N] as *const DmaDescriptor;
desc.d[i] = DmaDescriptor { desc.d[i] = DmaDescriptor {
xfercfg: encode_xfercfg( xfercfg: XferCfg::new()
true, // valid .with_cfgvalid(true) // valid
true, // reload .with_reload(true) // reload
false, // swtrig .with_swtrig(false) // swtrig
false, // clrtrig .with_clrtrig(false) // clrtrig
true, // intA .with_inta(true) // intA
false, // intB .with_intb(false) // intB
self.word_bytes as u32, .with_width(self.word_bytes)
1, // src_inc .with_src_inc(1) // src_inc
0, // dst_inc .with_dst_inc(0) // dst_inc
transfers, .with_transfers(transfers)
), .into_bits(),
src_end, src_end,
dst_end: self.dst_reg, dst_end: self.dst_reg,
next, next,
@@ -374,43 +424,3 @@ impl<const N: usize, const MAX_SLOT_BYTES: usize> DmaRing<N, MAX_SLOT_BYTES> {
} }
unsafe impl<const N: usize, const MAX_SLOT_BYTES: usize> Sync for DmaRing<N, MAX_SLOT_BYTES> {} unsafe impl<const N: usize, const MAX_SLOT_BYTES: usize> Sync for DmaRing<N, MAX_SLOT_BYTES> {}
/// 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)
}
+9 -5
View File
@@ -4,7 +4,7 @@ use core::mem::MaybeUninit;
use crate::hal; use crate::hal;
use crate::pac; use crate::pac;
use defmt::{debug, info}; use defmt::debug;
use hal::{ use hal::{
Enabled, Iocon, Pin, Enabled, Iocon, Pin,
drivers::pins, drivers::pins,
@@ -124,13 +124,16 @@ pub(crate) fn init_sys_pll1() {
syscon.mainclkselb.modify(|_, w| w.sel().enum_0x2()); // 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 // Set PLL0 to 24.576MHz, start, and wait for lock
// This is not exposed by lpc55-hal, unfortunately. Copy their implementation here. // This is not exposed by lpc55-hal, unfortunately. Copy their implementation here.
#[cfg(feature = "evk")]
pub(crate) fn init_audio_pll() { 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 syscon = unsafe { &*pac::SYSCON::ptr() };
let pmc = unsafe { &*pac::PMC::ptr() }; let pmc = unsafe { &*pac::PMC::ptr() };
let anactrl = unsafe { &*pac::ANACTRL::ptr() }; let anactrl = unsafe { &*pac::ANACTRL::ptr() };
@@ -200,6 +203,7 @@ pub struct SharedLed<T: OutputPin> {
inner: UnsafeCell<T>, inner: UnsafeCell<T>,
} }
unsafe impl<T: OutputPin> Sync for SharedLed<T> {} unsafe impl<T: OutputPin> Sync for SharedLed<T> {}
#[allow(dead_code)]
impl<T: OutputPin> SharedLed<T> { impl<T: OutputPin> SharedLed<T> {
pub fn new(inner: T) -> Self { pub fn new(inner: T) -> Self {
Self { Self {
+12 -15
View File
@@ -12,7 +12,6 @@ use core::ptr;
use core::sync::atomic::AtomicPtr; use core::sync::atomic::AtomicPtr;
use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use cortex_m_rt::entry; use cortex_m_rt::entry;
use defmt;
use defmt::debug; use defmt::debug;
use defmt_rtt as _; use defmt_rtt as _;
use hal::Pin; use hal::Pin;
@@ -110,6 +109,7 @@ const HID_INTERVAL_MS: u8 = 10;
const HID_CMD_INTERVAL_MS: u8 = 100; const HID_CMD_INTERVAL_MS: u8 = 100;
struct CodecPins { struct CodecPins {
#[allow(dead_code)]
reset: Pin<pins::Pio0_3, Gpio<Output>>, reset: Pin<pins::Pio0_3, Gpio<Output>>,
} }
@@ -221,7 +221,7 @@ pub struct FeedbackConfig {
impl FeedbackConfig { impl FeedbackConfig {
pub fn new(nominal_rate: u32, target_fill_bytes: usize) -> Self { pub fn new(nominal_rate: u32, target_fill_bytes: usize) -> Self {
Self { Self {
nominal_rate: nominal_rate, nominal_rate,
target_fill_bytes: target_fill_bytes as i32, target_fill_bytes: target_fill_bytes as i32,
deadband_bytes: 4, deadband_bytes: 4,
max_deviation_divider: 500, // 0.2% max_deviation_divider: 500, // 0.2%
@@ -321,11 +321,6 @@ fn cur_fill() -> usize {
produced_bytes.wrapping_sub(consumed_bytes) as 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) /// frames per slot (based on current slot size)
fn frames_per_slot() -> usize { fn frames_per_slot() -> usize {
dma_ring().slot_size() / BYTES_PER_FRAME dma_ring().slot_size() / BYTES_PER_FRAME
@@ -572,7 +567,10 @@ impl<D: Dac<I>, I> ClockSource for Audio<'_, D, I> {
} }
self.cur_rate = sample_rate; self.cur_rate = sample_rate;
let slot_bytes = bytes_per_slot(self.cur_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 self.fb
.update_config(FeedbackConfig::for_rate(self.cur_rate)); .update_config(FeedbackConfig::for_rate(self.cur_rate));
if 24_576_000u32.is_multiple_of(sample_rate) { if 24_576_000u32.is_multiple_of(sample_rate) {
@@ -669,7 +667,7 @@ impl<D: Dac<I>, I, B: bus::UsbBus> AudioHandler<'_, B> for Audio<'_, D, I> {
AudioState::Running => {} 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 // 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 => { 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 // 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() { if fill >= queue_running_up_threshold() {
self.transition(AudioState::Running); self.transition(AudioState::Running);
@@ -812,7 +810,7 @@ fn main() -> ! {
pins::Pio1_20::take().unwrap().into_i2c4_scl_pin(&mut iocon), pins::Pio1_20::take().unwrap().into_i2c4_scl_pin(&mut iocon),
pins::Pio1_21::take().unwrap().into_i2c4_sda_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_21::take().unwrap().into_spi7_sck_pin(&mut iocon),
pins::Pio0_20::take().unwrap().into_i2s7_sda_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), pins::Pio0_19::take().unwrap().into_i2s7_ws_pin(&mut iocon),
@@ -995,11 +993,11 @@ fn main() -> ! {
if hid_update_timer.wait().is_ok() { if hid_update_timer.wait().is_ok() {
let report = build_telemetry_report(&PERF, uac2.handler()); let report = build_telemetry_report(&PERF, uac2.handler());
if let Err(e) = hid.push_input(&report) { if let Err(e) = hid.push_input(&report)
if e != UsbError::WouldBlock { && e != UsbError::WouldBlock
{
defmt::error!("Failed to send HID report: {:?}", e); defmt::error!("Failed to send HID report: {:?}", e);
} }
}
// LPC55 CTIMER is not periodic; restart manually // LPC55 CTIMER is not periodic; restart manually
hid_update_timer.start(Microseconds::new(HID_INTERVAL_MS as u32 * 1000)); hid_update_timer.start(Microseconds::new(HID_INTERVAL_MS as u32 * 1000));
} }
@@ -1008,12 +1006,11 @@ fn main() -> ! {
Ok(len) => { Ok(len) => {
if let Ok((_left, cmd)) = if let Ok((_left, cmd)) =
AudioDeviceCommandReport::from_bytes((&cmd_report_buf[0..len], 0)) 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) => {} Err(UsbError::WouldBlock) => {}
Err(e) => defmt::error!("Invalid report: {:?}", e), Err(e) => defmt::error!("Invalid report: {:?}", e),
} }
+1
View File
@@ -5,6 +5,7 @@ pub trait Dac<T> {
fn init(&mut self); fn init(&mut self);
fn change_rate(&mut self, new_rate: u32); fn change_rate(&mut self, new_rate: u32);
#[allow(unused_variables)] #[allow(unused_variables)]
#[allow(dead_code)]
fn set_volume(&mut self, left: u8, right: u8) {} fn set_volume(&mut self, left: u8, right: u8) {}
fn mute(&mut self); fn mute(&mut self);
fn unmute(&mut self); fn unmute(&mut self);
+2 -9
View File
@@ -9,13 +9,14 @@ use num_enum::TryFromPrimitive;
#[cfg(feature = "serde")] #[cfg(feature = "serde")]
use serde::{Deserialize, Serialize}; 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))] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[repr(u8)] #[repr(u8)]
pub enum AudioState { pub enum AudioState {
/// Knowingly stopped, ie. AltSetting=0. DAC muted, I2S disabled. /// Knowingly stopped, ie. AltSetting=0. DAC muted, I2S disabled.
/// ///
/// AltSetting = 1 -> ARMED /// AltSetting = 1 -> ARMED
#[default]
Stopped = 0, Stopped = 0,
/// Waiting for data. DAC muted, I2S running sending 0s (FIFO not serviced). /// Waiting for data. DAC muted, I2S running sending 0s (FIFO not serviced).
/// ///
@@ -52,11 +53,6 @@ pub enum AudioState {
Stopping = 6, Stopping = 6,
} }
impl Default for AudioState {
fn default() -> Self {
AudioState::Stopped
}
}
impl defmt::Format for AudioState { impl defmt::Format for AudioState {
fn format(&self, fmt: defmt::Formatter) { fn format(&self, fmt: defmt::Formatter) {
defmt::write!( defmt::write!(
@@ -125,9 +121,6 @@ pub mod hid {
use deku::{DekuContainerWrite, DekuWrite}; use deku::{DekuContainerWrite, DekuWrite};
use usbd_hid::descriptor::generator_prelude::*; use usbd_hid::descriptor::generator_prelude::*;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
use crate::{AudioDeviceCommand, AudioState, AudioTelemetrySnapshot}; use crate::{AudioDeviceCommand, AudioState, AudioTelemetrySnapshot};
/// HID usage IDs identifying each vendor interface. `gen_hid_descriptor` only accepts /// HID usage IDs identifying each vendor interface. `gen_hid_descriptor` only accepts