Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1e87561b37
|
No files matched your search
+45
-134
@@ -7,149 +7,60 @@ on:
|
||||
|
||||
env:
|
||||
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:
|
||||
firmware:
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: catthehacker/ubuntu:rust-latest
|
||||
strategy:
|
||||
fail-fast: true
|
||||
matrix:
|
||||
variant: [cs4398, ak4490, evk]
|
||||
env:
|
||||
FEATURES: ${{ matrix.variant }},hid
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
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
|
||||
run: |
|
||||
rustup target install ${{ env.TARGET }}
|
||||
rustup component add llvm-tools
|
||||
|
||||
- name: Cache cargo
|
||||
uses: Swatinem/rust-cache@v2
|
||||
with:
|
||||
shared-key: firmware-${{ matrix.variant }}
|
||||
|
||||
- name: Install cargo-binutils
|
||||
run: cargo binstall -y --locked cargo-binutils
|
||||
|
||||
- name: Build firmware (${{ matrix.variant }})
|
||||
working-directory: firmware
|
||||
run: cargo build --release --target ${{ env.TARGET }} --no-default-features --features "${{ env.FEATURES }}"
|
||||
|
||||
- name: Create hex file
|
||||
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
|
||||
|
||||
- name: Package
|
||||
run: |
|
||||
out=target/${{ env.TARGET }}/release
|
||||
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"
|
||||
|
||||
- name: Upload artifact
|
||||
uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: firmware-${{ matrix.variant }}
|
||||
path: dist/*.zip
|
||||
|
||||
cli:
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
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=cli
|
||||
[[ "${{ matrix.target }}" == *windows* ]] && bin=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]
|
||||
build-and-release:
|
||||
runs-on: ubuntu-latest
|
||||
container:
|
||||
image: catthehacker/ubuntu:act-latest
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
steps:
|
||||
- name: Download artifacts
|
||||
uses: actions/download-artifact@v3
|
||||
with:
|
||||
path: dist
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Install Rust Toolchain
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
- name: Install cargo-binutils
|
||||
run: cargo install cargo-binutils
|
||||
- name: Build Firmware Binaries
|
||||
run: |
|
||||
cd firmware
|
||||
|
||||
# Array of "variant_name:features"
|
||||
VARIANTS=(
|
||||
"cs4398:cs4398,hid"
|
||||
"ak4490:ak4490,hid"
|
||||
"evk:evk,hid"
|
||||
)
|
||||
|
||||
mkdir -p ../dist
|
||||
|
||||
for entry in "${VARIANTS[@]}"; do
|
||||
IFS=":" read -r name features <<< "$entry"
|
||||
echo "Building variant: $name with features: $features"
|
||||
|
||||
# 1. Compile release binary
|
||||
cargo build --release --target ${{ env.TARGET }} --no-default-features --features "$features"
|
||||
|
||||
# 2. Paths setup
|
||||
ELF_PATH="../target/${{ env.TARGET }}/release/guac"
|
||||
HEX_PATH="../target/${{ env.TARGET }}/release/guac-${name}.hex"
|
||||
RENAMED_ELF="../target/${{ env.TARGET }}/release/guac-${name}.elf"
|
||||
|
||||
# 3. Create .hex file via rust-objcopy
|
||||
cargo objcopy --release --target ${{ env.TARGET }} --no-default-features --features "$features" -- -O ihex "$HEX_PATH"
|
||||
cp "$ELF_PATH" "$RENAMED_ELF"
|
||||
|
||||
# 4. Package ELF and HEX into target-specific ZIP
|
||||
ZIP_NAME="guac-firmware-${name}.zip"
|
||||
zip -j "../dist/${ZIP_NAME}" "$RENAMED_ELF" "$HEX_PATH"
|
||||
done
|
||||
|
||||
- name: Create Gitea Release
|
||||
uses: akkuman/gitea-release-action@v1
|
||||
with:
|
||||
files: dist/**/*.zip
|
||||
files: dist/*.zip
|
||||
draft: false
|
||||
prerelease: false
|
||||
Generated
+3
-15
@@ -173,17 +173,6 @@ 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"
|
||||
@@ -336,7 +325,7 @@ checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9"
|
||||
|
||||
[[package]]
|
||||
name = "cli"
|
||||
version = "0.3.0"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"async-hid",
|
||||
"clap",
|
||||
@@ -767,16 +756,15 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "guac"
|
||||
version = "0.3.0"
|
||||
version = "0.2.0"
|
||||
dependencies = [
|
||||
"atomic",
|
||||
"bbqueue",
|
||||
"bitfield-struct",
|
||||
"bytemuck",
|
||||
"cortex-m",
|
||||
"cortex-m-rt",
|
||||
"defmt 1.1.1",
|
||||
"defmt-rtt",
|
||||
"deku",
|
||||
"embedded-hal",
|
||||
"embedded-io",
|
||||
"log-to-defmt",
|
||||
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "cli"
|
||||
version = "0.3.0"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
@@ -12,4 +12,4 @@ deku = "0.20.3"
|
||||
futures-lite = "2.6.1"
|
||||
log = { version = "0.4.29", features = ["std"] }
|
||||
pollster = { version = "0.4.0", features = ["macro"] }
|
||||
shared = { path = "../shared", features = ["serde", "std"] }
|
||||
shared = { path = "../shared", features = ["serde"] }
|
||||
+23
-68
@@ -1,13 +1,10 @@
|
||||
use std::io;
|
||||
|
||||
use async_hid::{AsyncHidRead, AsyncHidWrite, Device, HidBackend, HidResult};
|
||||
use clap::{Parser, Subcommand, ValueEnum};
|
||||
use async_hid::{AsyncHidRead, HidBackend, HidResult};
|
||||
use clap::{Parser, ValueEnum};
|
||||
use deku::DekuContainerRead;
|
||||
use futures_lite::StreamExt;
|
||||
use shared::{
|
||||
AudioDeviceCommand, AudioTelemetrySnapshot,
|
||||
hid::{AudioDeviceCommandReport, AudioTelemetryReport, USAGE_COMMAND, USAGE_TELEMETRY},
|
||||
};
|
||||
use shared::{AudioTelemetrySnapshot, hid::AudioTelemetryReport};
|
||||
|
||||
#[derive(Clone, Copy, Debug, ValueEnum)]
|
||||
enum Format {
|
||||
@@ -15,22 +12,11 @@ enum Format {
|
||||
Csv,
|
||||
}
|
||||
|
||||
#[derive(Subcommand, Clone, Copy, Debug)]
|
||||
enum Command {
|
||||
Monitor,
|
||||
Reset {
|
||||
#[arg(short, long, default_value_t = false)]
|
||||
bootloader: bool,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(version, about)]
|
||||
struct Args {
|
||||
#[arg(short, long, default_value = "debug")]
|
||||
format: Format,
|
||||
#[command(subcommand)]
|
||||
command: Option<Command>,
|
||||
}
|
||||
|
||||
trait StateEmitter<W: io::Write> {
|
||||
@@ -49,7 +35,7 @@ impl<W: io::Write> StateEmitter<W> for DebugEmitter<W> {
|
||||
Self { writer }
|
||||
}
|
||||
fn emit(&mut self, r: &AudioTelemetrySnapshot) {
|
||||
writeln!(self.writer, "{r:?}").ok();
|
||||
writeln!(self.writer, "{r:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -72,62 +58,31 @@ impl<W: io::Write> StateEmitter<W> for CsvEmitter<W> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The device exposes one vendor HID interface per usage; pick the one we need.
|
||||
async fn find_device(usage_id: u16) -> HidResult<Device> {
|
||||
Ok(HidBackend::default()
|
||||
.enumerate()
|
||||
.await?
|
||||
.find(|d| d.product_id == 0xcc1d && d.vendor_id == 0x1209 && d.usage_id == usage_id)
|
||||
.await
|
||||
.expect("GUAC device not found or not accessible (try as root?)"))
|
||||
}
|
||||
|
||||
#[pollster::main]
|
||||
async fn main() -> HidResult<()> {
|
||||
colog::init();
|
||||
let args = Args::parse();
|
||||
let usbhid = HidBackend::default();
|
||||
let dev = usbhid
|
||||
.enumerate()
|
||||
.await?
|
||||
.find(|d| d.product_id == 0xcc1d && d.vendor_id == 0x1209)
|
||||
.await
|
||||
.expect("GUAC device not found or not accessible (try as root?)");
|
||||
let mut reader = dev.open_readable().await?;
|
||||
let mut writer: Box<dyn StateEmitter<_>> = match args.format {
|
||||
Format::Debug => Box::new(DebugEmitter::from_writer(io::stdout())),
|
||||
Format::Csv => Box::new(CsvEmitter::from_writer(io::stdout())),
|
||||
};
|
||||
|
||||
match &args.command {
|
||||
Some(Command::Monitor) => {
|
||||
let dev = find_device(USAGE_TELEMETRY).await?;
|
||||
let mut reader = dev.open_readable().await?;
|
||||
let mut writer: Box<dyn StateEmitter<_>> = match args.format {
|
||||
Format::Debug => Box::new(DebugEmitter::from_writer(io::stdout())),
|
||||
Format::Csv => Box::new(CsvEmitter::from_writer(io::stdout())),
|
||||
};
|
||||
|
||||
let mut buf = [0u8; core::mem::size_of::<AudioTelemetryReport>()];
|
||||
while let Ok(r) = reader.read_input_report(&mut buf).await {
|
||||
log::debug!("read {}: {:?}", r, &buf[..r]);
|
||||
let buf = &buf[..r];
|
||||
match AudioTelemetryReport::from_bytes((buf, 0)) {
|
||||
Ok((_, r)) => writer.emit(&r.into()),
|
||||
Err(e) => eprintln!("Unable to parse report: {:?}", e),
|
||||
}
|
||||
}
|
||||
let mut buf = [0u8; core::mem::size_of::<AudioTelemetryReport>()];
|
||||
while let Ok(r) = reader.read_input_report(&mut buf).await {
|
||||
log::debug!("read {}: {:?}", r, &buf[..r]);
|
||||
let buf = &buf[..r];
|
||||
match AudioTelemetryReport::from_bytes((buf, 0)) {
|
||||
Ok((_, r)) => writer.emit(&r.into()),
|
||||
Err(e) => eprintln!("Unable to parse report: {:?}", e),
|
||||
}
|
||||
Some(Command::Reset { bootloader }) => {
|
||||
let dev = find_device(USAGE_COMMAND).await?;
|
||||
let mut dev_writer = dev.open_writeable().await?;
|
||||
let cmd = if *bootloader {
|
||||
print!("Rebooting into bootloader...");
|
||||
AudioDeviceCommand::Bootloader
|
||||
} else {
|
||||
print!("Rebooting...");
|
||||
AudioDeviceCommand::Reset
|
||||
};
|
||||
log::debug!("writing command: {:?}", &cmd);
|
||||
let report: AudioDeviceCommandReport = cmd.into();
|
||||
log::debug!(" report: {:?}", &report);
|
||||
// Our descriptor has no report IDs, so hidraw expects a leading 0x00 that it strips
|
||||
let mut buf = [0u8; 1 + core::mem::size_of::<AudioDeviceCommandReport>()];
|
||||
buf[1..].copy_from_slice(&report.cmd);
|
||||
match dev_writer.write_output_report(&buf).await {
|
||||
Ok(_) => println!("write succeeded - reboot failed"),
|
||||
Err(_) => println!("lost device - reboot successful"),
|
||||
}
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
|
||||
+6
-7
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "guac"
|
||||
version = "0.3.0"
|
||||
version = "0.2.0"
|
||||
edition = "2024"
|
||||
|
||||
[features]
|
||||
@@ -9,18 +9,18 @@ ak4490 = []
|
||||
cs4398 = []
|
||||
nodac = []
|
||||
wm8904 = []
|
||||
hid = ["dep:usbd-hid", "dep:deku"]
|
||||
evk = ["wm8904"]
|
||||
hid = [ "dep:usbd-hid" ]
|
||||
evk = [ "wm8904" ]
|
||||
|
||||
[dependencies]
|
||||
shared = { path = "../shared" }
|
||||
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"
|
||||
defmt-rtt = "1.1.0"
|
||||
deku = { version = "0.20.3", optional = true, default-features = false }
|
||||
embedded-hal = "0.2.7"
|
||||
embedded-io = "0.7.1"
|
||||
log-to-defmt = "0.1.0"
|
||||
@@ -32,8 +32,7 @@ panic-probe = { version = "1.0.0", features = ["print-defmt"] }
|
||||
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"
|
||||
usbd-uac2 = { version = "0.1.2", features = ["defmt"]}
|
||||
|
||||
[profile.release]
|
||||
opt-level = "z"
|
||||
|
||||
+66
-78
@@ -1,4 +1,3 @@
|
||||
use bitfield_struct::bitfield;
|
||||
use hal::Syscon;
|
||||
use hal::peripherals::syscon::ClockControl;
|
||||
|
||||
@@ -8,6 +7,8 @@ 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 {
|
||||
@@ -17,56 +18,6 @@ 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!(
|
||||
@@ -97,7 +48,7 @@ pub struct PushResult {
|
||||
pub dropped: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Copy, Clone, defmt::Format, Eq, PartialEq)]
|
||||
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
|
||||
pub enum ConfigError {
|
||||
SlotTooLarge,
|
||||
SlotTooSmall,
|
||||
@@ -127,7 +78,7 @@ pub struct DmaRing<const N: usize, const MAX_SLOT_BYTES: usize> {
|
||||
|
||||
/// Effective bytes per slot (atomic for interior mutability)
|
||||
slot_bytes: AtomicUsize,
|
||||
word_bytes: u8,
|
||||
word_bytes: usize,
|
||||
|
||||
write_slot: UnsafeCell<usize>,
|
||||
write_off: UnsafeCell<usize>,
|
||||
@@ -146,7 +97,7 @@ impl<const N: usize, const MAX_SLOT_BYTES: usize> DmaRing<N, MAX_SLOT_BYTES> {
|
||||
dma: pac::DMA0,
|
||||
syscon: &mut Syscon,
|
||||
dst_reg: *mut u32,
|
||||
word_bytes: u8,
|
||||
word_bytes: usize,
|
||||
) -> Result<Self, ConfigError> {
|
||||
if word_bytes != 1 && word_bytes != 2 && word_bytes != 4 {
|
||||
return Err(ConfigError::UnsupportedWidth);
|
||||
@@ -156,7 +107,7 @@ impl<const N: usize, const MAX_SLOT_BYTES: usize> DmaRing<N, MAX_SLOT_BYTES> {
|
||||
|
||||
Ok(Self {
|
||||
dma,
|
||||
dst_reg,
|
||||
dst_reg: dst_reg,
|
||||
channel_desc: UnsafeCell::new(DescriptorTable {
|
||||
d: [DmaDescriptor {
|
||||
xfercfg: 0,
|
||||
@@ -187,7 +138,6 @@ impl<const N: usize, const MAX_SLOT_BYTES: usize> DmaRing<N, MAX_SLOT_BYTES> {
|
||||
}
|
||||
|
||||
/// 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);
|
||||
}
|
||||
@@ -202,7 +152,7 @@ impl<const N: usize, const MAX_SLOT_BYTES: usize> DmaRing<N, MAX_SLOT_BYTES> {
|
||||
if slot_bytes > MAX_SLOT_BYTES {
|
||||
return Err(ConfigError::SlotTooLarge);
|
||||
}
|
||||
if !slot_bytes.is_multiple_of(self.word_bytes as usize) {
|
||||
if slot_bytes % self.word_bytes != 0 {
|
||||
return Err(ConfigError::SlotNotAligned);
|
||||
}
|
||||
|
||||
@@ -303,7 +253,7 @@ impl<const N: usize, const MAX_SLOT_BYTES: usize> DmaRing<N, MAX_SLOT_BYTES> {
|
||||
let remaining_bytes = if reg_1 == 0x3FF {
|
||||
0
|
||||
} else {
|
||||
(reg_1 as usize + 1) * self.word_bytes as usize
|
||||
(reg_1 as usize + 1) * self.word_bytes
|
||||
};
|
||||
|
||||
// Active slot consumed calculation accounts for dynamic slot size
|
||||
@@ -344,8 +294,6 @@ impl<const N: usize, const MAX_SLOT_BYTES: usize> DmaRing<N, MAX_SLOT_BYTES> {
|
||||
}
|
||||
|
||||
pub fn run(&self) {
|
||||
self.dma.inta0.write(|w| unsafe { w.bits(1 << 19) });
|
||||
self.dma.errint0.write(|w| unsafe { w.bits(1 << 19) });
|
||||
self.dma.enableset0.write(|w| unsafe { w.bits(1 << 19) });
|
||||
}
|
||||
|
||||
@@ -383,30 +331,30 @@ impl<const N: usize, const MAX_SLOT_BYTES: usize> DmaRing<N, MAX_SLOT_BYTES> {
|
||||
let chan_desc = unsafe { &mut *self.channel_desc.get() };
|
||||
|
||||
// Pre-fill active slot regions with silence
|
||||
for slot in slots.iter_mut() {
|
||||
slot.fill(0);
|
||||
for i in 0..N {
|
||||
slots[i][..slot_bytes].fill(0);
|
||||
}
|
||||
|
||||
let transfers = (slot_bytes / self.word_bytes as usize) as u32;
|
||||
let transfers = (slot_bytes / self.word_bytes) as u32;
|
||||
|
||||
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;
|
||||
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;
|
||||
let next = &desc.d[(i + 1) % N] as *const DmaDescriptor;
|
||||
|
||||
desc.d[i] = DmaDescriptor {
|
||||
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(),
|
||||
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,
|
||||
),
|
||||
src_end,
|
||||
dst_end: self.dst_reg,
|
||||
next,
|
||||
@@ -424,3 +372,43 @@ 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> {}
|
||||
|
||||
/// 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)
|
||||
}
|
||||
+5
-9
@@ -4,7 +4,7 @@ use core::mem::MaybeUninit;
|
||||
use crate::hal;
|
||||
use crate::pac;
|
||||
|
||||
use defmt::debug;
|
||||
use defmt::{debug, info};
|
||||
use hal::{
|
||||
Enabled, Iocon, Pin,
|
||||
drivers::pins,
|
||||
@@ -124,16 +124,13 @@ 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() };
|
||||
@@ -203,7 +200,6 @@ pub struct SharedLed<T: OutputPin> {
|
||||
inner: UnsafeCell<T>,
|
||||
}
|
||||
unsafe impl<T: OutputPin> Sync for SharedLed<T> {}
|
||||
#[allow(dead_code)]
|
||||
impl<T: OutputPin> SharedLed<T> {
|
||||
pub fn new(inner: T) -> Self {
|
||||
Self {
|
||||
|
||||
+163
-265
@@ -8,10 +8,9 @@ fn panic() -> ! {
|
||||
}
|
||||
|
||||
use atomic::Atomic;
|
||||
use core::ptr;
|
||||
use core::sync::atomic::AtomicPtr;
|
||||
use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||
use core::sync::atomic::{AtomicBool, AtomicI32, AtomicUsize, Ordering};
|
||||
use cortex_m_rt::entry;
|
||||
use defmt;
|
||||
use defmt::debug;
|
||||
use defmt_rtt as _;
|
||||
use hal::Pin;
|
||||
@@ -43,7 +42,7 @@ use crate::hw::led1;
|
||||
use crate::hw::led2;
|
||||
use crate::traits::Dac;
|
||||
use shared::AudioState;
|
||||
use shared::hid::{AudioDeviceCommandReport, AudioTelemetryReport};
|
||||
use shared::hid::AudioTelemetryReport;
|
||||
|
||||
#[cfg(feature = "ak4490")]
|
||||
pub mod dac {
|
||||
@@ -106,10 +105,8 @@ const USB_FRAME_RATE: u32 = 8000; // microframe rate: 8000 for HS, 1000 for FS
|
||||
// const NODATA_TIMEOUT_FRAMES: usize = SAMPLE_RATE as usize / 100; // ~100ms
|
||||
|
||||
const HID_INTERVAL_MS: u8 = 10;
|
||||
const HID_CMD_INTERVAL_MS: u8 = 100;
|
||||
|
||||
struct CodecPins {
|
||||
#[allow(dead_code)]
|
||||
reset: Pin<pins::Pio0_3, Gpio<Output>>,
|
||||
}
|
||||
|
||||
@@ -120,29 +117,47 @@ struct ClockSelPins {
|
||||
|
||||
#[derive(Default)]
|
||||
struct PerfCounters {
|
||||
// state: Atomic<AudioState>,
|
||||
state: Atomic<AudioState>,
|
||||
received_frames: AtomicUsize,
|
||||
played_frames: AtomicUsize,
|
||||
// min_fill: AtomicUsize,
|
||||
// avg_fill: AtomicUsize,
|
||||
min_fill: AtomicUsize,
|
||||
avg_fill: AtomicUsize,
|
||||
queue_underflows: AtomicUsize,
|
||||
queue_overflows: AtomicUsize,
|
||||
audio_underflows: AtomicUsize,
|
||||
// p: AtomicI32,
|
||||
// fb: AtomicI32,
|
||||
integrator: AtomicI32,
|
||||
p: AtomicI32,
|
||||
i: AtomicI32,
|
||||
fb: AtomicI32,
|
||||
}
|
||||
|
||||
impl PerfCounters {
|
||||
fn reset(&self) {
|
||||
self.received_frames.store(0, Ordering::Relaxed);
|
||||
self.played_frames.store(0, Ordering::Relaxed);
|
||||
// self.min_fill
|
||||
// .store(N_SLOTS * MAX_BYTES_PER_SLOT, Ordering::Relaxed);
|
||||
// self.avg_fill.store(0 as usize, Ordering::Relaxed);
|
||||
self.min_fill
|
||||
.store(N_SLOTS * MAX_BYTES_PER_SLOT, Ordering::Relaxed);
|
||||
self.avg_fill.store(0 as usize, Ordering::Relaxed);
|
||||
self.queue_underflows.store(0, Ordering::Relaxed);
|
||||
self.queue_overflows.store(0, Ordering::Relaxed);
|
||||
self.audio_underflows.store(0, Ordering::Relaxed);
|
||||
// self.p.store(0, Ordering::Relaxed);
|
||||
self.p.store(0, Ordering::Relaxed);
|
||||
self.i.store(0, Ordering::Relaxed);
|
||||
// FB loop will have to take care of the fb value
|
||||
}
|
||||
fn build_report(&self) -> AudioTelemetryReport {
|
||||
AudioTelemetryReport {
|
||||
state: self.state.load(Ordering::Relaxed) as u8,
|
||||
average_buffer_fill: self.avg_fill.load(Ordering::Relaxed) as u16,
|
||||
frame_count: self.played_frames.load(Ordering::Relaxed) as i32,
|
||||
dac_underflow_count: self.audio_underflows.load(Ordering::Relaxed) as u16,
|
||||
usb_underflow_count: self.queue_underflows.load(Ordering::Relaxed) as u16,
|
||||
dac_overflow_count: self.queue_overflows.load(Ordering::Relaxed) as u16,
|
||||
integrator: self.integrator.load(Ordering::Relaxed),
|
||||
p: self.p.load(Ordering::Relaxed),
|
||||
i: self.i.load(Ordering::Relaxed),
|
||||
fb: u32::cast_signed(self.fb.load(Ordering::Relaxed) as u32),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -150,11 +165,11 @@ impl defmt::Format for PerfCounters {
|
||||
fn format(&self, fmt: defmt::Formatter) {
|
||||
defmt::write!(
|
||||
fmt,
|
||||
"frames: {}/{} a_underflows: {} q_underflows: {} q_overflows: {}",
|
||||
"frames: {}/{} min_fill: {} avg fill: {} a_underflows: {} q_underflows: {} q_overflows: {}",
|
||||
self.played_frames.load(Ordering::Relaxed),
|
||||
self.received_frames.load(Ordering::Relaxed),
|
||||
// self.min_fill.load(Ordering::Relaxed),
|
||||
// self.avg_fill.load(Ordering::Relaxed),
|
||||
self.min_fill.load(Ordering::Relaxed),
|
||||
self.avg_fill.load(Ordering::Relaxed),
|
||||
self.audio_underflows.load(Ordering::Relaxed),
|
||||
self.queue_underflows.load(Ordering::Relaxed),
|
||||
self.queue_overflows.load(Ordering::Relaxed)
|
||||
@@ -163,154 +178,27 @@ impl defmt::Format for PerfCounters {
|
||||
}
|
||||
|
||||
static PERF: PerfCounters = PerfCounters {
|
||||
// state: Atomic::new(AudioState::Stopped),
|
||||
state: Atomic::new(AudioState::Stopped),
|
||||
received_frames: AtomicUsize::new(0), // received from USB
|
||||
played_frames: AtomicUsize::new(0), // played audio frames
|
||||
// min_fill: AtomicUsize::new(0), // not recording this for now, need to figure out how to make it meaningful, since the queue starts empty
|
||||
// avg_fill: AtomicUsize::new(0),
|
||||
min_fill: AtomicUsize::new(0), // not recording this for now, need to figure out how to make it meaningful, since the queue starts empty
|
||||
avg_fill: AtomicUsize::new(0),
|
||||
queue_underflows: AtomicUsize::new(0), // ditto here, since we underflow at startup, but we record this one as it can be trended
|
||||
queue_overflows: AtomicUsize::new(0),
|
||||
audio_underflows: AtomicUsize::new(0),
|
||||
// p: AtomicI32::new(0),
|
||||
// fb: AtomicI32::new(0),
|
||||
integrator: AtomicI32::new(0),
|
||||
p: AtomicI32::new(0),
|
||||
i: AtomicI32::new(0),
|
||||
fb: AtomicI32::new(0),
|
||||
};
|
||||
|
||||
fn boot_to_bootloader() -> ! {
|
||||
cortex_m::interrupt::disable();
|
||||
unsafe {
|
||||
let pmc = &*pac::PMC::ptr();
|
||||
// https://community.nxp.com/t5/LPC-Microcontrollers/Configure-LPC55-to-enter-re-invoke-ROM-Bootloader-from/m-p/966990?profile.language=en
|
||||
// If you write the following register, it will be set to boot from the ROM:
|
||||
// PMC->AOREG1 |= (0x0A << 16); //Set to boot from ROM
|
||||
// NVIC_SystemReset(); //Reset
|
||||
pmc.aoreg1.modify(|r, w| w.bits(r.bits() | (0x0a << 16)));
|
||||
}
|
||||
cortex_m::peripheral::SCB::sys_reset()
|
||||
}
|
||||
|
||||
fn build_telemetry_report<D: Dac<I>, I>(
|
||||
perf: &PerfCounters,
|
||||
audio: &Audio<D, I>,
|
||||
) -> AudioTelemetryReport {
|
||||
AudioTelemetryReport {
|
||||
state: audio.state.load(Ordering::Relaxed) as u8,
|
||||
average_buffer_fill: audio.fb.avg_fill as u16,
|
||||
frame_count: perf.played_frames.load(Ordering::Relaxed).cast_signed() as i32,
|
||||
dac_underflow_count: perf.audio_underflows.load(Ordering::Relaxed) as u16,
|
||||
usb_underflow_count: perf.queue_underflows.load(Ordering::Relaxed) as u16,
|
||||
dac_overflow_count: perf.queue_overflows.load(Ordering::Relaxed) as u16,
|
||||
cur_rate: audio.cur_rate.cast_signed(),
|
||||
fb_rate_estimate: audio.fb.current_freq_estimate() as i32,
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct FeedbackConfig {
|
||||
/// Nominal USB rate in Q12.13 fixed-point format (or target sample rate context).
|
||||
pub nominal_rate: u32,
|
||||
/// Target ring buffer fill level in bytes.
|
||||
pub target_fill_bytes: i32,
|
||||
/// Deadband threshold in bytes (e.g., 4).
|
||||
pub deadband_bytes: i32,
|
||||
/// Maximum allowed feedback deviation permille denominator (e.g., 500 => 0.2%).
|
||||
pub max_deviation_divider: i32,
|
||||
/// Master toggle for feedback correction.
|
||||
pub correction_enabled: bool,
|
||||
}
|
||||
|
||||
impl FeedbackConfig {
|
||||
pub fn new(nominal_rate: u32, target_fill_bytes: usize) -> Self {
|
||||
Self {
|
||||
nominal_rate,
|
||||
target_fill_bytes: target_fill_bytes as i32,
|
||||
deadband_bytes: 4,
|
||||
max_deviation_divider: 500, // 0.2%
|
||||
correction_enabled: true,
|
||||
}
|
||||
}
|
||||
pub fn for_rate(nominal_rate: u32) -> Self {
|
||||
let target_fill_bytes = (bytes_per_slot(nominal_rate) * N_SLOTS) / 2;
|
||||
Self::new(nominal_rate, target_fill_bytes)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct FeedbackLoop {
|
||||
pub config: FeedbackConfig,
|
||||
pub avg_fill: usize,
|
||||
last_freq: u32,
|
||||
}
|
||||
|
||||
impl FeedbackLoop {
|
||||
pub fn new(config: FeedbackConfig) -> Self {
|
||||
Self {
|
||||
config,
|
||||
avg_fill: config.target_fill_bytes as usize,
|
||||
last_freq: config.nominal_rate,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn reset(&mut self) {
|
||||
self.avg_fill = self.config.target_fill_bytes as usize;
|
||||
self.last_freq = self.config.nominal_rate
|
||||
}
|
||||
|
||||
pub fn update_config(&mut self, config: FeedbackConfig) {
|
||||
self.config = config;
|
||||
self.reset();
|
||||
}
|
||||
|
||||
pub fn compute(
|
||||
&mut self,
|
||||
nominal_rate: UsbIsochronousFeedback,
|
||||
current_fill_bytes: usize,
|
||||
) -> UsbIsochronousFeedback {
|
||||
if !self.config.correction_enabled {
|
||||
return nominal_rate;
|
||||
}
|
||||
|
||||
let current_bytes = current_fill_bytes as i32;
|
||||
|
||||
if current_bytes == 0 {
|
||||
defmt::error!("[fb] dma underrun detected!");
|
||||
PERF.queue_underflows.fetch_add(1, Ordering::Relaxed);
|
||||
return nominal_rate;
|
||||
}
|
||||
|
||||
self.avg_fill = ((self.avg_fill << 6) - self.avg_fill + current_bytes as usize) >> 6;
|
||||
|
||||
let target_fill = self.config.target_fill_bytes;
|
||||
let raw_error = current_bytes - target_fill;
|
||||
|
||||
let nominal_v = nominal_rate.to_u32_12_13() as i32;
|
||||
let max_allowed_deviation = nominal_v / self.config.max_deviation_divider;
|
||||
|
||||
let error_permille = (raw_error * 1000) / target_fill;
|
||||
let p_term = (-((error_permille as i64) * (nominal_v as i64)) / (10 * 256000)) as i32;
|
||||
|
||||
let mut v = nominal_v + p_term;
|
||||
v = v.clamp(
|
||||
nominal_v - max_allowed_deviation,
|
||||
nominal_v + max_allowed_deviation,
|
||||
);
|
||||
self.last_freq = v as u32;
|
||||
UsbIsochronousFeedback::new(v as u32)
|
||||
}
|
||||
|
||||
pub fn current_freq_estimate(&self) -> f32 {
|
||||
// Divides by 8 (frame-to-microframe) and 65536.0 (Q16.16 shift)
|
||||
(self.last_freq as f32 / (65536.0)) * USB_FRAME_RATE as f32
|
||||
}
|
||||
}
|
||||
|
||||
static NODATA_FLAG: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
static DMA_RING: StaticCell<DmaRing<N_SLOTS, MAX_BYTES_PER_SLOT>> = StaticCell::new();
|
||||
static DMA_RING_PTR: AtomicPtr<DmaRing<N_SLOTS, MAX_BYTES_PER_SLOT>> =
|
||||
AtomicPtr::new(ptr::null_mut());
|
||||
static mut DMA_RING_REF: Option<&'static DmaRing<N_SLOTS, MAX_BYTES_PER_SLOT>> = None;
|
||||
#[inline]
|
||||
fn dma_ring() -> &'static DmaRing<N_SLOTS, MAX_BYTES_PER_SLOT> {
|
||||
let ptr = DMA_RING_PTR.load(Ordering::Acquire);
|
||||
unsafe { &*ptr }
|
||||
unsafe { DMA_RING_REF.unwrap() }
|
||||
}
|
||||
|
||||
fn cur_fill() -> usize {
|
||||
@@ -321,14 +209,12 @@ fn cur_fill() -> usize {
|
||||
produced_bytes.wrapping_sub(consumed_bytes) as usize
|
||||
}
|
||||
|
||||
/// frames per slot (based on current slot size)
|
||||
fn frames_per_slot() -> usize {
|
||||
dma_ring().slot_size() / BYTES_PER_FRAME
|
||||
fn cur_fill_target() -> i32 {
|
||||
(dma_ring().slot_size() * N_SLOTS) as i32 / 2
|
||||
}
|
||||
|
||||
/// bytes per slot (based on provided rate)
|
||||
fn bytes_per_slot(rate: u32) -> usize {
|
||||
(rate as usize / DMA_RATE) * BYTES_PER_FRAME
|
||||
fn frames_per_slot() -> usize {
|
||||
dma_ring().slot_size() / BYTES_PER_FRAME
|
||||
}
|
||||
|
||||
// 50%
|
||||
@@ -390,13 +276,39 @@ fn FLEXCOMM7() {
|
||||
.modify(|_, w| w.txerr().set_bit())
|
||||
}
|
||||
|
||||
struct FeedbackState {
|
||||
correction_enabled: AtomicBool,
|
||||
integrator: AtomicI32,
|
||||
filtered_fill: AtomicI32,
|
||||
}
|
||||
impl FeedbackState {
|
||||
fn start(&mut self) {
|
||||
self.correction_enabled.store(true, Ordering::Relaxed);
|
||||
}
|
||||
fn reset(&mut self) {
|
||||
self.correction_enabled.store(false, Ordering::Relaxed);
|
||||
self.integrator.store(0, Ordering::Relaxed);
|
||||
self.filtered_fill
|
||||
.store(cur_fill_target(), Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
impl Default for FeedbackState {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
correction_enabled: AtomicBool::new(false),
|
||||
integrator: AtomicI32::new(0),
|
||||
filtered_fill: AtomicI32::new(cur_fill_target()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Audio<'a, D: Dac<I>, I> {
|
||||
state: Atomic<AudioState>,
|
||||
alt_setting: u8,
|
||||
i2s: I2sTx,
|
||||
dac: D,
|
||||
dma: &'a DmaRing<N_SLOTS, MAX_BYTES_PER_SLOT>,
|
||||
fb: FeedbackLoop,
|
||||
fb: FeedbackState,
|
||||
nodata_timeout_frame: AtomicUsize,
|
||||
cur_rate: u32,
|
||||
clock_pins: ClockSelPins,
|
||||
@@ -420,8 +332,8 @@ impl<D: Dac<I>, I> Audio<'_, D, I> {
|
||||
AudioState::NoData => self.nodata(),
|
||||
AudioState::Stopping => self.stopping(),
|
||||
}
|
||||
self.state.store(state, Ordering::Release);
|
||||
// PERF.state.store(state, Ordering::Relaxed);
|
||||
self.state.store(state, Ordering::SeqCst);
|
||||
PERF.state.store(state, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
fn init(&mut self) {
|
||||
@@ -464,7 +376,6 @@ impl<D: Dac<I>, I> Audio<'_, D, I> {
|
||||
});
|
||||
|
||||
unsafe { pac::NVIC::unmask(pac::Interrupt::FLEXCOMM7) };
|
||||
|
||||
self.dac.init();
|
||||
}
|
||||
///Transition -> Stopped:
|
||||
@@ -504,7 +415,7 @@ impl<D: Dac<I>, I> Audio<'_, D, I> {
|
||||
///Transition -> Running
|
||||
///Unmask I2S ISR, start feedback
|
||||
fn run(&mut self) {
|
||||
self.i2s.i2s.fifostat.write(|w| w.txerr().set_bit());
|
||||
self.fb.start();
|
||||
// FIFO threshold trigger enable
|
||||
self.i2s
|
||||
.i2s
|
||||
@@ -514,14 +425,14 @@ impl<D: Dac<I>, I> Audio<'_, D, I> {
|
||||
.i2s
|
||||
.fifocfg
|
||||
.modify(|_, w| w.enabletx().enabled().dmatx().enabled());
|
||||
dma_ring().run();
|
||||
// clear tx error status
|
||||
self.i2s.i2s.fifostat.write(|w| w.txerr().set_bit());
|
||||
// enable tx error interrupt
|
||||
self.i2s.i2s.fifointenset.write(|w| w.txerr().enabled());
|
||||
unsafe {
|
||||
pac::NVIC::unmask(pac::Interrupt::DMA0);
|
||||
}
|
||||
dma_ring().run();
|
||||
// clear tx error status
|
||||
// self.i2s.i2s.fifostat.write(|w| w.txerr().set_bit());
|
||||
// enable tx error interrupt
|
||||
self.i2s.i2s.fifointenset.write(|w| w.txerr().enabled());
|
||||
}
|
||||
///Transition->NoData
|
||||
///store framecount at transition so we can time out recovery
|
||||
@@ -561,18 +472,13 @@ impl<D: Dac<I>, I> ClockSource for Audio<'_, D, I> {
|
||||
sample_rate: u32,
|
||||
) -> core::result::Result<(), usbd_uac2::UsbAudioClassError> {
|
||||
defmt::info!("[clock] changing rate to {}", sample_rate);
|
||||
if self.state.load(Ordering::Acquire) != AudioState::Stopped {
|
||||
if self.state.load(Ordering::SeqCst) != AudioState::Stopped {
|
||||
defmt::warn!("[clock] changing rate when not stopped, stopping first");
|
||||
self.stop();
|
||||
}
|
||||
let slot_bytes = (self.cur_rate as usize / DMA_RATE) * BYTES_PER_FRAME;
|
||||
dma_ring().set_slot_size(slot_bytes);
|
||||
self.cur_rate = sample_rate;
|
||||
let slot_bytes = bytes_per_slot(self.cur_rate);
|
||||
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) {
|
||||
defmt::info!("[clock] 24M osc selected");
|
||||
self.clock_pins.sel_22m.set_low().ok();
|
||||
@@ -600,7 +506,7 @@ impl<D: Dac<I>, I> ClockSource for Audio<'_, D, I> {
|
||||
}
|
||||
impl<D: Dac<I>, I, B: bus::UsbBus> AudioHandler<'_, B> for Audio<'_, D, I> {
|
||||
fn alternate_setting_changed(&mut self, _terminal: usb_device::UsbDirection, alt_setting: u8) {
|
||||
let state = self.state.load(Ordering::Acquire);
|
||||
let state = self.state.load(Ordering::Relaxed);
|
||||
match (alt_setting, state) {
|
||||
(0, AudioState::Armed | AudioState::Prefill | AudioState::NoData) => {
|
||||
self.transition(AudioState::Stopped)
|
||||
@@ -619,7 +525,7 @@ impl<D: Dac<I>, I, B: bus::UsbBus> AudioHandler<'_, B> for Audio<'_, D, I> {
|
||||
&mut self,
|
||||
ep: &usb_device::endpoint::Endpoint<'_, B, usb_device::endpoint::Out>,
|
||||
) {
|
||||
let state = self.state.load(Ordering::Acquire);
|
||||
let state = self.state.load(Ordering::Relaxed);
|
||||
let mut buf =
|
||||
[0; (MAX_SAMPLE_RATE.div_ceil(USB_FRAME_RATE) + 1) as usize * BYTES_PER_FRAME];
|
||||
let len = match ep.read(&mut buf) {
|
||||
@@ -650,8 +556,7 @@ impl<D: Dac<I>, I, B: bus::UsbBus> AudioHandler<'_, B> for Audio<'_, D, I> {
|
||||
// Valid states here are Armed, Prefill, Running, Draining and NoData
|
||||
match state {
|
||||
AudioState::Stopped | AudioState::Stopping => {
|
||||
defmt::warn!("Received audio data when stopped/stopping");
|
||||
self.transition(AudioState::Prefill);
|
||||
defmt::error!("Received audio data when stopped/stopping")
|
||||
}
|
||||
// When armed, data rx goes to prefill
|
||||
AudioState::Armed => self.transition(AudioState::Prefill),
|
||||
@@ -667,7 +572,7 @@ impl<D: Dac<I>, 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();
|
||||
let fill = cur_fill() as usize;
|
||||
// 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);
|
||||
@@ -678,7 +583,7 @@ impl<D: Dac<I>, I, B: bus::UsbBus> AudioHandler<'_, B> for Audio<'_, D, I> {
|
||||
}
|
||||
}
|
||||
// Any data in NoData moves us into LowData. But maybe it should be more like prefill?
|
||||
AudioState::NoData => self.transition(AudioState::Prefill),
|
||||
AudioState::NoData => self.transition(AudioState::LowData),
|
||||
}
|
||||
}
|
||||
fn audio_data_tx(
|
||||
@@ -687,7 +592,11 @@ impl<D: Dac<I>, I, B: bus::UsbBus> AudioHandler<'_, B> for Audio<'_, D, I> {
|
||||
) {
|
||||
}
|
||||
fn feedback(&mut self, nominal_rate: UsbIsochronousFeedback) -> Option<UsbIsochronousFeedback> {
|
||||
let current_bytes = cur_fill();
|
||||
if !self.fb.correction_enabled.load(Ordering::Relaxed) {
|
||||
return Some(nominal_rate);
|
||||
}
|
||||
|
||||
let current_bytes = cur_fill() as i32;
|
||||
|
||||
if current_bytes == 0 {
|
||||
defmt::error!("[fb] dma underrun detected!");
|
||||
@@ -695,11 +604,44 @@ impl<D: Dac<I>, I, B: bus::UsbBus> AudioHandler<'_, B> for Audio<'_, D, I> {
|
||||
return Some(nominal_rate);
|
||||
}
|
||||
|
||||
let v = self.fb.compute(nominal_rate, current_bytes);
|
||||
// PERF.avg_fill.store(self.fb.avg_fill, Ordering::Relaxed);
|
||||
// PERF.fb.store(v as i32, Ordering::Relaxed);
|
||||
PERF.avg_fill
|
||||
.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |v| {
|
||||
Some(((v << 6) - v + current_bytes as usize) >> 6)
|
||||
})
|
||||
.ok();
|
||||
|
||||
Some(v)
|
||||
let raw_error = current_bytes - cur_fill_target();
|
||||
let i_error = if raw_error.abs() <= 4 { 0 } else { raw_error }; // deadband
|
||||
let current_i = self.fb.integrator.load(Ordering::Relaxed);
|
||||
let leak = current_i >> 7;
|
||||
let new_i = current_i
|
||||
.saturating_sub(leak)
|
||||
.saturating_add(i_error)
|
||||
.clamp(-5000, 5000);
|
||||
self.fb.integrator.store(new_i, Ordering::Relaxed);
|
||||
PERF.integrator.store(new_i, Ordering::Relaxed);
|
||||
|
||||
let nominal_v = nominal_rate.to_u32_12_13() as i32;
|
||||
let max_allowed_deviation = nominal_v / 500; // 0.2%
|
||||
|
||||
// 3. SEPARATE GAINS FOR P AND I
|
||||
// For P: Keep your working math (converting raw error to a permille equivalent scale)
|
||||
let error_permille = (raw_error * 1000) / cur_fill_target();
|
||||
let p_term = (-((error_permille as i64) * (nominal_v as i64)) / (10 * 256000)) as i32;
|
||||
let i_term = (-((new_i as i64) * (nominal_v as i64)) / (256000 * 1000)) as i32;
|
||||
let i_term = 0;
|
||||
|
||||
PERF.p.store(p_term, Ordering::Relaxed);
|
||||
PERF.i.store(i_term, Ordering::Relaxed);
|
||||
|
||||
let mut v = nominal_v + p_term + i_term;
|
||||
v = v.clamp(
|
||||
nominal_v - max_allowed_deviation,
|
||||
nominal_v + max_allowed_deviation,
|
||||
);
|
||||
PERF.fb.store(v, Ordering::Relaxed);
|
||||
|
||||
Some(UsbIsochronousFeedback::new(v as u32))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -810,7 +752,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),
|
||||
@@ -889,17 +831,15 @@ fn main() -> ! {
|
||||
)
|
||||
.unwrap();
|
||||
let dma_ref = DMA_RING.init(dma);
|
||||
DMA_RING_PTR.store(dma_ref as *const _ as *mut _, Ordering::Release);
|
||||
// unsafe { DMA_RING_PTR = Some(dma_ref) };
|
||||
unsafe { DMA_RING_REF = Some(dma_ref) };
|
||||
|
||||
defmt::info!("audio init");
|
||||
|
||||
let mut audio = Audio {
|
||||
state: Atomic::new(AudioState::Stopped),
|
||||
i2s: i2s_peripheral,
|
||||
dac: dac_impl,
|
||||
dma: dma_ring(),
|
||||
fb: FeedbackLoop::new(FeedbackConfig::for_rate(SAMPLE_RATES[0].min)),
|
||||
fb: FeedbackState::default(),
|
||||
alt_setting: 0,
|
||||
nodata_timeout_frame: AtomicUsize::new(0),
|
||||
cur_rate: SAMPLE_RATES[0].min,
|
||||
@@ -919,17 +859,7 @@ fn main() -> ! {
|
||||
);
|
||||
let mut uac2 = config.build(&usb_bus).unwrap();
|
||||
#[cfg(feature = "hid")]
|
||||
let (mut hid, mut hid_cmd) = {
|
||||
let hid = HIDClass::new_ep_in(&usb_bus, AudioTelemetryReport::desc(), HID_INTERVAL_MS);
|
||||
// Linux's usbhid refuses to bind an interface without an interrupt IN endpoint
|
||||
// (no hidraw node), so the command interface needs one even though it is unused.
|
||||
let hid_cmd = HIDClass::new(
|
||||
&usb_bus,
|
||||
AudioDeviceCommandReport::desc(),
|
||||
HID_CMD_INTERVAL_MS,
|
||||
);
|
||||
(hid, hid_cmd)
|
||||
};
|
||||
let mut hid = HIDClass::new_ep_in(&usb_bus, AudioTelemetryReport::desc(), HID_INTERVAL_MS);
|
||||
|
||||
let mut usb_dev = usbd_uac2::builder(&usb_bus, UsbVidPid(0x1209, 0xcc1d))
|
||||
.strings(&[StringDescriptors::default()
|
||||
@@ -940,79 +870,46 @@ fn main() -> ! {
|
||||
.unwrap()
|
||||
.build();
|
||||
|
||||
// 1. Initialize the HID timer conditionally outside the closure
|
||||
#[cfg(feature = "hid")]
|
||||
let mut hid_update_timer = {
|
||||
let mut timer = Timer::new(
|
||||
let mut poll_all = {
|
||||
let mut hid_update_timer = Timer::new(
|
||||
hal.ctimer
|
||||
.1
|
||||
.enabled(&mut syscon, clocks.support_1mhz_fro_token().unwrap()),
|
||||
);
|
||||
timer.start(Microseconds::new(HID_INTERVAL_MS as u32 * 1000));
|
||||
timer
|
||||
};
|
||||
hid_update_timer.start(Microseconds::new(HID_INTERVAL_MS as u32 * 1000));
|
||||
|
||||
// 2. Single consolidated poll_all closure
|
||||
let mut poll_all = move || {
|
||||
// Poll active USB classes
|
||||
#[cfg(feature = "hid")]
|
||||
usb_dev.poll(&mut [&mut uac2, &mut hid, &mut hid_cmd]);
|
||||
|
||||
#[cfg(not(feature = "hid"))]
|
||||
usb_dev.poll(&mut [&mut uac2]);
|
||||
|
||||
// TODO: we should handle unexpected NODATA differently from 'Stopping'
|
||||
if NODATA_FLAG.swap(false, Ordering::AcqRel) {
|
||||
let audio = uac2.handler();
|
||||
audio.transition(AudioState::Stopped);
|
||||
// The host is still streaming (alt setting 1) so no alt setting change will
|
||||
// re-arm us; re-arm now so the DMA channel is re-initialised before more data
|
||||
// arrives.
|
||||
if audio.alt_setting == 1 {
|
||||
audio.transition(AudioState::Armed);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "hid")]
|
||||
{
|
||||
use deku::DekuContainerRead;
|
||||
use shared::AudioDeviceCommand;
|
||||
|
||||
fn handle_cmd(cmd: AudioDeviceCommand) {
|
||||
use shared::AudioDeviceCommand;
|
||||
|
||||
match cmd {
|
||||
AudioDeviceCommand::Noop => {}
|
||||
AudioDeviceCommand::Reset => {
|
||||
cortex_m::interrupt::disable();
|
||||
cortex_m::peripheral::SCB::sys_reset();
|
||||
}
|
||||
AudioDeviceCommand::Bootloader => boot_to_bootloader(),
|
||||
move || {
|
||||
usb_dev.poll(&mut [&mut uac2, &mut hid]);
|
||||
// DMA ring is empty; if altsetting = 0 then -> stopped else NoData
|
||||
// TODO: handle NoData state
|
||||
if NODATA_FLAG.swap(false, Ordering::Acquire) {
|
||||
match uac2.handler().state.load(Ordering::Acquire) {
|
||||
AudioState::Stopping => uac2.handler().transition(AudioState::Stopped),
|
||||
_ => uac2.handler().transition(AudioState::Stopped),
|
||||
}
|
||||
}
|
||||
|
||||
if hid_update_timer.wait().is_ok() {
|
||||
let report = build_telemetry_report(&PERF, uac2.handler());
|
||||
if let Err(e) = hid.push_input(&report)
|
||||
&& e != UsbError::WouldBlock
|
||||
{
|
||||
defmt::error!("Failed to send HID report: {:?}", e);
|
||||
let report = PERF.build_report();
|
||||
match hid.push_input(&report) {
|
||||
Ok(_) => {}
|
||||
Err(UsbError::WouldBlock) => {}
|
||||
Err(e) => defmt::error!("Failed to send HID report: {:?}", e),
|
||||
}
|
||||
// LPC55 CTIMER is not periodic; restart manually
|
||||
// lpc55 ctimer is not Periodic, so restart it
|
||||
hid_update_timer.start(Microseconds::new(HID_INTERVAL_MS as u32 * 1000));
|
||||
}
|
||||
let mut cmd_report_buf = [0u8; core::mem::size_of::<AudioDeviceCommandReport>()];
|
||||
match hid_cmd.pull_raw_output(&mut cmd_report_buf) {
|
||||
Ok(len) => {
|
||||
if let Ok((_left, cmd)) =
|
||||
AudioDeviceCommandReport::from_bytes((&cmd_report_buf[0..len], 0))
|
||||
&& let Ok(cmd) = cmd.try_into()
|
||||
{
|
||||
handle_cmd(cmd)
|
||||
}
|
||||
}
|
||||
};
|
||||
#[cfg(not(feature = "hid"))]
|
||||
let mut poll_all = {
|
||||
move || {
|
||||
usb_dev.poll(&mut [&mut uac2]);
|
||||
if NODATA_FLAG.swap(false, Ordering::Acquire) {
|
||||
match uac2.handler().state.load(Ordering::Acquire) {
|
||||
AudioState::Stopping => uac2.handler().transition(AudioState::Stopped),
|
||||
_ => uac2.handler().transition(AudioState::Stopped),
|
||||
}
|
||||
Err(UsbError::WouldBlock) => {}
|
||||
Err(e) => defmt::error!("Invalid report: {:?}", e),
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -1021,5 +918,6 @@ fn main() -> ! {
|
||||
|
||||
loop {
|
||||
poll_all();
|
||||
// usb_dev.poll(&mut [&mut uac2]);
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,6 @@ pub trait Dac<T> {
|
||||
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);
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
[toolchain]
|
||||
channel = "1.95.0"
|
||||
targets = ["thumbv8m.main-none-eabihf"]
|
||||
components = ["llvm-tools-preview"]
|
||||
+1
-1
@@ -3,7 +3,7 @@ name = "shared"
|
||||
edition = "2024"
|
||||
|
||||
[features]
|
||||
std = ["deku/alloc"]
|
||||
std = []
|
||||
serde = ["dep:serde"]
|
||||
|
||||
[dependencies]
|
||||
|
||||
+26
-63
@@ -1,22 +1,18 @@
|
||||
#![no_std]
|
||||
|
||||
use bytemuck::NoUninit;
|
||||
use deku::DekuRead;
|
||||
#[cfg(feature = "std")]
|
||||
use deku::DekuWrite;
|
||||
use num_enum::TryFromPrimitive;
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, NoUninit, Eq, PartialEq, TryFromPrimitive)]
|
||||
#[derive(Clone, Copy, Debug, 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).
|
||||
///
|
||||
@@ -53,6 +49,11 @@ 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!(
|
||||
@@ -98,35 +99,19 @@ pub struct AudioTelemetrySnapshot {
|
||||
pub dac_underflow_count: u16,
|
||||
pub usb_underflow_count: u16,
|
||||
pub dac_overflow_count: u16,
|
||||
pub cur_rate: u32,
|
||||
pub fb_rate_estimate: f32,
|
||||
}
|
||||
|
||||
// Writing is host-side only (needs deku's `alloc`, enabled by the `std` feature)
|
||||
#[derive(Debug, DekuRead, Clone)]
|
||||
#[cfg_attr(feature = "std", derive(DekuWrite))]
|
||||
#[deku(id_type = "u8")]
|
||||
pub enum AudioDeviceCommand {
|
||||
#[deku(id = 0)]
|
||||
Noop,
|
||||
#[deku(id = 1)]
|
||||
Reset,
|
||||
#[deku(id = 2)]
|
||||
Bootloader,
|
||||
pub p: i32,
|
||||
pub i: i32,
|
||||
pub fb: i32,
|
||||
}
|
||||
|
||||
pub mod hid {
|
||||
use deku::{DekuContainerRead, DekuError, DekuRead};
|
||||
#[cfg(feature = "std")]
|
||||
use deku::{DekuContainerWrite, DekuWrite};
|
||||
use deku::DekuRead;
|
||||
use usbd_hid::descriptor::generator_prelude::*;
|
||||
|
||||
use crate::{AudioDeviceCommand, AudioState, AudioTelemetrySnapshot};
|
||||
#[cfg(feature = "serde")]
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// HID usage IDs identifying each vendor interface. `gen_hid_descriptor` only accepts
|
||||
/// literals, so the descriptors below repeat these values; keep them in sync.
|
||||
pub const USAGE_TELEMETRY: u16 = 0x01;
|
||||
pub const USAGE_COMMAND: u16 = 0x02;
|
||||
use crate::{AudioState, AudioTelemetrySnapshot};
|
||||
|
||||
#[derive(DekuRead)]
|
||||
#[deku(endian = "little")]
|
||||
@@ -138,8 +123,10 @@ pub mod hid {
|
||||
dac_underflow_count=input;
|
||||
usb_underflow_count=input;
|
||||
dac_overflow_count=input;
|
||||
cur_rate=input;
|
||||
fb_rate_estimate=input;
|
||||
p=input;
|
||||
i=input;
|
||||
fb=input;
|
||||
integrator=input;
|
||||
}
|
||||
)]
|
||||
#[repr(C, packed)]
|
||||
@@ -151,8 +138,10 @@ pub mod hid {
|
||||
pub dac_underflow_count: u16,
|
||||
pub usb_underflow_count: u16,
|
||||
pub dac_overflow_count: u16,
|
||||
pub cur_rate: i32,
|
||||
pub fb_rate_estimate: i32,
|
||||
pub p: i32,
|
||||
pub i: i32,
|
||||
pub fb: i32,
|
||||
pub integrator: i32,
|
||||
}
|
||||
|
||||
impl From<AudioTelemetryReport> for AudioTelemetrySnapshot {
|
||||
@@ -160,40 +149,14 @@ pub mod hid {
|
||||
AudioTelemetrySnapshot {
|
||||
state: AudioState::try_from(value.state).expect("Invalid AudioState"),
|
||||
average_buffer_fill: value.average_buffer_fill,
|
||||
frame_count: value.frame_count.cast_unsigned(), // on firmware side is usize == u32
|
||||
frame_count: i32::cast_unsigned(value.frame_count), // on firmware side is usize == u32
|
||||
dac_underflow_count: value.dac_underflow_count,
|
||||
usb_underflow_count: value.usb_underflow_count,
|
||||
dac_overflow_count: value.dac_overflow_count,
|
||||
cur_rate: value.cur_rate.cast_unsigned(),
|
||||
fb_rate_estimate: (value.fb_rate_estimate as f32),
|
||||
p: value.p,
|
||||
i: value.i,
|
||||
fb: value.fb,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(DekuRead)]
|
||||
#[cfg_attr(feature = "std", derive(DekuWrite))]
|
||||
#[deku(endian = "little")]
|
||||
#[gen_hid_descriptor((collection = APPLICATION, usage_page = VENDOR_DEFINED_START, usage = 0x02, ) = {
|
||||
cmd=output;
|
||||
})]
|
||||
#[repr(C, packed)]
|
||||
pub struct AudioDeviceCommandReport {
|
||||
pub cmd: [u8; 32],
|
||||
}
|
||||
|
||||
impl TryFrom<AudioDeviceCommandReport> for AudioDeviceCommand {
|
||||
type Error = DekuError;
|
||||
fn try_from(value: AudioDeviceCommandReport) -> Result<Self, Self::Error> {
|
||||
Ok(AudioDeviceCommand::from_bytes((value.cmd.as_slice(), 0))?.1)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "std")]
|
||||
impl From<AudioDeviceCommand> for AudioDeviceCommandReport {
|
||||
fn from(value: AudioDeviceCommand) -> Self {
|
||||
let mut buf = [0u8; core::mem::size_of::<Self>()];
|
||||
value.to_slice(&mut buf).unwrap();
|
||||
Self { cmd: buf }
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user