1026 lines
33 KiB
Rust
1026 lines
33 KiB
Rust
#![no_main]
|
||
#![no_std]
|
||
|
||
extern crate panic_probe;
|
||
#[defmt::panic_handler]
|
||
fn panic() -> ! {
|
||
panic_probe::hard_fault()
|
||
}
|
||
|
||
use atomic::Atomic;
|
||
use core::ptr;
|
||
use core::sync::atomic::AtomicPtr;
|
||
use core::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||
use cortex_m_rt::entry;
|
||
use defmt::debug;
|
||
use defmt_rtt as _;
|
||
use hal::Pin;
|
||
use hal::Syscon;
|
||
use hal::drivers::{Timer, UsbBus, pins, pins::direction::Output};
|
||
use hal::prelude::*;
|
||
use hal::raw as pac;
|
||
use hal::time::{Hertz, Microseconds};
|
||
use hal::typestates::pin::state::Gpio;
|
||
use lpc55_hal as hal;
|
||
use pac::interrupt;
|
||
use static_cell::StaticCell;
|
||
use usb_device::{
|
||
bus::{self},
|
||
device::{StringDescriptors, UsbVidPid},
|
||
};
|
||
#[cfg(feature = "hid")]
|
||
use usbd_hid::{descriptor::SerializedDescriptor, hid_class::HIDClass};
|
||
use usbd_uac2::{
|
||
self, AudioHandler, ClockSource, RangeEntry, TerminalConfig, UsbAudioClassConfig,
|
||
UsbAudioClassError, UsbIsochronousFeedback, UsbSpeed,
|
||
constants::{FunctionCode, TerminalType},
|
||
descriptors::ClockType,
|
||
};
|
||
|
||
use crate::dac::DacImpl;
|
||
use crate::dma::DmaRing;
|
||
use crate::hw::led1;
|
||
use crate::hw::led2;
|
||
use crate::traits::Dac;
|
||
use shared::AudioState;
|
||
use shared::hid::{AudioDeviceCommandReport, AudioTelemetryReport};
|
||
|
||
#[cfg(feature = "ak4490")]
|
||
pub mod dac {
|
||
mod ak4490;
|
||
pub use self::ak4490::Ak4490Dac as DacImpl;
|
||
}
|
||
#[cfg(feature = "cs4398")]
|
||
pub mod dac {
|
||
mod cs4398;
|
||
pub use self::cs4398::Cs4398Dac as DacImpl;
|
||
}
|
||
#[cfg(feature = "nodac")]
|
||
pub mod dac {
|
||
mod noop;
|
||
pub use self::noop::NoopDac as DacImpl;
|
||
}
|
||
#[cfg(feature = "wm8904")]
|
||
pub mod dac {
|
||
mod wm8904;
|
||
pub use self::wm8904::Wm8904Dac as DacImpl;
|
||
}
|
||
|
||
mod dma;
|
||
mod hw;
|
||
mod traits;
|
||
|
||
#[cfg(not(feature = "evk"))]
|
||
const MAX_SAMPLE_RATE: u32 = 192000;
|
||
#[cfg(feature = "evk")]
|
||
const MAX_SAMPLE_RATE: u32 = 96000;
|
||
|
||
#[cfg(not(feature = "evk"))]
|
||
const SAMPLE_RATES: [RangeEntry<u32>; 6] = [
|
||
RangeEntry::new_fixed(44100),
|
||
RangeEntry::new_fixed(48000),
|
||
RangeEntry::new_fixed(44100 * 2),
|
||
RangeEntry::new_fixed(48000 * 2),
|
||
RangeEntry::new_fixed(44100 * 4),
|
||
RangeEntry::new_fixed(48000 * 4),
|
||
];
|
||
|
||
#[cfg(feature = "evk")]
|
||
const SAMPLE_RATES: [RangeEntry<u32>; 2] = [
|
||
RangeEntry::new_fixed(48000),
|
||
RangeEntry::new_fixed(48000 * 2),
|
||
];
|
||
|
||
const DMA_RATE: usize = 4000;
|
||
const BYTES_PER_SAMPLE: usize = 4; // 32 bit samples
|
||
const BYTES_PER_FRAME: usize = BYTES_PER_SAMPLE * 2; // 2 channels
|
||
const MAX_FRAMES_PER_SLOT: usize = MAX_SAMPLE_RATE as usize / 4000; // run the DMA at 4khz
|
||
const MAX_BYTES_PER_SLOT: usize = MAX_FRAMES_PER_SLOT * BYTES_PER_FRAME;
|
||
const N_SLOTS: usize = 8;
|
||
// const FILL_TARGET_BYTES: i32 = (BYTES_PER_SLOT * N_SLOTS) as i32 / 2;
|
||
const USB_FRAME_RATE: u32 = 8000; // microframe rate: 8000 for HS, 1000 for FS
|
||
|
||
// In frames
|
||
// const QUEUE_RUNNING_UP: usize = ((FRAMES_PER_SLOT * N_SLOTS) * 5) / 10; // 50%
|
||
// const QUEUE_RUNNING_DOWN: usize = ((FRAMES_PER_SLOT * N_SLOTS) * 2) / 10; // 20%
|
||
// 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>>,
|
||
}
|
||
|
||
struct ClockSelPins {
|
||
sel_24m: Pin<pins::Pio0_27, Gpio<Output>>,
|
||
sel_22m: Pin<pins::Pio0_31, Gpio<Output>>,
|
||
}
|
||
|
||
#[derive(Default)]
|
||
struct PerfCounters {
|
||
// state: Atomic<AudioState>,
|
||
received_frames: AtomicUsize,
|
||
played_frames: AtomicUsize,
|
||
// min_fill: AtomicUsize,
|
||
// avg_fill: AtomicUsize,
|
||
queue_underflows: AtomicUsize,
|
||
queue_overflows: AtomicUsize,
|
||
audio_underflows: AtomicUsize,
|
||
// p: 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.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);
|
||
}
|
||
}
|
||
|
||
impl defmt::Format for PerfCounters {
|
||
fn format(&self, fmt: defmt::Formatter) {
|
||
defmt::write!(
|
||
fmt,
|
||
"frames: {}/{} 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.audio_underflows.load(Ordering::Relaxed),
|
||
self.queue_underflows.load(Ordering::Relaxed),
|
||
self.queue_overflows.load(Ordering::Relaxed)
|
||
)
|
||
}
|
||
}
|
||
|
||
static PERF: PerfCounters = PerfCounters {
|
||
// 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),
|
||
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),
|
||
};
|
||
|
||
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());
|
||
#[inline]
|
||
fn dma_ring() -> &'static DmaRing<N_SLOTS, MAX_BYTES_PER_SLOT> {
|
||
let ptr = DMA_RING_PTR.load(Ordering::Acquire);
|
||
unsafe { &*ptr }
|
||
}
|
||
|
||
fn cur_fill() -> usize {
|
||
let produced_bytes = dma_ring().produced_bytes() as u32;
|
||
let consumed_bytes = dma_ring().consumed_bytes() as u32;
|
||
|
||
// Handle rollover properly
|
||
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
|
||
}
|
||
|
||
/// bytes per slot (based on provided rate)
|
||
fn bytes_per_slot(rate: u32) -> usize {
|
||
(rate as usize / DMA_RATE) * BYTES_PER_FRAME
|
||
}
|
||
|
||
// 50%
|
||
fn queue_running_up_threshold() -> usize {
|
||
(frames_per_slot() * N_SLOTS) / 2
|
||
}
|
||
|
||
// 20%
|
||
fn queue_running_down_threshold() -> usize {
|
||
(frames_per_slot() * N_SLOTS) / 5
|
||
}
|
||
|
||
#[interrupt]
|
||
fn DMA0() {
|
||
defmt::debug!("dma0");
|
||
let dma = unsafe { &*pac::DMA0::ptr() };
|
||
|
||
let inta = dma.inta0.read().bits();
|
||
let err = dma.errint0.read().bits();
|
||
|
||
// TODO: figure out how to track underflows properly
|
||
if (err & (1 << 19)) != 0 {
|
||
let live = dma.channel19.xfercfg.read().bits();
|
||
|
||
let desc = unsafe { &*dma_ring().channel_desc.get() };
|
||
let mem = desc.d[19];
|
||
defmt::error!(
|
||
"DMA error ch19: live={=u32:08x} INTA={=u32:x} ERR={=u32:x}\n desc: {}",
|
||
live,
|
||
inta,
|
||
err,
|
||
mem
|
||
);
|
||
dma.errint0.write(|w| unsafe { w.bits(1 << 19) });
|
||
}
|
||
|
||
if (inta & (1 << 19)) != 0 {
|
||
dma.inta0.write(|w| unsafe { w.bits(1 << 19) });
|
||
if dma_ring().advance_consumed(1).is_err() {
|
||
PERF.audio_underflows.fetch_add(1, Ordering::Relaxed);
|
||
} else {
|
||
led1().toggle();
|
||
PERF.played_frames
|
||
.fetch_add(frames_per_slot(), Ordering::Relaxed);
|
||
}
|
||
if cur_fill() <= dma_ring().slot_size() {
|
||
led2().on();
|
||
NODATA_FLAG.store(true, Ordering::Release);
|
||
}
|
||
}
|
||
}
|
||
|
||
#[interrupt]
|
||
fn FLEXCOMM7() {
|
||
// Count I2S TX FIFO error (should be underrun, assuming we set up our DMA trigger correctly)
|
||
PERF.audio_underflows.fetch_add(1, Ordering::Relaxed);
|
||
unsafe { &*pac::I2S7::ptr() }
|
||
.fifostat
|
||
.modify(|_, w| w.txerr().set_bit())
|
||
}
|
||
|
||
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,
|
||
nodata_timeout_frame: AtomicUsize,
|
||
cur_rate: u32,
|
||
clock_pins: ClockSelPins,
|
||
_marker: core::marker::PhantomData<I>,
|
||
}
|
||
impl<D: Dac<I>, I> Audio<'_, D, I> {
|
||
const RATES: &'static [RangeEntry<u32>] = &SAMPLE_RATES;
|
||
/// Perform a state transition to `state`
|
||
fn transition(&mut self, state: AudioState) {
|
||
defmt::info!(
|
||
"AudioState {} -> {}",
|
||
self.state.load(Ordering::Relaxed),
|
||
state
|
||
);
|
||
match state {
|
||
AudioState::Stopped => self.stop(),
|
||
AudioState::Armed => self.arm(),
|
||
AudioState::Prefill => self.prefill(),
|
||
AudioState::Running => self.run(),
|
||
AudioState::LowData => {}
|
||
AudioState::NoData => self.nodata(),
|
||
AudioState::Stopping => self.stopping(),
|
||
}
|
||
self.state.store(state, Ordering::Release);
|
||
// PERF.state.store(state, Ordering::Relaxed);
|
||
}
|
||
|
||
fn init(&mut self) {
|
||
// Enable TX FIFO only
|
||
self.i2s.i2s.fifocfg.modify(|_, w| {
|
||
w.enabletx()
|
||
.enabled()
|
||
.enablerx()
|
||
.disabled()
|
||
.dmatx()
|
||
.disabled()
|
||
.txi2se0()
|
||
.zero()
|
||
});
|
||
|
||
// Flush
|
||
self.i2s.i2s.fifocfg.modify(|_, w| w.emptytx().set_bit());
|
||
|
||
self.i2s
|
||
.i2s
|
||
.cfg2
|
||
.modify(|_, w| unsafe { w.position().bits(0).framelen().bits(63) }); // framelen = 64
|
||
|
||
self.update_bclk();
|
||
|
||
// Config
|
||
self.i2s.i2s.cfg1.modify(|_, w| unsafe {
|
||
w.mstslvcfg()
|
||
.normal_master()
|
||
.onechannel()
|
||
.dual_channel()
|
||
.datalen()
|
||
.bits(31)
|
||
.mainenable()
|
||
.disabled()
|
||
.mode()
|
||
.classic_mode()
|
||
.datapause()
|
||
.normal()
|
||
});
|
||
|
||
unsafe { pac::NVIC::unmask(pac::Interrupt::FLEXCOMM7) };
|
||
|
||
self.dac.init();
|
||
}
|
||
///Transition -> Stopped:
|
||
///clear queue, mute DAC, mask I2S ISR, stop I2S peripheral, disable & reset feedback and performance queues
|
||
fn stop(&mut self) {
|
||
// Disable FIFO error interrupt
|
||
self.i2s.i2s.fifointenclr.write(|w| w.txerr().set_bit());
|
||
dma_ring().stop();
|
||
pac::NVIC::mask(pac::Interrupt::DMA0);
|
||
self.dac.mute();
|
||
// Clear any samples in the FIFO
|
||
self.i2s.i2s.fifocfg.modify(|_, w| w.emptytx().set_bit());
|
||
// Disable I2S
|
||
self.i2s.i2s.cfg1.modify(|_, w| w.mainenable().disabled());
|
||
// Reset feedback state
|
||
self.fb.reset();
|
||
// reset performance counters
|
||
PERF.reset();
|
||
// Stop the clocks
|
||
// self.clock_pins.sel_22m.set_low().ok();
|
||
// self.clock_pins.sel_24m.set_low().ok();
|
||
}
|
||
///Transition -> Armed
|
||
/// Start I2S peripheral and MCLK. Since we assume we have interrupts disabled at
|
||
/// this point (as we came from Stopped), and the FIFO is empty, this will
|
||
/// play out 0s.
|
||
fn arm(&mut self) {
|
||
dma_ring().init();
|
||
self.set_sample_rate(self.cur_rate).ok();
|
||
self.i2s.i2s.cfg1.modify(|_, w| w.mainenable().enabled());
|
||
}
|
||
///Transition -> Prefill
|
||
/// Unmute DAC
|
||
fn prefill(&mut self) {
|
||
self.dac.unmute();
|
||
}
|
||
///Transition -> Running
|
||
///Unmask I2S ISR, start feedback
|
||
fn run(&mut self) {
|
||
self.i2s.i2s.fifostat.write(|w| w.txerr().set_bit());
|
||
// FIFO threshold trigger enable
|
||
self.i2s
|
||
.i2s
|
||
.fifotrig
|
||
.modify(|_, w| unsafe { w.txlvl().bits(6).txlvlena().enabled() });
|
||
self.i2s
|
||
.i2s
|
||
.fifocfg
|
||
.modify(|_, w| w.enabletx().enabled().dmatx().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
|
||
fn nodata(&mut self) {
|
||
// TODO: Actually handle this
|
||
// self.nodata_timeout_frame.store(
|
||
// PERF.queue_underflows.load(Ordering::Relaxed) + NODATA_TIMEOUT_FRAMES, // we underflow every frame, use it as a timeout counter
|
||
// Ordering::Relaxed,
|
||
// );
|
||
}
|
||
/// Transition -> Stopping
|
||
/// just a marker that upcoming nodata is expected, do nothing
|
||
fn stopping(&mut self) {}
|
||
|
||
fn update_bclk(&mut self) {
|
||
let mclk_freq = if 24_576_000u32.is_multiple_of(self.cur_rate) {
|
||
24576000
|
||
} else {
|
||
22579200
|
||
};
|
||
let bclk_div = (mclk_freq / self.cur_rate / 64) as u16;
|
||
self.i2s
|
||
.i2s
|
||
.div
|
||
.modify(|_, w| unsafe { w.div().bits(bclk_div - 1) });
|
||
}
|
||
}
|
||
impl<D: Dac<I>, I> ClockSource for Audio<'_, D, I> {
|
||
const CLOCK_TYPE: usbd_uac2::descriptors::ClockType = ClockType::InternalProgrammable;
|
||
const SOF_SYNC: bool = false;
|
||
|
||
fn sample_rate(&self) -> u32 {
|
||
self.cur_rate
|
||
}
|
||
fn set_sample_rate(
|
||
&mut self,
|
||
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 {
|
||
defmt::warn!("[clock] changing rate when not stopped, stopping first");
|
||
self.stop();
|
||
}
|
||
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();
|
||
// hal::wait_at_least(1);
|
||
self.clock_pins.sel_24m.set_high().ok();
|
||
} else {
|
||
defmt::info!("[clock] 22M osc selected");
|
||
self.clock_pins.sel_24m.set_low().ok();
|
||
// hal::wait_at_least(1);
|
||
self.clock_pins.sel_22m.set_high().ok();
|
||
};
|
||
self.dac.change_rate(sample_rate);
|
||
self.update_bclk();
|
||
Ok(())
|
||
}
|
||
fn sample_rates(
|
||
&self,
|
||
) -> core::result::Result<&[usbd_uac2::RangeEntry<u32>], usbd_uac2::UsbAudioClassError> {
|
||
defmt::debug!("[clock] sample_rates will return {:?}", &Self::RATES.len());
|
||
Ok(Self::RATES)
|
||
}
|
||
fn clock_validity(&self) -> Result<bool, UsbAudioClassError> {
|
||
Ok(true)
|
||
}
|
||
}
|
||
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);
|
||
match (alt_setting, state) {
|
||
(0, AudioState::Armed | AudioState::Prefill | AudioState::NoData) => {
|
||
self.transition(AudioState::Stopped)
|
||
}
|
||
(0, AudioState::Running) => self.transition(AudioState::Stopping),
|
||
(0, AudioState::Stopped | AudioState::Stopping) => {} // already stopped/ing
|
||
(1, AudioState::Stopped) => self.transition(AudioState::Armed),
|
||
(1, _) => {} // altSetting 1 in any other state is a no-op
|
||
(_, _) => {
|
||
defmt::error!("Invalid alt setting {}", alt_setting)
|
||
}
|
||
}
|
||
self.alt_setting = alt_setting;
|
||
}
|
||
fn audio_data_rx(
|
||
&mut self,
|
||
ep: &usb_device::endpoint::Endpoint<'_, B, usb_device::endpoint::Out>,
|
||
) {
|
||
let state = self.state.load(Ordering::Acquire);
|
||
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) {
|
||
Ok(len) => len,
|
||
Err(_) => {
|
||
defmt::error!("usb error in rx callback");
|
||
return;
|
||
}
|
||
};
|
||
let buf = &buf[..len];
|
||
let res = self.dma.push(buf);
|
||
|
||
if res.dropped != 0 {
|
||
// Overflow: some or all bytes couldn't be queued.
|
||
defmt::warn!(
|
||
"overflowed dma ring, asked {}, wrote {}, dropped {}",
|
||
buf.len(),
|
||
res.written,
|
||
res.dropped
|
||
);
|
||
PERF.queue_overflows
|
||
.fetch_add(res.dropped / BYTES_PER_FRAME, Ordering::Relaxed);
|
||
}
|
||
|
||
PERF.received_frames
|
||
.fetch_add(res.written / BYTES_PER_FRAME, Ordering::Relaxed);
|
||
|
||
// 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);
|
||
}
|
||
// When armed, data rx goes to prefill
|
||
AudioState::Armed => self.transition(AudioState::Prefill),
|
||
// When prefilling, if we have received frames over the up threshold, move to running
|
||
AudioState::Prefill => {
|
||
if PERF.received_frames.load(Ordering::Relaxed) >= queue_running_up_threshold()
|
||
// 50%
|
||
{
|
||
self.transition(AudioState::Running);
|
||
}
|
||
}
|
||
// When running, USB RX is a no-op
|
||
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();
|
||
// 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);
|
||
} else if fill == 0 && self.alt_setting == 0 {
|
||
self.transition(AudioState::Stopped);
|
||
} else if fill == 0 {
|
||
self.transition(AudioState::NoData);
|
||
}
|
||
}
|
||
// Any data in NoData moves us into LowData. But maybe it should be more like prefill?
|
||
AudioState::NoData => self.transition(AudioState::Prefill),
|
||
}
|
||
}
|
||
fn audio_data_tx(
|
||
&mut self,
|
||
_ep: &usb_device::endpoint::Endpoint<'_, B, usb_device::endpoint::In>,
|
||
) {
|
||
}
|
||
fn feedback(&mut self, nominal_rate: UsbIsochronousFeedback) -> Option<UsbIsochronousFeedback> {
|
||
let current_bytes = cur_fill();
|
||
|
||
if current_bytes == 0 {
|
||
defmt::error!("[fb] dma underrun detected!");
|
||
PERF.queue_underflows.fetch_add(1, Ordering::Relaxed);
|
||
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);
|
||
|
||
Some(v)
|
||
}
|
||
}
|
||
|
||
pub struct I2sTx {
|
||
pub i2s: pac::I2S7,
|
||
}
|
||
|
||
pub fn init_i2s(mut fc7: pac::FLEXCOMM7, i2s7: pac::I2S7, syscon: &mut Syscon) -> I2sTx {
|
||
defmt::debug!("init i2s");
|
||
// Enable BOTH
|
||
syscon.reset(&mut fc7);
|
||
syscon.enable_clock(&mut fc7);
|
||
|
||
unsafe {
|
||
pac::SYSCON::ptr()
|
||
.as_ref()
|
||
.unwrap()
|
||
.fcclksel7()
|
||
.modify(|_, w| w.sel().enum_0x5()); // MCLK
|
||
}
|
||
#[cfg(not(feature = "evk"))]
|
||
unsafe {
|
||
pac::IOCON::ptr().as_ref().unwrap().pio0_23.modify(|_, w| {
|
||
w.func()
|
||
.alt1() // MCLK
|
||
.mode()
|
||
.inactive()
|
||
.slew()
|
||
.fast()
|
||
.invert()
|
||
.disabled()
|
||
.digimode()
|
||
.digital()
|
||
.od()
|
||
.normal()
|
||
});
|
||
pac::SYSCON::ptr()
|
||
.as_ref()
|
||
.unwrap()
|
||
.mclkio
|
||
.modify(|_, w| w.mclkio().input());
|
||
};
|
||
|
||
#[cfg(feature = "evk")]
|
||
unsafe {
|
||
pac::IOCON::ptr().as_ref().unwrap().pio1_31.modify(|_, w| {
|
||
w.func()
|
||
.alt1()
|
||
.mode()
|
||
.inactive()
|
||
.slew()
|
||
.fast()
|
||
.invert()
|
||
.disabled()
|
||
.digimode()
|
||
.digital()
|
||
.od()
|
||
.normal()
|
||
});
|
||
pac::SYSCON::ptr()
|
||
.as_ref()
|
||
.unwrap()
|
||
.mclkclksel
|
||
.modify(|_, w| w.sel().enum_0x1()); // PLL0
|
||
pac::SYSCON::ptr()
|
||
.as_ref()
|
||
.unwrap()
|
||
.mclkdiv
|
||
.modify(|_, w| w.div().bits(1).halt().run().reset().released()); // div by 2 = PLL0 fout / 2 = 12.288MHz, max for WM8904 @ 96k
|
||
pac::SYSCON::ptr()
|
||
.as_ref()
|
||
.unwrap()
|
||
.mclkio
|
||
.modify(|_, w| w.mclkio().output());
|
||
}
|
||
|
||
// Select I2S TX function
|
||
fc7.pselid.write(|w| w.persel().i2s_transmit());
|
||
|
||
let regs = i2s7;
|
||
I2sTx { i2s: regs }
|
||
}
|
||
|
||
#[entry]
|
||
fn main() -> ! {
|
||
let hal = hal::new();
|
||
|
||
let mut anactrl = hal.anactrl;
|
||
let mut pmc = hal.pmc;
|
||
let mut syscon = hal.syscon;
|
||
let mut gpio = hal.gpio.enabled(&mut syscon);
|
||
let mut iocon = hal.iocon.enabled(&mut syscon);
|
||
|
||
debug!("start");
|
||
|
||
debug!("iocon");
|
||
let usb0_vbus_pin = pins::Pio0_22::take()
|
||
.unwrap()
|
||
.into_usb0_vbus_pin(&mut iocon);
|
||
|
||
#[cfg(not(feature = "evk"))]
|
||
let codec_i2c_pins = (
|
||
pins::Pio0_16::take().unwrap().into_i2c4_scl_pin(&mut iocon),
|
||
pins::Pio0_5::take().unwrap().into_i2c4_sda_pin(&mut iocon),
|
||
);
|
||
#[cfg(feature = "evk")]
|
||
let codec_i2c_pins = (
|
||
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 = (
|
||
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),
|
||
pins::Pio0_23::take().unwrap(),
|
||
);
|
||
let codec_gpio_pins = CodecPins {
|
||
reset: pins::Pio0_3::take()
|
||
.unwrap()
|
||
.into_gpio_pin(&mut iocon, &mut gpio)
|
||
.into_output_low(),
|
||
};
|
||
let clock_sel_pins = ClockSelPins {
|
||
sel_24m: pins::Pio0_27::take()
|
||
.unwrap()
|
||
.into_gpio_pin(&mut iocon, &mut gpio)
|
||
.into_output_low(),
|
||
sel_22m: pins::Pio0_31::take()
|
||
.unwrap()
|
||
.into_gpio_pin(&mut iocon, &mut gpio)
|
||
.into_output_low(),
|
||
};
|
||
|
||
hw::init_leds(&mut iocon, &mut gpio);
|
||
|
||
// iocon.disabled(&mut syscon).release(); // save the environment :)
|
||
|
||
debug!("clocks");
|
||
let clocks = hal::ClockRequirements::default()
|
||
.system_frequency(96.MHz())
|
||
.configure(&mut anactrl, &mut pmc, &mut syscon)
|
||
.unwrap();
|
||
hw::init_sys_pll1();
|
||
#[cfg(feature = "evk")]
|
||
hw::init_audio_pll();
|
||
|
||
let mut delay_timer = Timer::new(
|
||
hal.ctimer
|
||
.0
|
||
.enabled(&mut syscon, clocks.support_1mhz_fro_token().unwrap()),
|
||
);
|
||
|
||
debug!("peripherals");
|
||
|
||
let i2c_peripheral = hal
|
||
.flexcomm
|
||
.4
|
||
.enabled_as_i2c(&mut syscon, &clocks.support_flexcomm_token().unwrap());
|
||
|
||
let i2c_bus = I2cMaster::new(
|
||
i2c_peripheral,
|
||
codec_i2c_pins,
|
||
Hertz::try_from(400.kHz()).unwrap(),
|
||
);
|
||
let dac_impl = DacImpl::new(i2c_bus, codec_gpio_pins);
|
||
|
||
let i2s_peripheral = {
|
||
let fc7 = hal.flexcomm.7.release();
|
||
init_i2s(fc7.0, fc7.2, &mut syscon)
|
||
};
|
||
|
||
let usb_peripheral = hal.usbhs.enabled_as_device(
|
||
&mut anactrl,
|
||
&mut pmc,
|
||
&mut syscon,
|
||
&mut delay_timer,
|
||
clocks.support_usbhs_token().unwrap(),
|
||
);
|
||
|
||
defmt::info!("dma init");
|
||
let i2s_dma_addr = &i2s_peripheral.i2s.fifowr as *const _ as *mut u32;
|
||
let dma = DmaRing::<N_SLOTS, MAX_BYTES_PER_SLOT>::new(
|
||
hal.dma.release(),
|
||
&mut syscon,
|
||
i2s_dma_addr,
|
||
4,
|
||
)
|
||
.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) };
|
||
|
||
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)),
|
||
alt_setting: 0,
|
||
nodata_timeout_frame: AtomicUsize::new(0),
|
||
cur_rate: SAMPLE_RATES[0].min,
|
||
clock_pins: clock_sel_pins,
|
||
_marker: core::marker::PhantomData,
|
||
};
|
||
audio.init();
|
||
|
||
let usb_bus = UsbBus::new(usb_peripheral, usb0_vbus_pin);
|
||
|
||
let config = UsbAudioClassConfig::new(UsbSpeed::High, FunctionCode::Other, &mut audio)
|
||
.with_output_config(
|
||
TerminalConfig::builder()
|
||
.base_id(2)
|
||
.terminal_type(TerminalType::UsbUndefined)
|
||
.build(),
|
||
);
|
||
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 usb_dev = usbd_uac2::builder(&usb_bus, UsbVidPid(0x1209, 0xcc1d))
|
||
.strings(&[StringDescriptors::default()
|
||
.manufacturer("VE7XEN")
|
||
.product("Guac Tortilla")])
|
||
.unwrap()
|
||
.max_packet_size_0(64)
|
||
.unwrap()
|
||
.build();
|
||
|
||
// 1. Initialize the HID timer conditionally outside the closure
|
||
#[cfg(feature = "hid")]
|
||
let mut hid_update_timer = {
|
||
let mut 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
|
||
};
|
||
|
||
// 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(),
|
||
}
|
||
}
|
||
|
||
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);
|
||
}
|
||
// LPC55 CTIMER is not periodic; restart manually
|
||
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)
|
||
}
|
||
}
|
||
Err(UsbError::WouldBlock) => {}
|
||
Err(e) => defmt::error!("Invalid report: {:?}", e),
|
||
}
|
||
}
|
||
};
|
||
|
||
defmt::info!("main loop");
|
||
|
||
loop {
|
||
poll_all();
|
||
}
|
||
}
|