format services/codec

This commit is contained in:
bunnie 2024-01-14 22:05:15 +08:00
parent 81c5a1da57
commit 27a21e9112
6 changed files with 383 additions and 327 deletions

View file

@ -1,4 +1,4 @@
pub(crate) const SERVER_NAME_CODEC: &str = "_Low-level Audio Codec Server_";
pub(crate) const SERVER_NAME_CODEC: &str = "_Low-level Audio Codec Server_";
#[allow(dead_code)]
#[derive(num_derive::FromPrimitive, num_derive::ToPrimitive, Debug)]
@ -24,9 +24,11 @@ pub(crate) enum Opcode {
/// Powers on the CODEC, sets up 8k stereo streaming; puts audio in "paused" state
Setup8kStereo,
/// Pause the stream without powering anything off. Will wait until the current playback frames in process are finished.
/// Pause the stream without powering anything off. Will wait until the current playback frames in
/// process are finished.
PauseStream,
/// Pause the stream without powering anything off. Clears the buffer immediately, losing any frames in playback.
/// Pause the stream without powering anything off. Clears the buffer immediately, losing any frames in
/// playback.
AbortStream,
/// Resumes the stream withouth re-initializing anything
@ -69,7 +71,6 @@ pub enum VolumeOps {
RestoreDefault,
}
#[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)]
pub(crate) enum EventCallback {
Event,
@ -79,8 +80,10 @@ pub(crate) enum EventCallback {
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone)]
pub(crate) struct ScalarHook {
pub sid: (u32, u32, u32, u32),
pub id: u32, // ID of the scalar message to send through (e.g. the discriminant of the Enum on the caller's side API)
pub cid: xous::CID, // caller-side connection ID for the scalar message to route to. Created by the caller before hooking.
pub id: u32, /* ID of the scalar message to send through (e.g. the discriminant of the Enum on the
* caller's side API) */
pub cid: xous::CID, /* caller-side connection ID for the scalar message to route to. Created by the
* caller before hooking. */
}
//////////////////////////////////////////////////////////////////////////////////////
@ -128,31 +131,30 @@ impl FrameRing {
auth_token: None,
}
}
pub fn clear(&mut self) {
self.buffer = [[(ZERO_PCM as u32 | (ZERO_PCM as u32) << 16); FIFO_DEPTH]; FRAMES];
self.rd_frame = 0;
self.wr_frame = 0;
self.rec_ptr = 0;
}
pub fn reset_ptrs(&mut self) {
self.rd_frame = 0;
self.wr_frame = 0;
self.rec_ptr = 0;
}
/*
empty: rd_frame == wr_frame
full: wr_frame == (rd_frame - 1) || (rd_frame == 0) && (wr_frame == F-1)
*/
pub fn is_empty(&self) -> bool {
self.rd_frame == self.wr_frame
}
pub fn is_empty(&self) -> bool { self.rd_frame == self.wr_frame }
pub fn is_full(&self) -> bool {
if self.rd_frame == 0 {
self.wr_frame == FRAMES-1
} else {
self.wr_frame == (self.rd_frame - 1)
}
if self.rd_frame == 0 { self.wr_frame == FRAMES - 1 } else { self.wr_frame == (self.rd_frame - 1) }
}
pub fn readable_count(&self) -> usize {
if self.wr_frame >= self.rd_frame {
self.wr_frame - self.rd_frame
@ -160,10 +162,11 @@ impl FrameRing {
self.wr_frame + FRAMES - self.rd_frame
}
}
pub fn writeable_count(&self) -> usize {
(FRAMES-1) - self.readable_count()
}
// this is less time efficient, but more space efficient, as we don't allocate intermediate buffers, clear them, etc.
pub fn writeable_count(&self) -> usize { (FRAMES - 1) - self.readable_count() }
// this is less time efficient, but more space efficient, as we don't allocate intermediate buffers, clear
// them, etc.
pub fn rec_sample(&mut self, sample: u32) -> bool {
if self.rec_ptr < FIFO_DEPTH {
self.buffer[self.wr_frame][self.rec_ptr] = sample;
@ -173,6 +176,7 @@ impl FrameRing {
false
}
}
pub fn rec_advance(&mut self) -> bool {
if self.is_full() {
false
@ -182,6 +186,7 @@ impl FrameRing {
true
}
}
pub fn nq_frame(&mut self, frame: [u32; FIFO_DEPTH]) -> Result<(), [u32; FIFO_DEPTH]> {
if self.is_full() {
return Err(frame);
@ -194,6 +199,7 @@ impl FrameRing {
self.rec_ptr = 0;
Ok(())
}
pub fn dq_frame(&mut self) -> Option<[u32; FIFO_DEPTH]> {
if self.is_empty() {
None

View file

@ -2,95 +2,60 @@
use codec::FIFO_DEPTH;
pub struct Codec {
}
pub struct Codec {}
impl Codec {
pub fn new(_conn: xous::CID, _xns: &xous_names::XousNames) -> Codec {
Codec {
}
}
pub fn suspend(&self) {
}
pub fn resume(&self) {
}
pub fn init(&mut self) {
}
pub fn new(_conn: xous::CID, _xns: &xous_names::XousNames) -> Codec { Codec {} }
pub fn nq_play_frame(&mut self, _frame: [u32; FIFO_DEPTH]) -> Result<(), [u32; FIFO_DEPTH]> {
Ok(())
}
pub fn dq_rec_frame(&mut self) -> Option<[u32; FIFO_DEPTH]> {
None
}
pub fn free_play_frames(&self) -> usize {
0
}
pub fn suspend(&self) {}
pub fn can_play(&self) -> bool {
false
}
pub fn resume(&self) {}
pub fn drain(&mut self) {
}
pub fn init(&mut self) {}
pub fn available_rec_frames(&self) -> usize {
0
}
pub fn nq_play_frame(&mut self, _frame: [u32; FIFO_DEPTH]) -> Result<(), [u32; FIFO_DEPTH]> { Ok(()) }
pub fn power(&mut self, _state: bool) {
}
pub fn dq_rec_frame(&mut self) -> Option<[u32; FIFO_DEPTH]> { None }
pub fn is_on(&self) -> bool {
false
}
pub fn is_init(&self) -> bool {
true
}
pub fn is_live(&self) -> bool {
false
}
pub fn free_play_frames(&self) -> usize { 0 }
pub fn get_headset_code(&mut self) -> u8 {
0
}
pub fn can_play(&self) -> bool { false }
pub fn get_dacflag_code(&mut self) -> u8 {
0
}
pub fn drain(&mut self) {}
pub fn get_hp_status(&mut self) -> u8 {
0
}
pub fn available_rec_frames(&self) -> usize { 0 }
pub fn get_i2s_config(&mut self) -> [u8; 4] {
[0, 0, 0, 0]
}
pub fn power(&mut self, _state: bool) {}
pub fn audio_clocks(&mut self) {
}
pub fn is_on(&self) -> bool { false }
pub fn audio_ports(&mut self) {
}
pub fn is_init(&self) -> bool { true }
pub fn audio_loopback(&mut self, _do_loop:bool) {
}
pub fn is_live(&self) -> bool { false }
pub fn get_headset_code(&mut self) -> u8 { 0 }
pub fn get_dacflag_code(&mut self) -> u8 { 0 }
pub fn get_hp_status(&mut self) -> u8 { 0 }
pub fn get_i2s_config(&mut self) -> [u8; 4] { [0, 0, 0, 0] }
pub fn audio_clocks(&mut self) {}
pub fn audio_ports(&mut self) {}
pub fn audio_loopback(&mut self, _do_loop: bool) {}
/// set up the audio mixer to sane defaults
pub fn audio_mixer(&mut self) {
}
pub fn audio_mixer(&mut self) {}
/// set up the betrusted-side signals
pub fn audio_i2s_start(&mut self) {
}
pub fn audio_i2s_start(&mut self) {}
pub fn audio_i2s_stop(&mut self) {
}
pub fn audio_i2s_stop(&mut self) {}
pub fn set_speaker_gain_db(&mut self, _gain_db: f32) {
}
pub fn set_headphone_gain_db(&mut self, _gain_db_l: f32, _gain_db_r: f32) {
}
pub fn set_speaker_gain_db(&mut self, _gain_db: f32) {}
pub fn set_headphone_gain_db(&mut self, _gain_db_l: f32, _gain_db_r: f32) {}
}

View file

@ -3,7 +3,7 @@ mod hostaudio;
#[cfg(not(target_os = "xous"))]
pub use crate::backend::hostaudio::*;
#[cfg(any(feature="precursor", feature="renode"))]
#[cfg(any(feature = "precursor", feature = "renode"))]
mod tlv320aic3100;
#[cfg(any(feature="precursor", feature="renode"))]
#[cfg(any(feature = "precursor", feature = "renode"))]
pub(crate) use crate::backend::tlv320aic3100::*;

View file

@ -1,12 +1,14 @@
#![allow(dead_code)]
use core::sync::atomic::{AtomicBool, Ordering::SeqCst};
use llio::I2cStatus;
use num_traits::*;
use susres::{RegManager, RegOrField, SuspendResume};
use utralib::generated::*;
use xous::MemoryRange;
use susres::{RegManager, RegOrField, SuspendResume};
use llio::I2cStatus;
use crate::api::*;
use num_traits::*;
use core::sync::atomic::{AtomicBool, Ordering::SeqCst};
static INTERRUPT_HOOKED: AtomicBool = AtomicBool::new(false);
@ -16,7 +18,7 @@ const I2C_TIMEOUT: u32 = 50;
pub struct Codec {
csr: utralib::CSR<u32>,
fifo: MemoryRange,
susres_manager: RegManager<{utra::audio::AUDIO_NUMREGS}>,
susres_manager: RegManager<{ utra::audio::AUDIO_NUMREGS }>,
llio: llio::Llio,
i2c: llio::I2c,
ticktimer: ticktimer_server::Ticktimer,
@ -68,8 +70,12 @@ fn audio_handler(_irq_no: usize, arg: *mut usize) {
for &stereo_sample in frame.iter() {
if true {
//// TODO
// there is some bug which is causing the right channel to be frame shifted left by one, but not the left....could be a hardware bug.
unsafe { volatile_audio.write_volatile((stereo_sample & 0xFFFF_0000) | ((stereo_sample & 0xFFFF) >> 1)) };
// there is some bug which is causing the right channel to be frame shifted left by one, but
// not the left....could be a hardware bug.
unsafe {
volatile_audio
.write_volatile((stereo_sample & 0xFFFF_0000) | ((stereo_sample & 0xFFFF) >> 1))
};
} else {
unsafe { volatile_audio.write_volatile(stereo_sample) };
}
@ -89,19 +95,22 @@ fn audio_handler(_irq_no: usize, arg: *mut usize) {
let mut rec_buf: [u32; FIFO_DEPTH] = [ZERO_PCM as u32 | (ZERO_PCM as u32) << 16; FIFO_DEPTH];
for stereo_sample in rec_buf.iter_mut() {
unsafe{ *stereo_sample = volatile_audio.read_volatile(); }
unsafe {
*stereo_sample = volatile_audio.read_volatile();
}
}
match codec.rec_buffer.nq_frame(rec_buf) {
Ok(()) => {},
Err(_buff) => {
codec.rec_frames_dropped += 1
},
Ok(()) => {}
Err(_buff) => codec.rec_frames_dropped += 1,
}
// if the buffer is low, let the audio handler know we used up another frame!
if codec.play_buffer.readable_count() < 6 && !codec.drain {
xous::try_send_message(codec.conn,
xous::Message::new_scalar(Opcode::AnotherFrame.to_usize().unwrap(), rx_rdcount, rx_wrcount, 0, 0)).unwrap();
xous::try_send_message(
codec.conn,
xous::Message::new_scalar(Opcode::AnotherFrame.to_usize().unwrap(), rx_rdcount, rx_wrcount, 0, 0),
)
.unwrap();
}
codec.csr.wfo(utra::audio::EV_PENDING_RX_READY, 1);
@ -153,13 +162,24 @@ impl Codec {
fn trace(&mut self) {
if self.tx_stat_errors > 0 || self.rx_stat_errors > 0 {
log::trace!("drop p:{} r:{} | staterr tx:{} rx:{}", self.play_frames_dropped, self.rec_frames_dropped, self.tx_stat_errors, self.rx_stat_errors);
log::trace!(
"drop p:{} r:{} | staterr tx:{} rx:{}",
self.play_frames_dropped,
self.rec_frames_dropped,
self.tx_stat_errors,
self.rx_stat_errors
);
self.tx_stat_errors = 0;
self.rx_stat_errors = 0;
}
}
fn trace_rx(&self) {
log::trace!("T rd {} wr {}", self.csr.rf(utra::audio::RX_STAT_RDCOUNT), self.csr.rf(utra::audio::RX_STAT_WRCOUNT));
log::trace!(
"T rd {} wr {}",
self.csr.rf(utra::audio::RX_STAT_RDCOUNT),
self.csr.rf(utra::audio::RX_STAT_WRCOUNT)
);
}
pub fn suspend(&mut self) {
@ -168,6 +188,7 @@ impl Codec {
self.llio.audio_on(false).unwrap(); // force the codec into an off state for resume
}
}
pub fn resume(&mut self) {
self.ticktimer.sleep_ms(470).unwrap(); // audio code resume has the lowest priority, it should only resume after most other activities stabilized
if self.powered_on {
@ -186,12 +207,8 @@ impl Codec {
pub fn init(&mut self) {
// this should only be called once per reboot
if !INTERRUPT_HOOKED.swap(true, SeqCst) {
xous::claim_interrupt(
utra::audio::AUDIO_IRQ,
audio_handler,
self as *mut Codec as *mut usize,
)
.expect("couldn't claim audio irq");
xous::claim_interrupt(utra::audio::AUDIO_IRQ, audio_handler, self as *mut Codec as *mut usize)
.expect("couldn't claim audio irq");
self.csr.wfo(utra::audio::EV_PENDING_RX_READY, 1);
self.susres_manager.push(RegOrField::Reg(utra::audio::RX_CTL), None);
@ -217,21 +234,16 @@ impl Codec {
pub fn nq_play_frame(&mut self, frame: [u32; FIFO_DEPTH]) -> Result<(), [u32; FIFO_DEPTH]> {
self.play_buffer.nq_frame(frame)
}
pub fn dq_rec_frame(&mut self) -> Option<[u32; FIFO_DEPTH]> {
self.rec_buffer.dq_frame()
}
pub fn free_play_frames(&self) -> usize {
self.play_buffer.writeable_count()
}
pub fn can_play(&self) -> bool {
!self.play_buffer.is_empty()
}
pub fn drain(&mut self) {
self.drain = true;
}
pub fn available_rec_frames(&self) -> usize {
self.rec_buffer.readable_count()
}
pub fn dq_rec_frame(&mut self) -> Option<[u32; FIFO_DEPTH]> { self.rec_buffer.dq_frame() }
pub fn free_play_frames(&self) -> usize { self.play_buffer.writeable_count() }
pub fn can_play(&self) -> bool { !self.play_buffer.is_empty() }
pub fn drain(&mut self) { self.drain = true; }
pub fn available_rec_frames(&self) -> usize { self.rec_buffer.readable_count() }
pub fn power(&mut self, state: bool) {
self.llio.audio_on(state).expect("couldn't set audio power state");
@ -241,15 +253,11 @@ impl Codec {
}
}
pub fn is_on(&self) -> bool {
self.powered_on
}
pub fn is_init(&self) -> bool {
self.initialized
}
pub fn is_live(&self) -> bool {
self.live
}
pub fn is_on(&self) -> bool { self.powered_on }
pub fn is_init(&self) -> bool { self.initialized }
pub fn is_live(&self) -> bool { self.live }
pub fn set_speaker_gain_db(&mut self, gain_db: f32) {
self.i2c.i2c_mutex_acquire();
@ -262,9 +270,7 @@ impl Codec {
let code = analog_volume_db_to_code(gain_db);
self.w(0, &[1]); // select page 1
self.w(32, &[0b1_0_00011_0]); // class D amp powered on
self.w(38, &[
0b1_000_0000 | code,
]);
self.w(38, &[0b1_000_0000 | code]);
}
self.i2c.i2c_mutex_release();
}
@ -282,14 +288,19 @@ impl Codec {
let code_right = analog_volume_db_to_code(gain_db_right);
self.w(0, &[1]); // select page 1
self.w(31, &[0b1_1_00011_0]); // headphones powered up
self.w(36, &[
0b1_000_0000 | code_left, // HPL
0b1_000_0000 | code_right, // HPR
]);
self.w(
36,
&[
0b1_000_0000 | code_left, // HPL
0b1_000_0000 | code_right, // HPR
],
);
}
self.i2c.i2c_mutex_release();
}
/// Convenience wrapper for I2C transactions. Multiple I2C ops that have to be execute atomically must be manually guarded with a i2c_mutex_[acquire/release]
/// Convenience wrapper for I2C transactions. Multiple I2C ops that have to be execute atomically must be
/// manually guarded with a i2c_mutex_[acquire/release]
fn w(&mut self, adr: u8, data: &[u8]) -> bool {
// log::info!("writing to 0x{:x}, {:x?}", adr, data);
match self.i2c.i2c_write(TLV320AIC3100_I2C_ADR, adr, data) {
@ -298,23 +309,35 @@ impl Codec {
match status {
I2cStatus::ResponseWriteOk => true,
I2cStatus::ResponseBusy => false,
_ => {log::error!("try_send_i2c unhandled response: {:?}", status); false},
_ => {
log::error!("try_send_i2c unhandled response: {:?}", status);
false
}
}
}
_ => {log::error!("try_send_i2c unhandled error"); false}
_ => {
log::error!("try_send_i2c unhandled error");
false
}
}
}
/// Convenience wrapper for I2C transactions. Multiple I2C ops that have to be execute atomically must be manually guarded with a i2c_mutex_[acquire/release]
fn r(&mut self, adr: u8, data: &mut[u8]) -> bool {
/// Convenience wrapper for I2C transactions. Multiple I2C ops that have to be execute atomically must be
/// manually guarded with a i2c_mutex_[acquire/release]
fn r(&mut self, adr: u8, data: &mut [u8]) -> bool {
match self.i2c.i2c_read(TLV320AIC3100_I2C_ADR, adr, data) {
Ok(status) => {
match status {
I2cStatus::ResponseReadOk => true,
I2cStatus::ResponseBusy => false,
_ => {log::error!("try_send_i2c unhandled response: {:?}", status); false},
Ok(status) => match status {
I2cStatus::ResponseReadOk => true,
I2cStatus::ResponseBusy => false,
_ => {
log::error!("try_send_i2c unhandled response: {:?}", status);
false
}
},
_ => {
log::error!("try_send_i2c unhandled error");
false
}
_ => {log::error!("try_send_i2c unhandled error"); false}
}
}
@ -369,41 +392,50 @@ impl Codec {
/// oversampling rate (OSR) = 128
/// local divider = 12
/// 8_000 * 128 * 12 = 12_288_000 Hz
///
fn audio_clocks(&mut self) {
self.i2c.i2c_mutex_acquire();
self.w(0, &[0]); // select page 0
self.w(1, &[1]); // software reset
self.w(0, &[0]); // select page 0
self.w(1, &[1]); // software reset
self.ticktimer.sleep_ms(2).unwrap(); // reset happens in 1 ms; +1 ms due to timing jitter uncertainty
self.w(0, &[0]); // select page 0
self.w(0, &[0]); // select page 0
// select PLL_CLKIN = MCLK; CODEC_CLKIN = PLL_CLK
self.w(4, &[0b0000_0011]);
// fs = 8kHz
// PLL_CLKIN = 12MHz
// PLLP = 1, PLLR = 1, PLLJ = 7, PLLD = 1680, NDAC = *12*, MDAC = 7, DOSR = 128, MADC = 2 , NADC = *42*
// ^^ from page 68 of datasheet, fs=48kHz/12MHz clkin line, with *bold* items multiplied by 6 to get to 8kHz
self.w(5, &[
0b1001_0001, // P, R = 1, 1 and pll powered up
7, // PLLJ = 7
((1680 >> 8) & 0xFF) as u8, // D MSB of 1680
(1680 & 0xFF) as u8, // D LSB of 1680
]);
// PLLP = 1, PLLR = 1, PLLJ = 7, PLLD = 1680, NDAC = *12*, MDAC = 7, DOSR = 128, MADC = 2 , NADC =
// *42* ^^ from page 68 of datasheet, fs=48kHz/12MHz clkin line, with *bold* items multiplied
// by 6 to get to 8kHz
self.w(
5,
&[
0b1001_0001, // P, R = 1, 1 and pll powered up
7, // PLLJ = 7
((1680 >> 8) & 0xFF) as u8, // D MSB of 1680
(1680 & 0xFF) as u8, // D LSB of 1680
],
);
self.w(11, &[
0x80 | 12, // NADC = 12 (set to 2 for 48kHz)
0x80 | 7, // MDAC = 7
0, // DOSR = MSB of 128
128, // DOSR = LSB of 128
]);
self.w(
11,
&[
0x80 | 12, // NADC = 12 (set to 2 for 48kHz)
0x80 | 7, // MDAC = 7
0, // DOSR = MSB of 128
128, // DOSR = LSB of 128
],
);
self.w(18, &[
0x80 | 42, // NADC = 42 (set to 7 for 48kHz)
0x80 | 2, // MADC = 2
128, // AOSR = 128
]);
self.w(
18,
&[
0x80 | 42, // NADC = 42 (set to 7 for 48kHz)
0x80 | 2, // MADC = 2
128, // AOSR = 128
],
);
self.i2c.i2c_mutex_release();
}
@ -417,12 +449,16 @@ impl Codec {
// 32 bits/word * 2 channels * 8000 samples/s = 512_000 = BCLK
// pick off of DAC_MOD_CLK = 1.024MHz
self.w(27, &[
0b00_00_1_1_0_1, // I2S standard, 16 bits per sample, BCLK output, WCLK output, DOUT is Hi-Z when unused
0b0, // no offset on left justification
0b0000_0_1_01, // BDIV_CLKIN = DAC_MOD_CLK, BCLK active even when powered down
0b1000_0010 // BCLK_N_VAL = 2, N divider is powered up
]);
self.w(
27,
&[
0b00_00_1_1_0_1, /* I2S standard, 16 bits per sample, BCLK output, WCLK output, DOUT is
* Hi-Z when unused */
0b0, // no offset on left justification
0b0000_0_1_01, // BDIV_CLKIN = DAC_MOD_CLK, BCLK active even when powered down
0b1000_0010, // BCLK_N_VAL = 2, N divider is powered up
],
);
// "word width" (WCLK) timing is implied based on the DAC fs computed
// at the end of the clock tree, and WCLK simply toggles every other sample, so there is no
@ -431,14 +467,14 @@ impl Codec {
// turn on headset detection
self.w(0, &[0]); // select page 0
// detection enabled, 64ms glitch reject, 8ms button glitch reject
self.w(67, &[0b1_00_010_01] );
self.w(67, &[0b1_00_010_01]);
// use auto volume control -- DO WE WANT THIS???
//self.w(116, &[0b1_1_01_0_001] );
self.i2c.i2c_mutex_release();
}
pub fn audio_loopback(&mut self, do_loop:bool) {
pub fn audio_loopback(&mut self, do_loop: bool) {
self.i2c.i2c_mutex_acquire();
self.w(0, &[1]); // select page 1
@ -473,20 +509,27 @@ impl Codec {
//self.w(35, &[0b01_0_1_01_1_0]);
// internal volume control
self.w(36, &[
0b1_001_1110, // HPL channel control on, -15dB
0b1_001_1110, // HPR channel control on, -15dB
0b1_000_1100, // SPK control on, -6dB
]);
self.w(
36,
&[
0b1_001_1110, // HPL channel control on, -15dB
0b1_001_1110, // HPR channel control on, -15dB
0b1_000_1100, // SPK control on, -6dB
],
);
// driver PGA control
self.w(40, &[
0b0_0011_111, // HPL driver PGA = 3dB, not muted, all gains applied
0b0_0011_111, // HPR driver PGA = 3dB, not muted, all gains applied
0b000_01_1_0_1, // SPK gain = 12 dB, driver not muted, all gains applied
]);
self.w(
40,
&[
0b0_0011_111, // HPL driver PGA = 3dB, not muted, all gains applied
0b0_0011_111, // HPR driver PGA = 3dB, not muted, all gains applied
0b000_01_1_0_1, // SPK gain = 12 dB, driver not muted, all gains applied
],
);
// HP driver control -- 16us short circuit debounce, best DAC performance, HPL/HPR as headphone drivers
// HP driver control -- 16us short circuit debounce, best DAC performance, HPL/HPR as headphone
// drivers
self.w(44, &[0b010_11_0_0_0]);
// MICBIAS control -- micbias always on, set to 2.5V
@ -520,15 +563,18 @@ impl Codec {
// ADC digital volume control coarse adjust
self.w(83, &[0b0]); // +0.0 dB
self.w(86, &[
0b1_011_0000, // AGC enabled, target level = -12dB
0b00_10101_0, // hysteresis 1dB, noise threshold = -((value-1)*2 + 30): 21 => -70dB
100, // max gain = code/2 dB
0b_00010_000, // attack time = 0b_acode_mul = (acode*32*mul)/Fs
0b_01101_000, // decay time = 0b_dcode_mul = (dcode*32*mul)/Fs
0x01, // noise debounce time = code*4 / fs
0x01, // signal debounce time = code*4 / fs
]);
self.w(
86,
&[
0b1_011_0000, // AGC enabled, target level = -12dB
0b00_10101_0, // hysteresis 1dB, noise threshold = -((value-1)*2 + 30): 21 => -70dB
100, // max gain = code/2 dB
0b_00010_000, // attack time = 0b_acode_mul = (acode*32*mul)/Fs
0b_01101_000, // decay time = 0b_dcode_mul = (dcode*32*mul)/Fs
0x01, // noise debounce time = code*4 / fs
0x01, // signal debounce time = code*4 / fs
],
);
self.i2c.i2c_mutex_release();
}
@ -539,8 +585,10 @@ impl Codec {
self.csr.wfo(utra::audio::TX_CTL_RESET, 1);
*/
let volatile_audio = self.fifo.as_mut_ptr() as *mut u32;
for _ in 0..FIFO_DEPTH*2 {
unsafe { (volatile_audio).write(ZERO_PCM as u32 | (ZERO_PCM as u32) << 16); } // prefill TX fifo with zero's
for _ in 0..FIFO_DEPTH * 2 {
unsafe {
(volatile_audio).write(ZERO_PCM as u32 | (ZERO_PCM as u32) << 16);
} // prefill TX fifo with zero's
}
// enable interrupts on the RX_READY
@ -561,8 +609,13 @@ impl Codec {
self.csr.wfo(utra::audio::RX_CTL_ENABLE, 0);
self.csr.wfo(utra::audio::TX_CTL_ENABLE, 0);
log::info!("playback stopped. frames dropped: p{} r{} / errors: tx{} rx{}",
self.play_frames_dropped, self.rec_frames_dropped, self.tx_stat_errors, self.rx_stat_errors);
log::info!(
"playback stopped. frames dropped: p{} r{} / errors: tx{} rx{}",
self.play_frames_dropped,
self.rec_frames_dropped,
self.tx_stat_errors,
self.rx_stat_errors
);
self.play_frames_dropped = 0;
self.rec_frames_dropped = 0;
self.tx_stat_errors = 0;
@ -577,21 +630,37 @@ impl Codec {
}
/// this is a testing-only function which does a double-buffered audio loopback
pub fn audio_loopback_poll(&mut self, buf_a: &mut [u32; FIFO_DEPTH], buf_b: &mut [u32; FIFO_DEPTH], toggle: bool) -> bool {
pub fn audio_loopback_poll(
&mut self,
buf_a: &mut [u32; FIFO_DEPTH],
buf_b: &mut [u32; FIFO_DEPTH],
toggle: bool,
) -> bool {
let volatile_audio = self.fifo.as_mut_ptr() as *mut u32;
if (self.csr.rf(utra::audio::TX_STAT_FREE) == 1) && (self.csr.rf(utra::audio::RX_STAT_DATAREADY) == 1) {
if (self.csr.rf(utra::audio::TX_STAT_FREE) == 1) && (self.csr.rf(utra::audio::RX_STAT_DATAREADY) == 1)
{
for i in 0..FIFO_DEPTH {
if toggle {
unsafe{ buf_a[i] = *volatile_audio; }
unsafe { *volatile_audio = buf_b[i]; }
unsafe {
buf_a[i] = *volatile_audio;
}
unsafe {
*volatile_audio = buf_b[i];
}
} else {
unsafe{ buf_b[i] = *volatile_audio; }
unsafe { *volatile_audio = buf_a[i]; }
unsafe {
buf_b[i] = *volatile_audio;
}
unsafe {
*volatile_audio = buf_a[i];
}
}
}
// wait for the done flags to clear; with an interrupt-driven system, this isn't necessary
while (self.csr.rf(utra::audio::TX_STAT_FREE) == 1) & (self.csr.rf(utra::audio::RX_STAT_DATAREADY) == 1) {}
while (self.csr.rf(utra::audio::TX_STAT_FREE) == 1)
& (self.csr.rf(utra::audio::RX_STAT_DATAREADY) == 1)
{}
// indicate we had an audio event
true
} else {

View file

@ -1,10 +1,10 @@
#![cfg_attr(target_os = "none", no_std)]
pub mod api;
use xous::{CID, send_message, Message};
use num_traits::{ToPrimitive, FromPrimitive};
use xous_ipc::Buffer;
pub use api::*;
use num_traits::{FromPrimitive, ToPrimitive};
use xous::{send_message, Message, CID};
use xous_ipc::Buffer;
/// This is a keyword reserved for the "arg4" slot of a scalar callback, where args are numbered 1-4.
pub const AUDIO_CB_ROUTING_ID: usize = 0;
@ -16,48 +16,49 @@ pub struct Codec {
impl Codec {
pub fn new(xns: &xous_names::XousNames) -> Result<Self, xous::Error> {
REFCOUNT.fetch_add(1, Ordering::Relaxed);
let conn = xns.request_connection_blocking(api::SERVER_NAME_CODEC).expect("Can't connect to Codec server");
Ok(Codec {
conn,
frame_sid: None,
})
let conn =
xns.request_connection_blocking(api::SERVER_NAME_CODEC).expect("Can't connect to Codec server");
Ok(Codec { conn, frame_sid: None })
}
pub fn hook_frame_callback(&mut self, id: u32, cid: CID) -> Result<(), xous::Error> {
if self.frame_sid.is_none() {
let sid = xous::create_server().unwrap();
self.frame_sid = Some(sid);
let sid_tuple = sid.to_u32();
xous::create_thread_4(frame_cb_server, sid_tuple.0 as usize, sid_tuple.1 as usize, sid_tuple.2 as usize, sid_tuple.3 as usize).unwrap();
let hookdata = ScalarHook {
sid: sid_tuple,
id,
cid,
};
xous::create_thread_4(
frame_cb_server,
sid_tuple.0 as usize,
sid_tuple.1 as usize,
sid_tuple.2 as usize,
sid_tuple.3 as usize,
)
.unwrap();
let hookdata = ScalarHook { sid: sid_tuple, id, cid };
let buf = Buffer::into_buf(hookdata).or(Err(xous::Error::InternalError))?;
buf.lend(self.conn, Opcode::AudioStreamSubscribe.to_u32().unwrap()).map(|_|())
buf.lend(self.conn, Opcode::AudioStreamSubscribe.to_u32().unwrap()).map(|_| ())
} else {
Err(xous::Error::MemoryInUse) // can't hook it twice
}
}
pub fn setup_8k_stream(&mut self) -> Result<(), xous::Error> {
send_message(self.conn,
Message::new_scalar(Opcode::Setup8kStereo.to_usize().unwrap(), 0, 0, 0, 0)
).map(|_| ())
send_message(self.conn, Message::new_scalar(Opcode::Setup8kStereo.to_usize().unwrap(), 0, 0, 0, 0))
.map(|_| ())
}
pub fn power_off(&mut self) -> Result<(), xous::Error> {
send_message(self.conn,
Message::new_scalar(Opcode::PowerOff.to_usize().unwrap(), 0, 0, 0, 0)
).map(|_| ())
send_message(self.conn, Message::new_scalar(Opcode::PowerOff.to_usize().unwrap(), 0, 0, 0, 0))
.map(|_| ())
}
pub fn free_frames(&mut self) -> Result<(usize, usize), xous::Error> {
let response = send_message(self.conn,
Message::new_blocking_scalar(Opcode::FreeFrames.to_usize().unwrap(), 0, 0, 0, 0))?;
let response = send_message(
self.conn,
Message::new_blocking_scalar(Opcode::FreeFrames.to_usize().unwrap(), 0, 0, 0, 0),
)?;
if let xous::Result::Scalar2(play_free, rec_avail) = response {
Ok(
(play_free, rec_avail)
)
Ok((play_free, rec_avail))
} else {
log::error!("unexpected return value: {:#?}", response);
Err(xous::Error::InternalError)
@ -73,64 +74,64 @@ impl Codec {
}
pub fn resume(&mut self) -> Result<(), xous::Error> {
send_message(self.conn,
Message::new_scalar(Opcode::ResumeStream.to_usize().unwrap(), 0, 0, 0, 0)
).map(|_| ())
send_message(self.conn, Message::new_scalar(Opcode::ResumeStream.to_usize().unwrap(), 0, 0, 0, 0))
.map(|_| ())
}
pub fn pause(&mut self) -> Result<(), xous::Error> {
send_message(self.conn,
Message::new_scalar(Opcode::PauseStream.to_usize().unwrap(), 0, 0, 0, 0)
).map(|_| ())
send_message(self.conn, Message::new_scalar(Opcode::PauseStream.to_usize().unwrap(), 0, 0, 0, 0))
.map(|_| ())
}
pub fn abort(&mut self) -> Result<(), xous::Error> {
send_message(self.conn,
Message::new_scalar(Opcode::AbortStream.to_usize().unwrap(), 0, 0, 0, 0)
).map(|_| ())
send_message(self.conn, Message::new_scalar(Opcode::AbortStream.to_usize().unwrap(), 0, 0, 0, 0))
.map(|_| ())
}
/// gain goes from 0dB down to -80dB
pub fn set_speaker_volume(&self, op: VolumeOps, gain: Option<f32>) -> Result<(), xous::Error> {
let code = if let Some(g) = gain {
if g > 0.0 {
0 as usize
} else {
(-g * 10.0) as usize
}
if g > 0.0 { 0 as usize } else { (-g * 10.0) as usize }
} else {
800 // -80.0 dB => mute
};
send_message(self.conn,
Message::new_scalar(Opcode::SetSpeakerVolume.to_usize().unwrap(),
send_message(
self.conn,
Message::new_scalar(
Opcode::SetSpeakerVolume.to_usize().unwrap(),
op.to_usize().unwrap(),
code, // gain as -dB * 10 as usize
0,
0
)
).map(|_| ())
0,
),
)
.map(|_| ())
}
/// gain goes from 0dB down to -80dB
pub fn set_headphone_volume(&self, op: VolumeOps, gain: Option<f32>) -> Result<(), xous::Error> {
let code = if let Some(g) = gain {
if g > 0.0 {
0 as usize
} else {
(-g * 10.0) as usize
}
if g > 0.0 { 0 as usize } else { (-g * 10.0) as usize }
} else {
800 // -80.0 dB => mute
};
send_message(self.conn,
Message::new_scalar(Opcode::SetHeadphoneVolume.to_usize().unwrap(),
send_message(
self.conn,
Message::new_scalar(
Opcode::SetHeadphoneVolume.to_usize().unwrap(),
op.to_usize().unwrap(),
code, // gain as -dB * 10 as usize
0,
0
)
).map(|_| ())
0,
),
)
.map(|_| ())
}
pub fn is_running(&self) -> Result<bool, xous::Error> {
match send_message(self.conn,
Message::new_blocking_scalar(Opcode::IsLive.to_usize().unwrap(), 0, 0, 0, 0)
match send_message(
self.conn,
Message::new_blocking_scalar(Opcode::IsLive.to_usize().unwrap(), 0, 0, 0, 0),
) {
Ok(xous::Result::Scalar1(is_live)) => {
if is_live != 0 {
@ -139,12 +140,14 @@ impl Codec {
Ok(false)
}
}
_ => Err(xous::Error::InternalError)
_ => Err(xous::Error::InternalError),
}
}
pub fn poll_headphone_state(&self) -> Result<HeadphoneState, xous::Error> {
match send_message(self.conn,
Message::new_blocking_scalar(Opcode::GetHeadphoneCode.to_usize().unwrap(), 0, 0, 0, 0)
match send_message(
self.conn,
Message::new_blocking_scalar(Opcode::GetHeadphoneCode.to_usize().unwrap(), 0, 0, 0, 0),
) {
Ok(xous::Result::Scalar1(code)) => {
let retcode: Option<HeadphoneState> = FromPrimitive::from_usize(code);
@ -153,7 +156,7 @@ impl Codec {
None => Err(xous::Error::InternalError),
}
}
_ => Err(xous::Error::InternalError)
_ => Err(xous::Error::InternalError),
}
}
}
@ -162,14 +165,18 @@ use core::sync::atomic::{AtomicU32, Ordering};
static REFCOUNT: AtomicU32 = AtomicU32::new(0);
impl Drop for Codec {
fn drop(&mut self) {
// de-allocate myself. It's unsafe because we are responsible to make sure nobody else is using the connection.
// de-allocate myself. It's unsafe because we are responsible to make sure nobody else is using the
// connection.
if REFCOUNT.fetch_sub(1, Ordering::Relaxed) == 1 {
unsafe{xous::disconnect(self.conn).unwrap();}
unsafe {
xous::disconnect(self.conn).unwrap();
}
}
}
}
/// handles callback messages that indicate an audio frame has been used up, in the library user's process space.
/// handles callback messages that indicate an audio frame has been used up, in the library user's process
/// space.
fn frame_cb_server(sid0: usize, sid1: usize, sid2: usize, sid3: usize) {
let sid = xous::SID::from_u32(sid0 as u32, sid1 as u32, sid2 as u32, sid3 as u32);
loop {
@ -177,9 +184,11 @@ fn frame_cb_server(sid0: usize, sid1: usize, sid2: usize, sid3: usize) {
match FromPrimitive::from_usize(msg.body.id()) {
Some(EventCallback::Event) => xous::msg_scalar_unpack!(msg, cid, id, free_play, avail_rec, {
// directly pass the scalar message onto the CID with the ID memorized in the original hook
send_message(cid as u32,
Message::new_scalar(id, free_play, avail_rec, 0, AUDIO_CB_ROUTING_ID)
).unwrap();
send_message(
cid as u32,
Message::new_scalar(id, free_play, avail_rec, 0, AUDIO_CB_ROUTING_ID),
)
.unwrap();
}),
Some(EventCallback::Drop) => {
break; // this exits the loop and kills the thread

View file

@ -3,15 +3,12 @@
mod api;
mod backend;
use backend::Codec;
use num_traits::{ToPrimitive, FromPrimitive};
use xous_ipc::Buffer;
use xous::{CID, msg_scalar_unpack};
use log::info;
use api::*;
use backend::Codec;
use log::info;
use num_traits::{FromPrimitive, ToPrimitive};
use xous::{msg_scalar_unpack, CID};
use xous_ipc::Buffer;
#[derive(Copy, Clone, Debug)]
struct ScalarCallback {
@ -20,14 +17,9 @@ struct ScalarCallback {
cb_to_client_id: u32,
}
fn main () -> ! {
fn main() -> ! {
let stack_size = 256 * 1024;
std::thread::Builder::new()
.stack_size(stack_size)
.spawn(wrapped_main)
.unwrap()
.join()
.unwrap()
std::thread::Builder::new().stack_size(stack_size).spawn(wrapped_main).unwrap().join().unwrap()
}
fn wrapped_main() -> ! {
@ -48,7 +40,13 @@ fn wrapped_main() -> ! {
// register a suspend/resume listener
let sr_cid = xous::connect(codec_sid).expect("couldn't create suspend callback connection");
let mut susres = susres::Susres::new(Some(susres::SuspendOrder::Normal), &xns, api::Opcode::SuspendResume as u32, sr_cid).expect("couldn't create suspend/resume object");
let mut susres = susres::Susres::new(
Some(susres::SuspendOrder::Normal),
&xns,
api::Opcode::SuspendResume as u32,
sr_cid,
)
.expect("couldn't create suspend/resume object");
/*
let trng = trng::Trng::new(&xns).unwrap();
let mut noise: [u32; codec::FIFO_DEPTH] = [0; codec::FIFO_DEPTH];
@ -107,11 +105,7 @@ fn wrapped_main() -> ! {
}
}),
Some(api::Opcode::IsLive) => xous::msg_blocking_scalar_unpack!(msg, _, _, _, _, {
let ret = if codec.is_live() {
1
} else {
0
};
let ret = if codec.is_live() { 1 } else { 0 };
xous::return_scalar(msg.sender, ret).expect("couldn't return if codec is live");
}),
Some(api::Opcode::FreeFrames) => xous::msg_blocking_scalar_unpack!(msg, _, _, _, _, {
@ -120,7 +114,8 @@ fn wrapped_main() -> ! {
xous::return_scalar2(msg.sender, play_free, rec_avail).expect("couldn't return FreeFrames");
}),
Some(api::Opcode::SwapFrames) => {
let mut buffer = unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) };
let mut buffer =
unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) };
let mut framering = buffer.to_original::<codec::api::FrameRing, _>().unwrap();
loop {
@ -163,7 +158,7 @@ fn wrapped_main() -> ! {
}
buffer.replace(framering).unwrap();
},
}
Some(api::Opcode::AudioStreamSubscribe) => {
let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
let hookdata = buffer.to_original::<ScalarHook, _>().unwrap();
@ -179,25 +174,25 @@ fn wrapped_main() -> ! {
match FromPrimitive::from_usize(op) {
Some(VolumeOps::Set) => {
speaker_analog_gain_db = -(gain_code as f32) / 10.0;
},
}
Some(VolumeOps::Mute) => {
speaker_analog_gain_db = -80.0;
},
}
Some(VolumeOps::RestoreDefault) => {
speaker_analog_gain_db = -6.0;
},
}
Some(VolumeOps::UpOne) => {
speaker_analog_gain_db += 3.0;
if speaker_analog_gain_db >= 0.0 {
speaker_analog_gain_db = 0.0;
}
},
}
Some(VolumeOps::DownOne) => {
speaker_analog_gain_db -= 3.0;
if speaker_analog_gain_db <= -80.0 {
speaker_analog_gain_db = -80.0;
}
},
}
_ => log::error!("got speaker volume primitive that we don't recognize, ignoring!"),
};
codec.set_speaker_gain_db(speaker_analog_gain_db);
@ -206,25 +201,25 @@ fn wrapped_main() -> ! {
match FromPrimitive::from_usize(op) {
Some(VolumeOps::Set) => {
headphone_analog_gain_db = -(gain_code as f32) / 10.0;
},
}
Some(VolumeOps::Mute) => {
headphone_analog_gain_db = -80.0;
},
}
Some(VolumeOps::RestoreDefault) => {
headphone_analog_gain_db = -6.0;
},
}
Some(VolumeOps::UpOne) => {
headphone_analog_gain_db += 3.0;
if headphone_analog_gain_db >= 0.0 {
headphone_analog_gain_db = 0.0;
}
},
}
Some(VolumeOps::DownOne) => {
headphone_analog_gain_db -= 3.0;
if headphone_analog_gain_db <= -80.0 {
headphone_analog_gain_db = -80.0;
}
},
}
_ => log::error!("got speaker volume primitive that we don't recognize, ignoring!"),
};
codec.set_headphone_gain_db(headphone_analog_gain_db, headphone_analog_gain_db);
@ -236,7 +231,8 @@ fn wrapped_main() -> ! {
log::warn!("Headphone detection polled, but detection is not enabled in hardware!");
}
log::debug!("headset code: 0x{:x}", hp_code);
let code = if hp_code == 0xff { // kind of a hack, we could also check codec power state
let code = if hp_code == 0xff {
// kind of a hack, we could also check codec power state
HeadphoneState::CodecOff
} else {
match (hp_code >> 5) & 0x3 {
@ -254,7 +250,7 @@ fn wrapped_main() -> ! {
}),
None => {
log::error!("couldn't convert opcode");
break
break;
}
}
}
@ -267,7 +263,6 @@ fn wrapped_main() -> ! {
xous::terminate_process(0)
}
fn do_hook(hookdata: ScalarHook, cb_conns: &mut [Option<ScalarCallback>; 32]) {
let (s0, s1, s2, s3) = hookdata.sid;
let sid = xous::SID::from_u32(s0, s1, s2, s3);
@ -292,10 +287,14 @@ fn do_hook(hookdata: ScalarHook, cb_conns: &mut [Option<ScalarCallback>; 32]) {
fn unhook(cb_conns: &mut [Option<ScalarCallback>; 32]) {
for entry in cb_conns.iter_mut() {
if let Some(scb) = entry {
xous::send_message(scb.server_to_cb_cid,
xous::Message::new_blocking_scalar(EventCallback::Drop.to_usize().unwrap(), 0, 0, 0, 0)
).unwrap();
unsafe{xous::disconnect(scb.server_to_cb_cid).unwrap();}
xous::send_message(
scb.server_to_cb_cid,
xous::Message::new_blocking_scalar(EventCallback::Drop.to_usize().unwrap(), 0, 0, 0, 0),
)
.unwrap();
unsafe {
xous::disconnect(scb.server_to_cb_cid).unwrap();
}
}
*entry = None;
}
@ -303,11 +302,19 @@ fn unhook(cb_conns: &mut [Option<ScalarCallback>; 32]) {
fn send_event(cb_conns: &[Option<ScalarCallback>; 32], free_play: usize, avail_rec: usize) {
for entry in cb_conns.iter() {
if let Some(scb) = entry {
// note that the "which" argument is only used for GPIO events, to indicate which pin had the event
xous::send_message(scb.server_to_cb_cid,
xous::Message::new_scalar(EventCallback::Event.to_usize().unwrap(),
scb.cb_to_client_cid as usize, scb.cb_to_client_id as usize, free_play, avail_rec)
).unwrap();
// note that the "which" argument is only used for GPIO events, to indicate which pin had the
// event
xous::send_message(
scb.server_to_cb_cid,
xous::Message::new_scalar(
EventCallback::Event.to_usize().unwrap(),
scb.cb_to_client_cid as usize,
scb.cb_to_client_id as usize,
free_play,
avail_rec,
),
)
.unwrap();
};
}
}