mirror of
https://github.com/LegitCamper/picocalc-os-rs.git
synced 2025-12-27 07:45:28 +00:00
Compare commits
8 Commits
d17c3de72f
...
audio-driv
| Author | SHA1 | Date | |
|---|---|---|---|
| 39ced811c3 | |||
| 90d32f050c | |||
| 0e7e330998 | |||
| 8c20864392 | |||
| 7efea9eb8d | |||
| edbd598803 | |||
| 4c63f77c24 | |||
| d8a5ab465e |
21
Cargo.lock
generated
21
Cargo.lock
generated
@@ -898,6 +898,14 @@ dependencies = [
|
||||
"rlsf",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "embedded-audio"
|
||||
version = "0.1.0"
|
||||
source = "git+https://github.com/LegitCamper/embedded-audio#087784644d810b94dd659a03dbed4795dfb0bd24"
|
||||
dependencies = [
|
||||
"heapless",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "embedded-graphics"
|
||||
version = "0.8.1"
|
||||
@@ -1470,8 +1478,10 @@ dependencies = [
|
||||
"embedded-layout",
|
||||
"embedded-sdmmc",
|
||||
"embedded-text",
|
||||
"fixed",
|
||||
"goblin",
|
||||
"heapless",
|
||||
"micromath",
|
||||
"num_enum 0.7.5",
|
||||
"once_cell",
|
||||
"panic-probe",
|
||||
@@ -2744,6 +2754,17 @@ dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wav_player"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"abi",
|
||||
"embedded-audio",
|
||||
"embedded-graphics",
|
||||
"rand",
|
||||
"selection_ui",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "winapi"
|
||||
version = "0.3.9"
|
||||
|
||||
@@ -9,6 +9,7 @@ members = [
|
||||
"user-apps/snake",
|
||||
"user-apps/gallery",
|
||||
"user-apps/gif",
|
||||
"user-apps/wav_player",
|
||||
]
|
||||
|
||||
[profile.release]
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
extern crate alloc;
|
||||
|
||||
use abi_sys::{RngRequest, alloc, dealloc, keyboard::KeyEvent};
|
||||
use abi_sys::{RngRequest, keyboard::KeyEvent};
|
||||
pub use abi_sys::{keyboard, print};
|
||||
pub use alloc::format;
|
||||
use core::alloc::{GlobalAlloc, Layout};
|
||||
@@ -16,11 +16,11 @@ struct Alloc;
|
||||
|
||||
unsafe impl GlobalAlloc for Alloc {
|
||||
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
|
||||
alloc(layout.into())
|
||||
abi_sys::alloc(layout.into())
|
||||
}
|
||||
|
||||
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
|
||||
dealloc(ptr, layout.into());
|
||||
abi_sys::dealloc(ptr, layout.into());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -267,3 +267,11 @@ pub mod fs {
|
||||
abi_sys::file_len(str.as_ptr(), str.len())
|
||||
}
|
||||
}
|
||||
|
||||
pub mod audio {
|
||||
pub use abi_sys::{AUDIO_BUFFER_LEN, AUDIO_BUFFER_SAMPLES, audio_buffer_ready};
|
||||
|
||||
pub fn send_audio_buffer(buf: &[u8]) {
|
||||
abi_sys::send_audio_buffer(buf.as_ptr(), buf.len())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ use strum::{EnumCount, EnumIter};
|
||||
|
||||
pub type EntryFn = fn();
|
||||
|
||||
pub const ABI_CALL_TABLE_COUNT: usize = 12;
|
||||
pub const ABI_CALL_TABLE_COUNT: usize = 14;
|
||||
const _: () = assert!(ABI_CALL_TABLE_COUNT == CallTable::COUNT);
|
||||
|
||||
#[derive(Clone, Copy, EnumIter, EnumCount)]
|
||||
@@ -30,6 +30,8 @@ pub enum CallTable {
|
||||
ReadFile = 9,
|
||||
WriteFile = 10,
|
||||
FileLen = 11,
|
||||
AudioBufferReady = 12,
|
||||
SendAudioBuffer = 13,
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
@@ -467,3 +469,28 @@ pub extern "C" fn file_len(str: *const u8, len: usize) -> usize {
|
||||
f(str, len)
|
||||
}
|
||||
}
|
||||
|
||||
pub type AudioBufferReady = extern "C" fn() -> bool;
|
||||
|
||||
#[allow(unused)]
|
||||
pub fn audio_buffer_ready() -> bool {
|
||||
unsafe {
|
||||
let ptr = CALL_ABI_TABLE[CallTable::AudioBufferReady as usize];
|
||||
let f: AudioBufferReady = core::mem::transmute(ptr);
|
||||
f()
|
||||
}
|
||||
}
|
||||
|
||||
pub const AUDIO_BUFFER_SAMPLES: usize = 1024;
|
||||
pub const AUDIO_BUFFER_LEN: usize = AUDIO_BUFFER_SAMPLES * 2;
|
||||
|
||||
pub type SendAudioBuffer = extern "C" fn(ptr: *const u8, len: usize);
|
||||
|
||||
#[allow(unused)]
|
||||
pub fn send_audio_buffer(buf: *const u8, len: usize) {
|
||||
unsafe {
|
||||
let ptr = CALL_ABI_TABLE[CallTable::SendAudioBuffer as usize];
|
||||
let f: SendAudioBuffer = core::mem::transmute(ptr);
|
||||
f(buf, len)
|
||||
}
|
||||
}
|
||||
|
||||
2
justfile
2
justfile
@@ -39,6 +39,7 @@ userapps: cbindgen
|
||||
just userapp snake
|
||||
just userapp gallery
|
||||
just userapp gif
|
||||
just userapp wav_player
|
||||
|
||||
copy-userapp app:
|
||||
cp ./target/thumbv8m.main-none-eabihf/release-binary/{{app}} /run/media/$(whoami)/PICOCALC/{{app}}.bin
|
||||
@@ -50,6 +51,7 @@ copy-userapps:
|
||||
just copy-userapp snake
|
||||
just copy-userapp gallery
|
||||
just copy-userapp gif
|
||||
just copy-userapp wav_player
|
||||
|
||||
DEV=$(lsblk -o LABEL,NAME -nr | awk -v L="PICOCALC" '$1==L {print "/dev/" $2}')
|
||||
udisksctl unmount -b "$DEV"
|
||||
|
||||
@@ -82,6 +82,8 @@ embedded-graphics = { version = "0.8.1" }
|
||||
embedded-text = "0.7.2"
|
||||
embedded-layout = "0.4.2"
|
||||
|
||||
micromath = "2.1.0"
|
||||
fixed = "1.29.0"
|
||||
strum = { version = "0.27.2", default-features = false }
|
||||
rand = { version = "0.9.0", default-features = false }
|
||||
once_cell = { version = "1.21.3", default-features = false }
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use abi_sys::{
|
||||
AllocAbi, CLayout, CPixel, DeallocAbi, DrawIterAbi, FileLen, GenRand, GetMsAbi, ListDir,
|
||||
PrintAbi, ReadFile, RngRequest, SleepMsAbi, WriteFile, keyboard::*,
|
||||
AUDIO_BUFFER_SAMPLES, AllocAbi, AudioBufferReady, CLayout, CPixel, DeallocAbi, DrawIterAbi,
|
||||
FileLen, GenRand, GetMsAbi, ListDir, PrintAbi, ReadFile, RngRequest, SendAudioBuffer,
|
||||
SleepMsAbi, WriteFile, keyboard::*,
|
||||
};
|
||||
use alloc::{string::ToString, vec::Vec};
|
||||
use core::{ffi::c_char, ptr, sync::atomic::Ordering};
|
||||
@@ -17,6 +18,7 @@ use crate::heap::HEAP;
|
||||
use core::alloc::GlobalAlloc;
|
||||
|
||||
use crate::{
|
||||
audio::{AUDIO_BUFFER, AUDIO_BUFFER_READY},
|
||||
display::FRAMEBUFFER,
|
||||
framebuffer::FB_PAUSED,
|
||||
storage::{Dir, File, SDCARD},
|
||||
@@ -207,7 +209,6 @@ fn recurse_file<T>(
|
||||
dirs: &[&str],
|
||||
mut access: impl FnMut(&mut File) -> T,
|
||||
) -> Result<T, ()> {
|
||||
defmt::info!("dir: {}, dirs: {}", dir, dirs);
|
||||
if dirs.len() == 1 {
|
||||
let mut b = [0_u8; 50];
|
||||
let mut buf = LfnBuffer::new(&mut b);
|
||||
@@ -331,3 +332,28 @@ pub extern "C" fn file_len(str: *const u8, len: usize) -> usize {
|
||||
}
|
||||
len as usize
|
||||
}
|
||||
|
||||
const _: AudioBufferReady = audio_buffer_ready;
|
||||
pub extern "C" fn audio_buffer_ready() -> bool {
|
||||
AUDIO_BUFFER_READY.load(Ordering::Acquire)
|
||||
}
|
||||
|
||||
const _: SendAudioBuffer = send_audio_buffer;
|
||||
pub extern "C" fn send_audio_buffer(ptr: *const u8, len: usize) {
|
||||
// SAFETY: caller guarantees `ptr` is valid for `len` bytes
|
||||
let buf = unsafe { core::slice::from_raw_parts(ptr, len) };
|
||||
|
||||
while !AUDIO_BUFFER_READY.load(Ordering::Acquire) {}
|
||||
|
||||
if buf.len() == AUDIO_BUFFER_SAMPLES * 2 {
|
||||
AUDIO_BUFFER_READY.store(false, Ordering::Release);
|
||||
unsafe { AUDIO_BUFFER.copy_from_slice(buf) };
|
||||
} else {
|
||||
#[cfg(feature = "defmt")]
|
||||
defmt::warn!(
|
||||
"user audio stream was wrong size: {} should be {}",
|
||||
buf.len(),
|
||||
AUDIO_BUFFER_SAMPLES * 2
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
149
kernel/src/audio.rs
Normal file
149
kernel/src/audio.rs
Normal file
@@ -0,0 +1,149 @@
|
||||
use crate::Audio;
|
||||
use core::sync::atomic::{AtomicBool, Ordering};
|
||||
use embassy_futures::join::join;
|
||||
use embassy_rp::{
|
||||
Peri,
|
||||
clocks::clk_sys_freq,
|
||||
dma::{AnyChannel, Channel},
|
||||
gpio::Level,
|
||||
pio::{
|
||||
Common, Config, Direction, FifoJoin, Instance, LoadedProgram, PioPin, ShiftConfig,
|
||||
StateMachine, program::pio_asm,
|
||||
},
|
||||
};
|
||||
use fixed::traits::ToFixed;
|
||||
|
||||
pub const SAMPLE_RATE_HZ: u32 = 22_050;
|
||||
const AUDIO_BUFFER_SAMPLES: usize = 1024;
|
||||
const _: () = assert!(AUDIO_BUFFER_SAMPLES == abi_sys::AUDIO_BUFFER_SAMPLES);
|
||||
|
||||
// 8bit stereo interleaved PCM audio buffers
|
||||
pub static mut AUDIO_BUFFER: [u8; AUDIO_BUFFER_SAMPLES * 2] = [0; AUDIO_BUFFER_SAMPLES * 2];
|
||||
static mut AUDIO_BUFFER_1: [u8; AUDIO_BUFFER_SAMPLES * 2] = [0; AUDIO_BUFFER_SAMPLES * 2];
|
||||
|
||||
pub static AUDIO_BUFFER_READY: AtomicBool = AtomicBool::new(true);
|
||||
|
||||
#[embassy_executor::task]
|
||||
pub async fn audio_handler(mut audio: Audio) {
|
||||
const SILENCE_VALUE: u8 = u8::MAX / 2;
|
||||
|
||||
let prg = PioPwmAudioProgram8Bit::new(&mut audio.pio);
|
||||
let mut pwm_pio_left =
|
||||
PioPwmAudio::new(audio.dma0, &mut audio.pio, audio.sm0, audio.left, &prg);
|
||||
let mut pwm_pio_right =
|
||||
PioPwmAudio::new(audio.dma1, &mut audio.pio, audio.sm1, audio.right, &prg);
|
||||
|
||||
loop {
|
||||
write_samples(&mut pwm_pio_left, &mut pwm_pio_right, unsafe {
|
||||
&AUDIO_BUFFER_1
|
||||
})
|
||||
.await;
|
||||
unsafe { &mut AUDIO_BUFFER_1 }.fill(SILENCE_VALUE);
|
||||
|
||||
unsafe { core::mem::swap(&mut AUDIO_BUFFER, &mut AUDIO_BUFFER_1) };
|
||||
AUDIO_BUFFER_READY.store(true, Ordering::Release)
|
||||
}
|
||||
}
|
||||
|
||||
async fn write_samples<PIO: Instance>(
|
||||
left: &mut PioPwmAudio<'static, PIO, 0>,
|
||||
right: &mut PioPwmAudio<'static, PIO, 1>,
|
||||
buf: &[u8],
|
||||
) {
|
||||
// pack two samples per word
|
||||
let mut packed_buf_left: [u32; AUDIO_BUFFER_SAMPLES / 2] = [0; AUDIO_BUFFER_SAMPLES / 2];
|
||||
let mut packed_buf_right: [u32; AUDIO_BUFFER_SAMPLES / 2] = [0; AUDIO_BUFFER_SAMPLES / 2];
|
||||
|
||||
for ((pl, pr), sample) in packed_buf_left
|
||||
.iter_mut()
|
||||
.zip(packed_buf_right.iter_mut())
|
||||
.zip(buf.chunks(4))
|
||||
{
|
||||
*pl = pack_u8_samples(sample[0], sample[2]);
|
||||
*pr = pack_u8_samples(sample[1], sample[3]);
|
||||
}
|
||||
|
||||
let left_fut = left
|
||||
.sm
|
||||
.tx()
|
||||
.dma_push(left.dma.reborrow(), &packed_buf_left, false);
|
||||
|
||||
let right_fut = right
|
||||
.sm
|
||||
.tx()
|
||||
.dma_push(right.dma.reborrow(), &packed_buf_right, false);
|
||||
|
||||
join(left_fut, right_fut).await;
|
||||
}
|
||||
|
||||
struct PioPwmAudioProgram8Bit<'d, PIO: Instance>(LoadedProgram<'d, PIO>);
|
||||
|
||||
/// Writes one sample to pwm as high and low time
|
||||
impl<'d, PIO: Instance> PioPwmAudioProgram8Bit<'d, PIO> {
|
||||
fn new(common: &mut Common<'d, PIO>) -> Self {
|
||||
// only uses 16 bits top for high, bottom for low
|
||||
// allows two samples per word
|
||||
let prg = pio_asm!(
|
||||
"out x, 8", // pwm high time
|
||||
"out y, 8", // pwm low time
|
||||
"loop_high:",
|
||||
"set pins, 1", // keep pin high
|
||||
"jmp x-- loop_high", // decrement X until 0
|
||||
"loop_low:",
|
||||
"set pins, 0", // keep pin low
|
||||
"jmp y-- loop_low", // decrement Y until 0
|
||||
);
|
||||
|
||||
let prg = common.load_program(&prg.program);
|
||||
|
||||
Self(prg)
|
||||
}
|
||||
}
|
||||
|
||||
struct PioPwmAudio<'d, PIO: Instance, const SM: usize> {
|
||||
dma: Peri<'d, AnyChannel>,
|
||||
sm: StateMachine<'d, PIO, SM>,
|
||||
}
|
||||
|
||||
impl<'d, PIO: Instance, const SM: usize> PioPwmAudio<'d, PIO, SM> {
|
||||
fn new(
|
||||
dma: Peri<'d, impl Channel>,
|
||||
pio: &mut Common<'d, PIO>,
|
||||
mut sm: StateMachine<'d, PIO, SM>,
|
||||
pin: Peri<'d, impl PioPin>,
|
||||
prg: &PioPwmAudioProgram8Bit<'d, PIO>,
|
||||
) -> Self {
|
||||
let pin = pio.make_pio_pin(pin);
|
||||
sm.set_pins(Level::High, &[&pin]);
|
||||
sm.set_pin_dirs(Direction::Out, &[&pin]);
|
||||
|
||||
let mut cfg = Config::default();
|
||||
cfg.set_set_pins(&[&pin]);
|
||||
cfg.fifo_join = FifoJoin::TxOnly;
|
||||
let mut shift_cfg = ShiftConfig::default();
|
||||
shift_cfg.auto_fill = true;
|
||||
cfg.shift_out = shift_cfg;
|
||||
cfg.use_program(&prg.0, &[]);
|
||||
sm.set_config(&cfg);
|
||||
|
||||
let target_clock = (u8::MAX as u32 + 1) * SAMPLE_RATE_HZ;
|
||||
let divider = (clk_sys_freq() / (target_clock * 2)).to_fixed();
|
||||
sm.set_clock_divider(divider);
|
||||
|
||||
sm.set_enable(true);
|
||||
|
||||
Self {
|
||||
dma: dma.into(),
|
||||
sm,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// packs two u8 samples into 32bit word
|
||||
fn pack_u8_samples(sample1: u8, sample2: u8) -> u32 {
|
||||
(u8_pcm_to_pwm(sample1) as u32) << 16 | u8_pcm_to_pwm(sample2) as u32
|
||||
}
|
||||
|
||||
fn u8_pcm_to_pwm(sample: u8) -> u16 {
|
||||
((sample as u16) << 8) | ((u8::MAX - sample) as u16)
|
||||
}
|
||||
@@ -1,17 +1,15 @@
|
||||
use crate::framebuffer::{self, AtomicFrameBuffer, FB_PAUSED};
|
||||
use core::alloc::{GlobalAlloc, Layout};
|
||||
use core::sync::atomic::Ordering;
|
||||
use embassy_futures::yield_now;
|
||||
use embassy_rp::{
|
||||
Peri,
|
||||
gpio::{Level, Output},
|
||||
peripherals::{PIN_13, PIN_14, PIN_15, SPI1},
|
||||
spi::{Async, Spi},
|
||||
};
|
||||
use embassy_time::{Delay, Timer};
|
||||
use embedded_graphics::{
|
||||
pixelcolor::Rgb565,
|
||||
prelude::{DrawTarget, RgbColor},
|
||||
};
|
||||
use embassy_time::Delay;
|
||||
use embedded_graphics::{draw_target::DrawTarget, pixelcolor::Rgb565, prelude::RgbColor};
|
||||
use embedded_hal_bus::spi::ExclusiveDevice;
|
||||
use st7365p_lcd::ST7365P;
|
||||
|
||||
@@ -117,7 +115,7 @@ pub async fn display_handler(mut display: DISPLAY) {
|
||||
if elapsed < FRAME_TIME_MS {
|
||||
Timer::after_millis(FRAME_TIME_MS - elapsed).await;
|
||||
} else {
|
||||
Timer::after_millis(1).await;
|
||||
yield_now().await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,8 +2,7 @@ use crate::{
|
||||
abi,
|
||||
storage::{File, SDCARD},
|
||||
};
|
||||
use abi_sys::CallTable;
|
||||
use abi_sys::EntryFn;
|
||||
use abi_sys::{CallTable, EntryFn};
|
||||
use alloc::{vec, vec::Vec};
|
||||
use bumpalo::Bump;
|
||||
use core::ptr;
|
||||
@@ -208,6 +207,8 @@ fn patch_abi(
|
||||
CallTable::ReadFile => abi::read_file as usize,
|
||||
CallTable::WriteFile => abi::write_file as usize,
|
||||
CallTable::FileLen => abi::file_len as usize,
|
||||
CallTable::AudioBufferReady => abi::audio_buffer_ready as usize,
|
||||
CallTable::SendAudioBuffer => abi::send_audio_buffer as usize,
|
||||
};
|
||||
unsafe {
|
||||
table_base.add(idx as usize).write(ptr);
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
extern crate alloc;
|
||||
|
||||
mod abi;
|
||||
mod audio;
|
||||
mod display;
|
||||
mod elf;
|
||||
mod framebuffer;
|
||||
@@ -31,6 +32,7 @@ use crate::{heap::HEAP, heap::init_qmi_psram_heap, psram::init_psram, psram::ini
|
||||
|
||||
use crate::{
|
||||
abi::{KEY_CACHE, MS_SINCE_LAUNCH},
|
||||
audio::audio_handler,
|
||||
display::{FRAMEBUFFER, display_handler, init_display},
|
||||
peripherals::{
|
||||
conf_peripherals,
|
||||
@@ -55,9 +57,9 @@ use embassy_rp::{
|
||||
peripherals::{
|
||||
DMA_CH0, DMA_CH1, DMA_CH3, DMA_CH4, I2C1, PIN_2, PIN_3, PIN_6, PIN_7, PIN_10, PIN_11,
|
||||
PIN_12, PIN_13, PIN_14, PIN_15, PIN_16, PIN_17, PIN_18, PIN_19, PIN_20, PIN_21, PIN_22,
|
||||
PIO0, SPI0, SPI1, USB, WATCHDOG,
|
||||
PIN_26, PIN_27, PIO0, SPI0, SPI1, USB, WATCHDOG,
|
||||
},
|
||||
pio,
|
||||
pio::{self, Common, Pio, StateMachine},
|
||||
spi::{self, Spi},
|
||||
usb as embassy_rp_usb,
|
||||
watchdog::{ResetReason, Watchdog},
|
||||
@@ -119,10 +121,12 @@ async fn watchdog_task(mut watchdog: Watchdog) {
|
||||
static ENABLE_UI: AtomicBool = AtomicBool::new(true);
|
||||
static UI_CHANGE: Signal<CriticalSectionRawMutex, ()> = Signal::new();
|
||||
|
||||
const OVERCLOCK: u32 = 300_000_000;
|
||||
|
||||
#[embassy_executor::main]
|
||||
async fn main(_spawner: Spawner) {
|
||||
let p = if cfg!(feature = "overclock") {
|
||||
let clocks = ClockConfig::system_freq(300_000_000).unwrap();
|
||||
let clocks = ClockConfig::system_freq(OVERCLOCK).unwrap();
|
||||
let config = Config::new(clocks);
|
||||
embassy_rp::init(config)
|
||||
} else {
|
||||
@@ -149,6 +153,19 @@ async fn main(_spawner: Spawner) {
|
||||
data: p.PIN_14,
|
||||
reset: p.PIN_15,
|
||||
};
|
||||
let Pio {
|
||||
common, sm0, sm1, ..
|
||||
} = Pio::new(p.PIO0, Irqs);
|
||||
|
||||
let audio = Audio {
|
||||
pio: common,
|
||||
sm0,
|
||||
dma0: p.DMA_CH3,
|
||||
left: p.PIN_26,
|
||||
sm1,
|
||||
dma1: p.DMA_CH4,
|
||||
right: p.PIN_27,
|
||||
};
|
||||
let sd = Sd {
|
||||
spi: p.SPI0,
|
||||
clk: p.PIN_18,
|
||||
@@ -157,15 +174,15 @@ async fn main(_spawner: Spawner) {
|
||||
cs: p.PIN_17,
|
||||
det: p.PIN_22,
|
||||
};
|
||||
let psram = Psram {
|
||||
pio: p.PIO0,
|
||||
sclk: p.PIN_21,
|
||||
mosi: p.PIN_2,
|
||||
miso: p.PIN_3,
|
||||
cs: p.PIN_20,
|
||||
dma1: p.DMA_CH3,
|
||||
dma2: p.DMA_CH4,
|
||||
};
|
||||
// let psram = Psram {
|
||||
// pio: p.PIO0,
|
||||
// sclk: p.PIN_21,
|
||||
// mosi: p.PIN_2,
|
||||
// miso: p.PIN_3,
|
||||
// cs: p.PIN_20,
|
||||
// dma1: p.DMA_CH3,
|
||||
// dma2: p.DMA_CH4,
|
||||
// };
|
||||
let mcu = Mcu {
|
||||
i2c: p.I2C1,
|
||||
clk: p.PIN_7,
|
||||
@@ -175,7 +192,7 @@ async fn main(_spawner: Spawner) {
|
||||
executor0.run(|spawner| {
|
||||
spawner
|
||||
.spawn(kernel_task(
|
||||
spawner, p.WATCHDOG, display, sd, psram, mcu, p.USB,
|
||||
spawner, p.WATCHDOG, display, audio, sd, mcu, p.USB,
|
||||
))
|
||||
.unwrap()
|
||||
});
|
||||
@@ -229,6 +246,15 @@ struct Display {
|
||||
data: Peri<'static, PIN_14>,
|
||||
reset: Peri<'static, PIN_15>,
|
||||
}
|
||||
struct Audio {
|
||||
pio: Common<'static, PIO0>,
|
||||
dma0: Peri<'static, DMA_CH3>,
|
||||
sm0: StateMachine<'static, PIO0, 0>,
|
||||
left: Peri<'static, PIN_26>,
|
||||
dma1: Peri<'static, DMA_CH4>,
|
||||
sm1: StateMachine<'static, PIO0, 1>,
|
||||
right: Peri<'static, PIN_27>,
|
||||
}
|
||||
struct Sd {
|
||||
spi: Peri<'static, SPI0>,
|
||||
clk: Peri<'static, PIN_18>,
|
||||
@@ -330,8 +356,9 @@ async fn kernel_task(
|
||||
spawner: Spawner,
|
||||
watchdog: Peri<'static, WATCHDOG>,
|
||||
display: Display,
|
||||
audio: Audio,
|
||||
sd: Sd,
|
||||
_psram: Psram,
|
||||
// _psram: Psram,
|
||||
mcu: Mcu,
|
||||
usb: Peri<'static, USB>,
|
||||
) {
|
||||
@@ -356,6 +383,8 @@ async fn kernel_task(
|
||||
setup_display(display, spawner).await;
|
||||
setup_sd(sd).await;
|
||||
|
||||
spawner.spawn(audio_handler(audio)).unwrap();
|
||||
|
||||
let _usb = embassy_rp_usb::Driver::new(usb, Irqs);
|
||||
// spawner.spawn(usb_handler(usb)).unwrap();
|
||||
|
||||
|
||||
11
user-apps/wav_player/Cargo.toml
Normal file
11
user-apps/wav_player/Cargo.toml
Normal file
@@ -0,0 +1,11 @@
|
||||
[package]
|
||||
name = "wav_player"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
|
||||
[dependencies]
|
||||
abi = { path = "../../abi" }
|
||||
selection_ui = { path = "../../selection_ui" }
|
||||
embedded-graphics = "0.8.1"
|
||||
rand = { version = "0.9.0", default-features = false }
|
||||
embedded-audio = { git = "https://github.com/LegitCamper/embedded-audio" }
|
||||
28
user-apps/wav_player/build.rs
Normal file
28
user-apps/wav_player/build.rs
Normal file
@@ -0,0 +1,28 @@
|
||||
//! This build script copies the `memory.x` file from the crate root into
|
||||
//! a directory where the linker can always find it at build time.
|
||||
//! For many projects this is optional, as the linker always searches the
|
||||
//! project root directory -- wherever `Cargo.toml` is. However, if you
|
||||
//! are using a workspace or have a more complicated build setup, this
|
||||
//! build script becomes required. Additionally, by requesting that
|
||||
//! Cargo re-run the build script whenever `memory.x` is changed,
|
||||
//! updating `memory.x` ensures a rebuild of the application with the
|
||||
//! new memory settings.
|
||||
|
||||
use std::env;
|
||||
use std::fs::File;
|
||||
use std::io::Write;
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn main() {
|
||||
// Put `memory.x` in our output directory and ensure it's
|
||||
// on the linker search path.
|
||||
let out = &PathBuf::from(env::var_os("OUT_DIR").unwrap());
|
||||
File::create(out.join("memory.x"))
|
||||
.unwrap()
|
||||
.write_all(include_bytes!("../memory.x"))
|
||||
.unwrap();
|
||||
println!("cargo:rustc-link-search={}", out.display());
|
||||
|
||||
println!("cargo:rerun-if-changed=memory.x");
|
||||
println!("cargo:rustc-link-arg-bins=-Tmemory.x");
|
||||
}
|
||||
139
user-apps/wav_player/src/main.rs
Normal file
139
user-apps/wav_player/src/main.rs
Normal file
@@ -0,0 +1,139 @@
|
||||
#![no_std]
|
||||
#![no_main]
|
||||
|
||||
extern crate alloc;
|
||||
use abi::{
|
||||
audio::{AUDIO_BUFFER_LEN, audio_buffer_ready, send_audio_buffer},
|
||||
display::Display,
|
||||
format,
|
||||
fs::{Entries, file_len, list_dir, read_file},
|
||||
get_key,
|
||||
keyboard::{KeyCode, KeyState},
|
||||
println,
|
||||
};
|
||||
use alloc::{string::String, vec::Vec};
|
||||
use core::panic::PanicInfo;
|
||||
use embedded_audio::{AudioFile, PlatformFile, PlatformFileError, wav::Wav};
|
||||
use embedded_graphics::{
|
||||
mono_font::{MonoTextStyle, ascii::FONT_6X10},
|
||||
pixelcolor::Rgb565,
|
||||
prelude::RgbColor,
|
||||
};
|
||||
use selection_ui::{SelectionUi, SelectionUiError, draw_text_center};
|
||||
|
||||
#[panic_handler]
|
||||
fn panic(info: &PanicInfo) -> ! {
|
||||
println!("user panic: {} @ {:?}", info.message(), info.location(),);
|
||||
loop {}
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "Rust" fn _start() {
|
||||
main()
|
||||
}
|
||||
|
||||
pub fn main() {
|
||||
println!("Starting Wav player app");
|
||||
let mut display = Display::take().unwrap();
|
||||
|
||||
loop {
|
||||
let mut entries = Entries::new();
|
||||
list_dir("/music", &mut entries);
|
||||
|
||||
let mut files = entries.entries();
|
||||
files.retain(|e| e.extension().unwrap_or("") == "wav");
|
||||
let mut wavs = files.iter().map(|e| e.full_name()).collect::<Vec<&str>>();
|
||||
wavs.sort();
|
||||
|
||||
let mut selection_ui = SelectionUi::new(&mut wavs);
|
||||
let selection = match selection_ui.run_selection_ui(&mut display) {
|
||||
Ok(maybe_sel) => maybe_sel,
|
||||
Err(e) => match e {
|
||||
SelectionUiError::SelectionListEmpty => {
|
||||
draw_text_center(
|
||||
&mut display,
|
||||
"No Wavs were found in /gifs",
|
||||
MonoTextStyle::new(&FONT_6X10, Rgb565::RED),
|
||||
)
|
||||
.expect("Display Error");
|
||||
None
|
||||
}
|
||||
SelectionUiError::DisplayError(_) => panic!("Display Error"),
|
||||
},
|
||||
};
|
||||
|
||||
assert!(selection.is_some());
|
||||
|
||||
let file_name = format!("/music/{}", wavs[selection.unwrap()]);
|
||||
let file = File::new(String::from(file_name));
|
||||
let mut wav = Wav::new(file).unwrap();
|
||||
println!("sample rate: {}", wav.sample_rate());
|
||||
println!("channels: {:?}", wav.channels() as u8);
|
||||
|
||||
let mut buf = [0_u8; AUDIO_BUFFER_LEN];
|
||||
|
||||
loop {
|
||||
if audio_buffer_ready() {
|
||||
if wav.is_eof() {
|
||||
break;
|
||||
}
|
||||
|
||||
let _read = wav.read(&mut buf).unwrap();
|
||||
send_audio_buffer(&buf);
|
||||
}
|
||||
|
||||
let event = get_key();
|
||||
if event.state == KeyState::Released {
|
||||
match event.key {
|
||||
KeyCode::Esc => return,
|
||||
_ => (),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct File {
|
||||
current_pos: usize,
|
||||
file: String,
|
||||
}
|
||||
|
||||
impl File {
|
||||
fn new(file: String) -> Self {
|
||||
Self {
|
||||
current_pos: 0,
|
||||
file,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PlatformFile for File {
|
||||
fn read(&mut self, buf: &mut [u8]) -> Result<usize, PlatformFileError> {
|
||||
let read = read_file(&self.file, self.current_pos, buf);
|
||||
self.current_pos += read;
|
||||
Ok(read)
|
||||
}
|
||||
|
||||
fn seek_from_current(&mut self, offset: i64) -> Result<(), PlatformFileError> {
|
||||
if offset.is_positive() {
|
||||
self.current_pos += offset as usize;
|
||||
} else {
|
||||
self.current_pos -= offset as usize;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn seek_from_start(&mut self, offset: usize) -> Result<(), PlatformFileError> {
|
||||
self.current_pos = offset;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn seek_from_end(&mut self, offset: usize) -> Result<(), PlatformFileError> {
|
||||
self.current_pos = self.length() - offset;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn length(&mut self) -> usize {
|
||||
file_len(&self.file)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user