Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

3930 linhas
107KB

  1. #include "Audio.h"
  2. #include "arm_math.h"
  3. static arm_cfft_radix4_instance_q15 fft_inst;
  4. void AudioAnalyzeFFT256::init(void)
  5. {
  6. // TODO: replace this with static const version
  7. arm_cfft_radix4_init_q15(&fft_inst, 256, 0, 1);
  8. //for (int i=0; i<2048; i++) {
  9. //buffer[i] = i * 3;
  10. //}
  11. //__disable_irq();
  12. //ARM_DEMCR |= ARM_DEMCR_TRCENA;
  13. //ARM_DWT_CTRL |= ARM_DWT_CTRL_CYCCNTENA;
  14. //uint32_t n = ARM_DWT_CYCCNT;
  15. //arm_cfft_radix2_q15(&fft_inst, buffer);
  16. //n = ARM_DWT_CYCCNT - n;
  17. //__enable_irq();
  18. //cycles = n;
  19. //arm_cmplx_mag_q15(buffer, buffer, 512);
  20. // each audio block is 278525 cycles @ 96 MHz
  21. // 256 point fft2 takes 65408 cycles
  22. // 256 point fft4 takes 49108 cycles
  23. // 128 point cmag takes 10999 cycles
  24. // 1024 point fft2 takes 125948 cycles
  25. // 1024 point fft4 takes 125840 cycles
  26. // 512 point cmag takes 43764 cycles
  27. //state = 0;
  28. //outputflag = false;
  29. }
  30. static void copy_to_fft_buffer(void *destination, const void *source)
  31. {
  32. const int16_t *src = (const int16_t *)source;
  33. int16_t *dst = (int16_t *)destination;
  34. // TODO: optimize this
  35. for (int i=0; i < AUDIO_BLOCK_SAMPLES; i++) {
  36. *dst++ = *src++; // real
  37. *dst++ = 0; // imaginary
  38. }
  39. }
  40. // computes limit((val >> rshift), 2**bits)
  41. static inline int32_t signed_saturate_rshift(int32_t val, int bits, int rshift) __attribute__((always_inline));
  42. static inline int32_t signed_saturate_rshift(int32_t val, int bits, int rshift)
  43. {
  44. int32_t out;
  45. asm volatile("ssat %0, %1, %2, asr %3" : "=r" (out) : "I" (bits), "r" (val), "I" (rshift));
  46. return out;
  47. }
  48. static void apply_window_to_fft_buffer(void *buffer, const void *window)
  49. {
  50. int16_t *buf = (int16_t *)buffer;
  51. const int16_t *win = (int16_t *)window;;
  52. for (int i=0; i < 256; i++) {
  53. int32_t val = *buf * *win++;
  54. //*buf = signed_saturate_rshift(val, 16, 15);
  55. *buf = val >> 15;
  56. buf += 2;
  57. }
  58. }
  59. void AudioAnalyzeFFT256::update(void)
  60. {
  61. audio_block_t *block;
  62. block = receiveReadOnly();
  63. if (!block) return;
  64. if (!prevblock) {
  65. prevblock = block;
  66. return;
  67. }
  68. copy_to_fft_buffer(buffer, prevblock->data);
  69. copy_to_fft_buffer(buffer+256, block->data);
  70. //window = AudioWindowBlackmanNuttall256;
  71. //window = NULL;
  72. if (window) apply_window_to_fft_buffer(buffer, window);
  73. arm_cfft_radix4_q15(&fft_inst, buffer);
  74. // TODO: is this averaging correct? G. Heinzel's paper says we're
  75. // supposed to average the magnitude squared, then do the square
  76. // root at the end after dividing by naverage.
  77. arm_cmplx_mag_q15(buffer, buffer, 128);
  78. if (count == 0) {
  79. for (int i=0; i < 128; i++) {
  80. output[i] = buffer[i];
  81. }
  82. } else {
  83. for (int i=0; i < 128; i++) {
  84. output[i] += buffer[i];
  85. }
  86. }
  87. if (++count == naverage) {
  88. count = 0;
  89. for (int i=0; i < 128; i++) {
  90. output[i] /= naverage;
  91. }
  92. outputflag = true;
  93. }
  94. release(prevblock);
  95. prevblock = block;
  96. #if 0
  97. block = receiveReadOnly();
  98. if (state == 0) {
  99. //Serial.print("0");
  100. if (block == NULL) return;
  101. copy_to_fft_buffer(buffer, block->data);
  102. state = 1;
  103. } else if (state == 1) {
  104. //Serial.print("1");
  105. if (block == NULL) return;
  106. copy_to_fft_buffer(buffer+256, block->data);
  107. arm_cfft_radix4_q15(&fft_inst, buffer);
  108. state = 2;
  109. } else {
  110. //Serial.print("2");
  111. arm_cmplx_mag_q15(buffer, output, 128);
  112. outputflag = true;
  113. if (block == NULL) return;
  114. copy_to_fft_buffer(buffer, block->data);
  115. state = 1;
  116. }
  117. release(block);
  118. #endif
  119. }
  120. /******************************************************************/
  121. // PAH - add ramp-up and ramp-down at the beginning and end of the wave
  122. //
  123. void AudioSynthWaveform::set_ramp_length(uint16_t r_length)
  124. {
  125. if(r_length < 0) {
  126. ramp_length = 0;
  127. return;
  128. }
  129. // Don't set the ramp length longer than about 4 milliseconds
  130. if(r_length > 44*4) {
  131. ramp_length = 44*4;
  132. return;
  133. }
  134. ramp_length = r_length;
  135. }
  136. void AudioSynthWaveform::update(void)
  137. {
  138. audio_block_t *block;
  139. uint32_t i, ph, inc, index, scale;
  140. int32_t val1, val2, val3;
  141. //Serial.println("AudioSynthWaveform::update");
  142. if (((magnitude > 0) || ramp_down) && (block = allocate()) != NULL) {
  143. ph = phase;
  144. inc = phase_increment;
  145. for (i=0; i < AUDIO_BLOCK_SAMPLES; i++) {
  146. index = ph >> 24;
  147. val1 = wavetable[index];
  148. val2 = wavetable[index+1];
  149. scale = (ph >> 8) & 0xFFFF;
  150. val2 *= scale;
  151. val1 *= 0xFFFF - scale;
  152. val3 = (val1 + val2) >> 16;
  153. // The value of ramp_up is always initialized to RAMP_LENGTH and then is
  154. // decremented each time through here until it reaches zero.
  155. // The value of ramp_up is used to generate a Q15 fraction which varies
  156. // from [0 - 1), and multiplies this by the current sample
  157. if(ramp_up) {
  158. // ramp up to the new magnitude
  159. // ramp_mag is the Q15 representation of the fraction
  160. // Since ramp_up can't be zero, this cannot generate +1
  161. ramp_mag = ((ramp_length-ramp_up)<<15)/ramp_length;
  162. ramp_up--;
  163. block->data[i] = (val3 * ((ramp_mag * magnitude)>>15)) >> 15;
  164. } else if(ramp_down) {
  165. // ramp down to zero from the last magnitude
  166. // The value of ramp_down is always initialized to RAMP_LENGTH and then is
  167. // decremented each time through here until it reaches zero.
  168. // The value of ramp_down is used to generate a Q15 fraction which varies
  169. // from (1 - 0], and multiplies this by the current sample
  170. // avoid RAMP_LENGTH/RAMP_LENGTH because Q15 format
  171. // cannot represent +1
  172. ramp_mag = ((ramp_down - 1)<<15)/ramp_length;
  173. ramp_down--;
  174. block->data[i] = (val3 * ((ramp_mag * last_magnitude)>>15)) >> 15;
  175. } else {
  176. block->data[i] = (val3 * magnitude) >> 15;
  177. }
  178. //Serial.print(block->data[i]);
  179. //Serial.print(", ");
  180. //if ((i % 12) == 11) Serial.println();
  181. ph += inc;
  182. }
  183. //Serial.println();
  184. phase = ph;
  185. transmit(block);
  186. release(block);
  187. } else {
  188. // is this numerical overflow ok?
  189. phase += phase_increment * AUDIO_BLOCK_SAMPLES;
  190. }
  191. }
  192. #if 0
  193. void AudioSineWaveMod::frequency(float f)
  194. {
  195. if (f > AUDIO_SAMPLE_RATE_EXACT / 2 || f < 0.0) return;
  196. phase_increment = (f / AUDIO_SAMPLE_RATE_EXACT) * 4294967296.0f;
  197. }
  198. void AudioSineWaveMod::update(void)
  199. {
  200. audio_block_t *block, *modinput;
  201. uint32_t i, ph, inc, index, scale;
  202. int32_t val1, val2;
  203. //Serial.println("AudioSineWave::update");
  204. modinput = receiveReadOnly();
  205. ph = phase;
  206. inc = phase_increment;
  207. block = allocate();
  208. if (!block) {
  209. // unable to allocate memory, so we'll send nothing
  210. if (modinput) {
  211. // but if we got modulation data, update the phase
  212. for (i=0; i < AUDIO_BLOCK_SAMPLES; i++) {
  213. ph += inc + modinput->data[i] * modulation_factor;
  214. }
  215. release(modinput);
  216. } else {
  217. ph += phase_increment * AUDIO_BLOCK_SAMPLES;
  218. }
  219. phase = ph;
  220. return;
  221. }
  222. if (modinput) {
  223. for (i=0; i < AUDIO_BLOCK_SAMPLES; i++) {
  224. index = ph >> 24;
  225. val1 = sine_table[index];
  226. val2 = sine_table[index+1];
  227. scale = (ph >> 8) & 0xFFFF;
  228. val2 *= scale;
  229. val1 *= 0xFFFF - scale;
  230. block->data[i] = (val1 + val2) >> 16;
  231. //Serial.print(block->data[i]);
  232. //Serial.print(", ");
  233. //if ((i % 12) == 11) Serial.println();
  234. ph += inc + modinput->data[i] * modulation_factor;
  235. }
  236. release(modinput);
  237. } else {
  238. ph = phase;
  239. inc = phase_increment;
  240. for (i=0; i < AUDIO_BLOCK_SAMPLES; i++) {
  241. index = ph >> 24;
  242. val1 = sine_table[index];
  243. val2 = sine_table[index+1];
  244. scale = (ph >> 8) & 0xFFFF;
  245. val2 *= scale;
  246. val1 *= 0xFFFF - scale;
  247. block->data[i] = (val1 + val2) >> 16;
  248. //Serial.print(block->data[i]);
  249. //Serial.print(", ");
  250. //if ((i % 12) == 11) Serial.println();
  251. ph += inc;
  252. }
  253. }
  254. phase = ph;
  255. transmit(block);
  256. release(block);
  257. }
  258. #endif
  259. /******************************************************************/
  260. void AudioPrint::update(void)
  261. {
  262. audio_block_t *block;
  263. uint32_t i;
  264. Serial.println("AudioPrint::update");
  265. Serial.println(name);
  266. block = receiveReadOnly();
  267. if (block) {
  268. for (i=0; i < AUDIO_BLOCK_SAMPLES; i++) {
  269. Serial.print(block->data[i]);
  270. Serial.print(", ");
  271. if ((i % 12) == 11) Serial.println();
  272. }
  273. Serial.println();
  274. release(block);
  275. }
  276. }
  277. /******************************************************************/
  278. audio_block_t * AudioOutputPWM::block_1st = NULL;
  279. audio_block_t * AudioOutputPWM::block_2nd = NULL;
  280. uint32_t AudioOutputPWM::block_offset = 0;
  281. bool AudioOutputPWM::update_responsibility = false;
  282. uint8_t AudioOutputPWM::interrupt_count = 0;
  283. DMAMEM uint32_t pwm_dma_buffer[AUDIO_BLOCK_SAMPLES*2];
  284. void AudioOutputPWM::begin(void)
  285. {
  286. //Serial.println("AudioPwmOutput constructor");
  287. block_1st = NULL;
  288. FTM1_SC = 0;
  289. FTM1_CNT = 0;
  290. FTM1_MOD = 543;
  291. FTM1_C0SC = 0x69; // send DMA request on match
  292. FTM1_C1SC = 0x28;
  293. FTM1_SC = FTM_SC_CLKS(1) | FTM_SC_PS(0);
  294. CORE_PIN3_CONFIG = PORT_PCR_MUX(3) | PORT_PCR_DSE | PORT_PCR_SRE;
  295. CORE_PIN4_CONFIG = PORT_PCR_MUX(3) | PORT_PCR_DSE | PORT_PCR_SRE;
  296. FTM1_C0V = 120; // range 120 to 375
  297. FTM1_C1V = 0; // range 0 to 255
  298. for (int i=0; i<256; i+=2) {
  299. pwm_dma_buffer[i] = 120; // zero must not be used
  300. pwm_dma_buffer[i+1] = 0;
  301. }
  302. SIM_SCGC7 |= SIM_SCGC7_DMA;
  303. SIM_SCGC6 |= SIM_SCGC6_DMAMUX;
  304. DMA_CR = 0;
  305. DMA_TCD3_SADDR = pwm_dma_buffer;
  306. DMA_TCD3_SOFF = 4;
  307. DMA_TCD3_ATTR = DMA_TCD_ATTR_SSIZE(2) | DMA_TCD_ATTR_DSIZE(2) | DMA_TCD_ATTR_DMOD(4);
  308. DMA_TCD3_NBYTES_MLNO = 8;
  309. DMA_TCD3_SLAST = -sizeof(pwm_dma_buffer);
  310. DMA_TCD3_DADDR = &FTM1_C0V;
  311. DMA_TCD3_DOFF = 8;
  312. DMA_TCD3_CITER_ELINKNO = sizeof(pwm_dma_buffer) / 8;
  313. DMA_TCD3_DLASTSGA = 0;
  314. DMA_TCD3_BITER_ELINKNO = sizeof(pwm_dma_buffer) / 8;
  315. DMA_TCD3_CSR = DMA_TCD_CSR_INTHALF | DMA_TCD_CSR_INTMAJOR;
  316. DMAMUX0_CHCFG3 = DMAMUX_DISABLE;
  317. DMAMUX0_CHCFG3 = DMAMUX_SOURCE_FTM1_CH0 | DMAMUX_ENABLE;
  318. DMA_SERQ = 3;
  319. update_responsibility = update_setup();
  320. NVIC_ENABLE_IRQ(IRQ_DMA_CH3);
  321. }
  322. void AudioOutputPWM::update(void)
  323. {
  324. audio_block_t *block;
  325. block = receiveReadOnly();
  326. if (!block) return;
  327. __disable_irq();
  328. if (block_1st == NULL) {
  329. block_1st = block;
  330. block_offset = 0;
  331. __enable_irq();
  332. } else if (block_2nd == NULL) {
  333. block_2nd = block;
  334. __enable_irq();
  335. } else {
  336. audio_block_t *tmp = block_1st;
  337. block_1st = block_2nd;
  338. block_2nd = block;
  339. block_offset = 0;
  340. __enable_irq();
  341. release(tmp);
  342. }
  343. }
  344. void dma_ch3_isr(void)
  345. {
  346. int16_t *src;
  347. uint32_t *dest;
  348. audio_block_t *block;
  349. uint32_t saddr, offset;
  350. saddr = (uint32_t)DMA_TCD3_SADDR;
  351. DMA_CINT = 3;
  352. if (saddr < (uint32_t)pwm_dma_buffer + sizeof(pwm_dma_buffer) / 2) {
  353. // DMA is transmitting the first half of the buffer
  354. // so we must fill the second half
  355. dest = &pwm_dma_buffer[AUDIO_BLOCK_SAMPLES];
  356. } else {
  357. // DMA is transmitting the second half of the buffer
  358. // so we must fill the first half
  359. dest = pwm_dma_buffer;
  360. }
  361. block = AudioOutputPWM::block_1st;
  362. offset = AudioOutputPWM::block_offset;
  363. if (block) {
  364. src = &block->data[offset];
  365. for (int i=0; i < AUDIO_BLOCK_SAMPLES/4; i++) {
  366. uint16_t sample = *src++ + 0x8000;
  367. uint32_t msb = ((sample >> 8) & 255) + 120;
  368. uint32_t lsb = sample & 255;
  369. *dest++ = msb;
  370. *dest++ = lsb;
  371. *dest++ = msb;
  372. *dest++ = lsb;
  373. }
  374. offset += AUDIO_BLOCK_SAMPLES/4;
  375. if (offset < AUDIO_BLOCK_SAMPLES) {
  376. AudioOutputPWM::block_offset = offset;
  377. } else {
  378. AudioOutputPWM::block_offset = 0;
  379. AudioStream::release(block);
  380. AudioOutputPWM::block_1st = AudioOutputPWM::block_2nd;
  381. AudioOutputPWM::block_2nd = NULL;
  382. }
  383. } else {
  384. // fill with silence when no data available
  385. for (int i=0; i < AUDIO_BLOCK_SAMPLES/4; i++) {
  386. *dest++ = 248;
  387. *dest++ = 0;
  388. *dest++ = 248;
  389. *dest++ = 0;
  390. }
  391. }
  392. if (AudioOutputPWM::update_responsibility) {
  393. if (++AudioOutputPWM::interrupt_count >= 4) {
  394. AudioOutputPWM::interrupt_count = 0;
  395. AudioStream::update_all();
  396. }
  397. }
  398. }
  399. // DMA target is: (registers require 32 bit writes)
  400. // 40039010 Channel 0 Value (FTM1_C0V)
  401. // 40039018 Channel 1 Value (FTM1_C1V)
  402. // TCD:
  403. // source address = buffer address
  404. // source offset = 4 bytes
  405. // attr = no src mod, ssize = 32 bit, dest mod = 16 bytes (4), dsize = 32 bit
  406. // minor loop byte count = 8
  407. // source last adjust = -sizeof(buffer)
  408. // dest address = FTM1_C0V
  409. // dest address offset = 8
  410. // citer = sizeof(buffer) / 8 (no minor loop linking)
  411. // dest last adjust = 0 (dest modulo keeps it ready for more)
  412. // control:
  413. // throttling = 0
  414. // major link to same channel
  415. // done = 0
  416. // active = 0
  417. // majorlink = 1
  418. // scatter/gather = 0
  419. // disable request = 0
  420. // inthalf = 1
  421. // intmajor = 1
  422. // start = 0
  423. // biter = sizeof(buffer) / 8 (no minor loop linking)
  424. /******************************************************************/
  425. // MCLK needs to be 48e6 / 1088 * 256 = 11.29411765 MHz -> 44.117647 kHz sample rate
  426. // Possible to create using fractional divider for all USB-compatible Kinetis:
  427. // MCLK = 16e6 * 12 / 17
  428. // MCLK = 24e6 * 8 / 17
  429. // MCLK = 48e6 * 4 / 17
  430. // MCLK = 72e6 * 8 / 51
  431. // MCLK = 96e6 * 2 / 17
  432. // MCLK = 120e6 * 8 / 85
  433. // TODO: instigate using I2S0_MCR to select the crystal directly instead of the system
  434. // clock, which has audio band jitter from the PLL
  435. audio_block_t * AudioOutputI2S::block_left_1st = NULL;
  436. audio_block_t * AudioOutputI2S::block_right_1st = NULL;
  437. audio_block_t * AudioOutputI2S::block_left_2nd = NULL;
  438. audio_block_t * AudioOutputI2S::block_right_2nd = NULL;
  439. uint16_t AudioOutputI2S::block_left_offset = 0;
  440. uint16_t AudioOutputI2S::block_right_offset = 0;
  441. bool AudioOutputI2S::update_responsibility = false;
  442. DMAMEM static uint32_t i2s_tx_buffer[AUDIO_BLOCK_SAMPLES];
  443. void AudioOutputI2S::begin(void)
  444. {
  445. //pinMode(2, OUTPUT);
  446. block_left_1st = NULL;
  447. block_right_1st = NULL;
  448. config_i2s();
  449. CORE_PIN22_CONFIG = PORT_PCR_MUX(6); // pin 22, PTC1, I2S0_TXD0
  450. DMA_CR = 0;
  451. DMA_TCD0_SADDR = i2s_tx_buffer;
  452. DMA_TCD0_SOFF = 2;
  453. DMA_TCD0_ATTR = DMA_TCD_ATTR_SSIZE(1) | DMA_TCD_ATTR_DSIZE(1);
  454. DMA_TCD0_NBYTES_MLNO = 2;
  455. DMA_TCD0_SLAST = -sizeof(i2s_tx_buffer);
  456. DMA_TCD0_DADDR = &I2S0_TDR0;
  457. DMA_TCD0_DOFF = 0;
  458. DMA_TCD0_CITER_ELINKNO = sizeof(i2s_tx_buffer) / 2;
  459. DMA_TCD0_DLASTSGA = 0;
  460. DMA_TCD0_BITER_ELINKNO = sizeof(i2s_tx_buffer) / 2;
  461. DMA_TCD0_CSR = DMA_TCD_CSR_INTHALF | DMA_TCD_CSR_INTMAJOR;
  462. DMAMUX0_CHCFG0 = DMAMUX_DISABLE;
  463. DMAMUX0_CHCFG0 = DMAMUX_SOURCE_I2S0_TX | DMAMUX_ENABLE;
  464. update_responsibility = update_setup();
  465. DMA_SERQ = 0;
  466. I2S0_TCSR |= I2S_TCSR_TE | I2S_TCSR_BCE | I2S_TCSR_FRDE | I2S_TCSR_FR;
  467. NVIC_ENABLE_IRQ(IRQ_DMA_CH0);
  468. }
  469. void dma_ch0_isr(void)
  470. {
  471. const int16_t *src, *end;
  472. int16_t *dest;
  473. audio_block_t *block;
  474. uint32_t saddr, offset;
  475. saddr = (uint32_t)DMA_TCD0_SADDR;
  476. DMA_CINT = 0;
  477. if (saddr < (uint32_t)i2s_tx_buffer + sizeof(i2s_tx_buffer) / 2) {
  478. // DMA is transmitting the first half of the buffer
  479. // so we must fill the second half
  480. dest = (int16_t *)&i2s_tx_buffer[AUDIO_BLOCK_SAMPLES/2];
  481. end = (int16_t *)&i2s_tx_buffer[AUDIO_BLOCK_SAMPLES];
  482. if (AudioOutputI2S::update_responsibility) AudioStream::update_all();
  483. } else {
  484. // DMA is transmitting the second half of the buffer
  485. // so we must fill the first half
  486. dest = (int16_t *)i2s_tx_buffer;
  487. end = (int16_t *)&i2s_tx_buffer[AUDIO_BLOCK_SAMPLES/2];
  488. }
  489. // TODO: these copy routines could be merged and optimized, maybe in assembly?
  490. block = AudioOutputI2S::block_left_1st;
  491. if (block) {
  492. offset = AudioOutputI2S::block_left_offset;
  493. src = &block->data[offset];
  494. do {
  495. *dest = *src++;
  496. dest += 2;
  497. } while (dest < end);
  498. offset += AUDIO_BLOCK_SAMPLES/2;
  499. if (offset < AUDIO_BLOCK_SAMPLES) {
  500. AudioOutputI2S::block_left_offset = offset;
  501. } else {
  502. AudioOutputI2S::block_left_offset = 0;
  503. AudioStream::release(block);
  504. AudioOutputI2S::block_left_1st = AudioOutputI2S::block_left_2nd;
  505. AudioOutputI2S::block_left_2nd = NULL;
  506. }
  507. } else {
  508. do {
  509. *dest = 0;
  510. dest += 2;
  511. } while (dest < end);
  512. }
  513. dest -= AUDIO_BLOCK_SAMPLES - 1;
  514. block = AudioOutputI2S::block_right_1st;
  515. if (block) {
  516. offset = AudioOutputI2S::block_right_offset;
  517. src = &block->data[offset];
  518. do {
  519. *dest = *src++;
  520. dest += 2;
  521. } while (dest < end);
  522. offset += AUDIO_BLOCK_SAMPLES/2;
  523. if (offset < AUDIO_BLOCK_SAMPLES) {
  524. AudioOutputI2S::block_right_offset = offset;
  525. } else {
  526. AudioOutputI2S::block_right_offset = 0;
  527. AudioStream::release(block);
  528. AudioOutputI2S::block_right_1st = AudioOutputI2S::block_right_2nd;
  529. AudioOutputI2S::block_right_2nd = NULL;
  530. }
  531. } else {
  532. do {
  533. *dest = 0;
  534. dest += 2;
  535. } while (dest < end);
  536. }
  537. }
  538. void AudioOutputI2S::update(void)
  539. {
  540. // null audio device: discard all incoming data
  541. //if (!active) return;
  542. //audio_block_t *block = receiveReadOnly();
  543. //if (block) release(block);
  544. audio_block_t *block;
  545. block = receiveReadOnly(0); // input 0 = left channel
  546. if (block) {
  547. __disable_irq();
  548. if (block_left_1st == NULL) {
  549. block_left_1st = block;
  550. block_left_offset = 0;
  551. __enable_irq();
  552. } else if (block_left_2nd == NULL) {
  553. block_left_2nd = block;
  554. __enable_irq();
  555. } else {
  556. audio_block_t *tmp = block_left_1st;
  557. block_left_1st = block_left_2nd;
  558. block_left_2nd = block;
  559. block_left_offset = 0;
  560. __enable_irq();
  561. release(tmp);
  562. }
  563. }
  564. block = receiveReadOnly(1); // input 1 = right channel
  565. if (block) {
  566. __disable_irq();
  567. if (block_right_1st == NULL) {
  568. block_right_1st = block;
  569. block_right_offset = 0;
  570. __enable_irq();
  571. } else if (block_right_2nd == NULL) {
  572. block_right_2nd = block;
  573. __enable_irq();
  574. } else {
  575. audio_block_t *tmp = block_right_1st;
  576. block_right_1st = block_right_2nd;
  577. block_right_2nd = block;
  578. block_right_offset = 0;
  579. __enable_irq();
  580. release(tmp);
  581. }
  582. }
  583. }
  584. void AudioOutputI2S::config_i2s(void)
  585. {
  586. SIM_SCGC6 |= SIM_SCGC6_I2S;
  587. SIM_SCGC7 |= SIM_SCGC7_DMA;
  588. SIM_SCGC6 |= SIM_SCGC6_DMAMUX;
  589. // if either transmitter or receiver is enabled, do nothing
  590. if (I2S0_TCSR & I2S_TCSR_TE) return;
  591. if (I2S0_RCSR & I2S_RCSR_RE) return;
  592. // enable MCLK output
  593. I2S0_MCR = I2S_MCR_MICS(3) | I2S_MCR_MOE;
  594. I2S0_MDR = I2S_MDR_FRACT(1) | I2S_MDR_DIVIDE(16);
  595. // configure transmitter
  596. I2S0_TMR = 0;
  597. I2S0_TCR1 = I2S_TCR1_TFW(1); // watermark at half fifo size
  598. I2S0_TCR2 = I2S_TCR2_SYNC(0) | I2S_TCR2_BCP | I2S_TCR2_MSEL(1)
  599. | I2S_TCR2_BCD | I2S_TCR2_DIV(3);
  600. I2S0_TCR3 = I2S_TCR3_TCE;
  601. I2S0_TCR4 = I2S_TCR4_FRSZ(1) | I2S_TCR4_SYWD(15) | I2S_TCR4_MF
  602. | I2S_TCR4_FSE | I2S_TCR4_FSP | I2S_TCR4_FSD;
  603. I2S0_TCR5 = I2S_TCR5_WNW(15) | I2S_TCR5_W0W(15) | I2S_TCR5_FBT(15);
  604. // configure receiver (sync'd to transmitter clocks)
  605. I2S0_RMR = 0;
  606. I2S0_RCR1 = I2S_RCR1_RFW(1);
  607. I2S0_RCR2 = I2S_RCR2_SYNC(1) | I2S_TCR2_BCP | I2S_RCR2_MSEL(1)
  608. | I2S_RCR2_BCD | I2S_RCR2_DIV(3);
  609. I2S0_RCR3 = I2S_RCR3_RCE;
  610. I2S0_RCR4 = I2S_RCR4_FRSZ(1) | I2S_RCR4_SYWD(15) | I2S_RCR4_MF
  611. | I2S_RCR4_FSE | I2S_RCR4_FSP | I2S_RCR4_FSD;
  612. I2S0_RCR5 = I2S_RCR5_WNW(15) | I2S_RCR5_W0W(15) | I2S_RCR5_FBT(15);
  613. // configure pin mux for 3 clock signals
  614. CORE_PIN23_CONFIG = PORT_PCR_MUX(6); // pin 23, PTC2, I2S0_TX_FS (LRCLK)
  615. CORE_PIN9_CONFIG = PORT_PCR_MUX(6); // pin 9, PTC3, I2S0_TX_BCLK
  616. CORE_PIN11_CONFIG = PORT_PCR_MUX(6); // pin 11, PTC6, I2S0_MCLK
  617. }
  618. /******************************************************************/
  619. void AudioOutputI2Sslave::begin(void)
  620. {
  621. //pinMode(2, OUTPUT);
  622. block_left_1st = NULL;
  623. block_right_1st = NULL;
  624. AudioOutputI2Sslave::config_i2s();
  625. CORE_PIN22_CONFIG = PORT_PCR_MUX(6); // pin 22, PTC1, I2S0_TXD0
  626. DMA_CR = 0;
  627. DMA_TCD0_SADDR = i2s_tx_buffer;
  628. DMA_TCD0_SOFF = 2;
  629. DMA_TCD0_ATTR = DMA_TCD_ATTR_SSIZE(1) | DMA_TCD_ATTR_DSIZE(1);
  630. DMA_TCD0_NBYTES_MLNO = 2;
  631. DMA_TCD0_SLAST = -sizeof(i2s_tx_buffer);
  632. DMA_TCD0_DADDR = &I2S0_TDR0;
  633. DMA_TCD0_DOFF = 0;
  634. DMA_TCD0_CITER_ELINKNO = sizeof(i2s_tx_buffer) / 2;
  635. DMA_TCD0_DLASTSGA = 0;
  636. DMA_TCD0_BITER_ELINKNO = sizeof(i2s_tx_buffer) / 2;
  637. DMA_TCD0_CSR = DMA_TCD_CSR_INTHALF | DMA_TCD_CSR_INTMAJOR;
  638. DMAMUX0_CHCFG0 = DMAMUX_DISABLE;
  639. DMAMUX0_CHCFG0 = DMAMUX_SOURCE_I2S0_TX | DMAMUX_ENABLE;
  640. update_responsibility = update_setup();
  641. DMA_SERQ = 0;
  642. I2S0_TCSR |= I2S_TCSR_TE | I2S_TCSR_BCE | I2S_TCSR_FRDE | I2S_TCSR_FR;
  643. NVIC_ENABLE_IRQ(IRQ_DMA_CH0);
  644. }
  645. void AudioOutputI2Sslave::config_i2s(void)
  646. {
  647. SIM_SCGC6 |= SIM_SCGC6_I2S;
  648. SIM_SCGC7 |= SIM_SCGC7_DMA;
  649. SIM_SCGC6 |= SIM_SCGC6_DMAMUX;
  650. // if either transmitter or receiver is enabled, do nothing
  651. if (I2S0_TCSR & I2S_TCSR_TE) return;
  652. if (I2S0_RCSR & I2S_RCSR_RE) return;
  653. // Select input clock 0
  654. // Configure to input the bit-clock from pin, bypasses the MCLK divider
  655. I2S0_MCR = I2S_MCR_MICS(0);
  656. I2S0_MDR = 0;
  657. // configure transmitter
  658. I2S0_TMR = 0;
  659. I2S0_TCR1 = I2S_TCR1_TFW(1); // watermark at half fifo size
  660. I2S0_TCR2 = I2S_TCR2_SYNC(0) | I2S_TCR2_BCP;
  661. I2S0_TCR3 = I2S_TCR3_TCE;
  662. I2S0_TCR4 = I2S_TCR4_FRSZ(1) | I2S_TCR4_SYWD(15) | I2S_TCR4_MF
  663. | I2S_TCR4_FSE | I2S_TCR4_FSP;
  664. I2S0_TCR5 = I2S_TCR5_WNW(15) | I2S_TCR5_W0W(15) | I2S_TCR5_FBT(15);
  665. // configure receiver (sync'd to transmitter clocks)
  666. I2S0_RMR = 0;
  667. I2S0_RCR1 = I2S_RCR1_RFW(1);
  668. I2S0_RCR2 = I2S_RCR2_SYNC(1) | I2S_TCR2_BCP;
  669. I2S0_RCR3 = I2S_RCR3_RCE;
  670. I2S0_RCR4 = I2S_RCR4_FRSZ(1) | I2S_RCR4_SYWD(15) | I2S_RCR4_MF
  671. | I2S_RCR4_FSE | I2S_RCR4_FSP | I2S_RCR4_FSD;
  672. I2S0_RCR5 = I2S_RCR5_WNW(15) | I2S_RCR5_W0W(15) | I2S_RCR5_FBT(15);
  673. // configure pin mux for 3 clock signals
  674. CORE_PIN23_CONFIG = PORT_PCR_MUX(6); // pin 23, PTC2, I2S0_TX_FS (LRCLK)
  675. CORE_PIN9_CONFIG = PORT_PCR_MUX(6); // pin 9, PTC3, I2S0_TX_BCLK
  676. CORE_PIN11_CONFIG = PORT_PCR_MUX(6); // pin 11, PTC6, I2S0_MCLK
  677. }
  678. /******************************************************************/
  679. DMAMEM static uint32_t i2s_rx_buffer[AUDIO_BLOCK_SAMPLES];
  680. audio_block_t * AudioInputI2S::block_left = NULL;
  681. audio_block_t * AudioInputI2S::block_right = NULL;
  682. uint16_t AudioInputI2S::block_offset = 0;
  683. bool AudioInputI2S::update_responsibility = false;
  684. void AudioInputI2S::begin(void)
  685. {
  686. //block_left_1st = NULL;
  687. //block_right_1st = NULL;
  688. //pinMode(3, OUTPUT);
  689. //digitalWriteFast(3, HIGH);
  690. //delayMicroseconds(500);
  691. //digitalWriteFast(3, LOW);
  692. AudioOutputI2S::config_i2s();
  693. CORE_PIN13_CONFIG = PORT_PCR_MUX(4); // pin 13, PTC5, I2S0_RXD0
  694. DMA_CR = 0;
  695. DMA_TCD1_SADDR = &I2S0_RDR0;
  696. DMA_TCD1_SOFF = 0;
  697. DMA_TCD1_ATTR = DMA_TCD_ATTR_SSIZE(1) | DMA_TCD_ATTR_DSIZE(1);
  698. DMA_TCD1_NBYTES_MLNO = 2;
  699. DMA_TCD1_SLAST = 0;
  700. DMA_TCD1_DADDR = i2s_rx_buffer;
  701. DMA_TCD1_DOFF = 2;
  702. DMA_TCD1_CITER_ELINKNO = sizeof(i2s_rx_buffer) / 2;
  703. DMA_TCD1_DLASTSGA = -sizeof(i2s_rx_buffer);
  704. DMA_TCD1_BITER_ELINKNO = sizeof(i2s_rx_buffer) / 2;
  705. DMA_TCD1_CSR = DMA_TCD_CSR_INTHALF | DMA_TCD_CSR_INTMAJOR;
  706. DMAMUX0_CHCFG1 = DMAMUX_DISABLE;
  707. DMAMUX0_CHCFG1 = DMAMUX_SOURCE_I2S0_RX | DMAMUX_ENABLE;
  708. update_responsibility = update_setup();
  709. DMA_SERQ = 1;
  710. // TODO: is I2S_RCSR_BCE appropriate if sync'd to transmitter clock?
  711. //I2S0_RCSR |= I2S_RCSR_RE | I2S_RCSR_BCE | I2S_RCSR_FRDE | I2S_RCSR_FR;
  712. I2S0_RCSR |= I2S_RCSR_RE | I2S_RCSR_FRDE | I2S_RCSR_FR;
  713. NVIC_ENABLE_IRQ(IRQ_DMA_CH1);
  714. }
  715. void dma_ch1_isr(void)
  716. {
  717. uint32_t daddr, offset;
  718. const int16_t *src, *end;
  719. int16_t *dest_left, *dest_right;
  720. audio_block_t *left, *right;
  721. //digitalWriteFast(3, HIGH);
  722. daddr = (uint32_t)DMA_TCD1_DADDR;
  723. DMA_CINT = 1;
  724. if (daddr < (uint32_t)i2s_rx_buffer + sizeof(i2s_rx_buffer) / 2) {
  725. // DMA is receiving to the first half of the buffer
  726. // need to remove data from the second half
  727. src = (int16_t *)&i2s_rx_buffer[AUDIO_BLOCK_SAMPLES/2];
  728. end = (int16_t *)&i2s_rx_buffer[AUDIO_BLOCK_SAMPLES];
  729. if (AudioInputI2S::update_responsibility) AudioStream::update_all();
  730. } else {
  731. // DMA is receiving to the second half of the buffer
  732. // need to remove data from the first half
  733. src = (int16_t *)&i2s_rx_buffer[0];
  734. end = (int16_t *)&i2s_rx_buffer[AUDIO_BLOCK_SAMPLES/2];
  735. }
  736. left = AudioInputI2S::block_left;
  737. right = AudioInputI2S::block_right;
  738. if (left != NULL && right != NULL) {
  739. offset = AudioInputI2S::block_offset;
  740. if (offset <= AUDIO_BLOCK_SAMPLES/2) {
  741. dest_left = &(left->data[offset]);
  742. dest_right = &(right->data[offset]);
  743. AudioInputI2S::block_offset = offset + AUDIO_BLOCK_SAMPLES/2;
  744. do {
  745. //n = *src++;
  746. //*dest_left++ = (int16_t)n;
  747. //*dest_right++ = (int16_t)(n >> 16);
  748. *dest_left++ = *src++;
  749. *dest_right++ = *src++;
  750. } while (src < end);
  751. }
  752. }
  753. //digitalWriteFast(3, LOW);
  754. }
  755. void AudioInputI2S::update(void)
  756. {
  757. audio_block_t *new_left=NULL, *new_right=NULL, *out_left=NULL, *out_right=NULL;
  758. // allocate 2 new blocks, but if one fails, allocate neither
  759. new_left = allocate();
  760. if (new_left != NULL) {
  761. new_right = allocate();
  762. if (new_right == NULL) {
  763. release(new_left);
  764. new_left = NULL;
  765. }
  766. }
  767. __disable_irq();
  768. if (block_offset >= AUDIO_BLOCK_SAMPLES) {
  769. // the DMA filled 2 blocks, so grab them and get the
  770. // 2 new blocks to the DMA, as quickly as possible
  771. out_left = block_left;
  772. block_left = new_left;
  773. out_right = block_right;
  774. block_right = new_right;
  775. block_offset = 0;
  776. __enable_irq();
  777. // then transmit the DMA's former blocks
  778. transmit(out_left, 0);
  779. release(out_left);
  780. transmit(out_right, 1);
  781. release(out_right);
  782. //Serial.print(".");
  783. } else if (new_left != NULL) {
  784. // the DMA didn't fill blocks, but we allocated blocks
  785. if (block_left == NULL) {
  786. // the DMA doesn't have any blocks to fill, so
  787. // give it the ones we just allocated
  788. block_left = new_left;
  789. block_right = new_right;
  790. block_offset = 0;
  791. __enable_irq();
  792. } else {
  793. // the DMA already has blocks, doesn't need these
  794. __enable_irq();
  795. release(new_left);
  796. release(new_right);
  797. }
  798. } else {
  799. // The DMA didn't fill blocks, and we could not allocate
  800. // memory... the system is likely starving for memory!
  801. // Sadly, there's nothing we can do.
  802. __enable_irq();
  803. }
  804. }
  805. /******************************************************************/
  806. void AudioInputI2Sslave::begin(void)
  807. {
  808. //block_left_1st = NULL;
  809. //block_right_1st = NULL;
  810. //pinMode(3, OUTPUT);
  811. //digitalWriteFast(3, HIGH);
  812. //delayMicroseconds(500);
  813. //digitalWriteFast(3, LOW);
  814. AudioOutputI2Sslave::config_i2s();
  815. CORE_PIN13_CONFIG = PORT_PCR_MUX(4); // pin 13, PTC5, I2S0_RXD0
  816. DMA_CR = 0;
  817. DMA_TCD1_SADDR = &I2S0_RDR0;
  818. DMA_TCD1_SOFF = 0;
  819. DMA_TCD1_ATTR = DMA_TCD_ATTR_SSIZE(1) | DMA_TCD_ATTR_DSIZE(1);
  820. DMA_TCD1_NBYTES_MLNO = 2;
  821. DMA_TCD1_SLAST = 0;
  822. DMA_TCD1_DADDR = i2s_rx_buffer;
  823. DMA_TCD1_DOFF = 2;
  824. DMA_TCD1_CITER_ELINKNO = sizeof(i2s_rx_buffer) / 2;
  825. DMA_TCD1_DLASTSGA = -sizeof(i2s_rx_buffer);
  826. DMA_TCD1_BITER_ELINKNO = sizeof(i2s_rx_buffer) / 2;
  827. DMA_TCD1_CSR = DMA_TCD_CSR_INTHALF | DMA_TCD_CSR_INTMAJOR;
  828. DMAMUX0_CHCFG1 = DMAMUX_DISABLE;
  829. DMAMUX0_CHCFG1 = DMAMUX_SOURCE_I2S0_RX | DMAMUX_ENABLE;
  830. update_responsibility = update_setup();
  831. DMA_SERQ = 1;
  832. // TODO: is I2S_RCSR_BCE appropriate if sync'd to transmitter clock?
  833. //I2S0_RCSR |= I2S_RCSR_RE | I2S_RCSR_BCE | I2S_RCSR_FRDE | I2S_RCSR_FR;
  834. I2S0_RCSR |= I2S_RCSR_RE | I2S_RCSR_FRDE | I2S_RCSR_FR;
  835. NVIC_ENABLE_IRQ(IRQ_DMA_CH1);
  836. }
  837. /******************************************************************/
  838. DMAMEM static uint16_t analog_rx_buffer[AUDIO_BLOCK_SAMPLES];
  839. audio_block_t * AudioInputAnalog::block_left = NULL;
  840. uint16_t AudioInputAnalog::block_offset = 0;
  841. bool AudioInputAnalog::update_responsibility = false;
  842. #define PDB_CONFIG (PDB_SC_TRGSEL(15) | PDB_SC_PDBEN | PDB_SC_CONT)
  843. #define PDB_PERIOD 1087 // 48e6 / 44100
  844. void AudioInputAnalog::begin(unsigned int pin)
  845. {
  846. uint32_t i, sum=0;
  847. // pin must be 0 to 13 (for A0 to A13)
  848. // or 14 to 23 for digital pin numbers A0-A9
  849. // or 34 to 37 corresponding to A10-A13
  850. if (pin > 23 && !(pin >= 34 && pin <= 37)) return;
  851. //pinMode(2, OUTPUT);
  852. //pinMode(3, OUTPUT);
  853. //digitalWriteFast(3, HIGH);
  854. //delayMicroseconds(500);
  855. //digitalWriteFast(3, LOW);
  856. // Configure the ADC and run at least one software-triggered
  857. // conversion. This completes the self calibration stuff and
  858. // leaves the ADC in a state that's mostly ready to use
  859. analogReadRes(16);
  860. analogReference(INTERNAL); // range 0 to 1.2 volts
  861. //analogReference(DEFAULT); // range 0 to 3.3 volts
  862. analogReadAveraging(8);
  863. // Actually, do many normal reads, to start with a nice DC level
  864. for (i=0; i < 1024; i++) {
  865. sum += analogRead(pin);
  866. }
  867. dc_average = sum >> 10;
  868. // testing only, enable adc interrupt
  869. //ADC0_SC1A |= ADC_SC1_AIEN;
  870. //while ((ADC0_SC1A & ADC_SC1_COCO) == 0) ; // wait
  871. //NVIC_ENABLE_IRQ(IRQ_ADC0);
  872. // set the programmable delay block to trigger the ADC at 44.1 kHz
  873. SIM_SCGC6 |= SIM_SCGC6_PDB;
  874. PDB0_MOD = PDB_PERIOD;
  875. PDB0_SC = PDB_CONFIG | PDB_SC_LDOK;
  876. PDB0_SC = PDB_CONFIG | PDB_SC_SWTRIG;
  877. PDB0_CH0C1 = 0x0101;
  878. // enable the ADC for hardware trigger and DMA
  879. ADC0_SC2 |= ADC_SC2_ADTRG | ADC_SC2_DMAEN;
  880. // set up a DMA channel to store the ADC data
  881. SIM_SCGC7 |= SIM_SCGC7_DMA;
  882. SIM_SCGC6 |= SIM_SCGC6_DMAMUX;
  883. DMA_CR = 0;
  884. DMA_TCD2_SADDR = &ADC0_RA;
  885. DMA_TCD2_SOFF = 0;
  886. DMA_TCD2_ATTR = DMA_TCD_ATTR_SSIZE(1) | DMA_TCD_ATTR_DSIZE(1);
  887. DMA_TCD2_NBYTES_MLNO = 2;
  888. DMA_TCD2_SLAST = 0;
  889. DMA_TCD2_DADDR = analog_rx_buffer;
  890. DMA_TCD2_DOFF = 2;
  891. DMA_TCD2_CITER_ELINKNO = sizeof(analog_rx_buffer) / 2;
  892. DMA_TCD2_DLASTSGA = -sizeof(analog_rx_buffer);
  893. DMA_TCD2_BITER_ELINKNO = sizeof(analog_rx_buffer) / 2;
  894. DMA_TCD2_CSR = DMA_TCD_CSR_INTHALF | DMA_TCD_CSR_INTMAJOR;
  895. DMAMUX0_CHCFG2 = DMAMUX_DISABLE;
  896. DMAMUX0_CHCFG2 = DMAMUX_SOURCE_ADC0 | DMAMUX_ENABLE;
  897. update_responsibility = update_setup();
  898. DMA_SERQ = 2;
  899. NVIC_ENABLE_IRQ(IRQ_DMA_CH2);
  900. }
  901. void dma_ch2_isr(void)
  902. {
  903. uint32_t daddr, offset;
  904. const uint16_t *src, *end;
  905. uint16_t *dest_left;
  906. audio_block_t *left;
  907. //digitalWriteFast(3, HIGH);
  908. daddr = (uint32_t)DMA_TCD2_DADDR;
  909. DMA_CINT = 2;
  910. if (daddr < (uint32_t)analog_rx_buffer + sizeof(analog_rx_buffer) / 2) {
  911. // DMA is receiving to the first half of the buffer
  912. // need to remove data from the second half
  913. src = (uint16_t *)&analog_rx_buffer[AUDIO_BLOCK_SAMPLES/2];
  914. end = (uint16_t *)&analog_rx_buffer[AUDIO_BLOCK_SAMPLES];
  915. if (AudioInputAnalog::update_responsibility) AudioStream::update_all();
  916. } else {
  917. // DMA is receiving to the second half of the buffer
  918. // need to remove data from the first half
  919. src = (uint16_t *)&analog_rx_buffer[0];
  920. end = (uint16_t *)&analog_rx_buffer[AUDIO_BLOCK_SAMPLES/2];
  921. }
  922. left = AudioInputAnalog::block_left;
  923. if (left != NULL) {
  924. offset = AudioInputAnalog::block_offset;
  925. if (offset > AUDIO_BLOCK_SAMPLES/2) offset = AUDIO_BLOCK_SAMPLES/2;
  926. //if (offset <= AUDIO_BLOCK_SAMPLES/2) {
  927. dest_left = (uint16_t *)&(left->data[offset]);
  928. AudioInputAnalog::block_offset = offset + AUDIO_BLOCK_SAMPLES/2;
  929. do {
  930. *dest_left++ = *src++;
  931. } while (src < end);
  932. //}
  933. }
  934. //digitalWriteFast(3, LOW);
  935. }
  936. #if 0
  937. void adc0_isr(void)
  938. {
  939. uint32_t tmp = ADC0_RA; // read ADC result to clear interrupt
  940. digitalWriteFast(3, HIGH);
  941. delayMicroseconds(1);
  942. digitalWriteFast(3, LOW);
  943. }
  944. #endif
  945. void AudioInputAnalog::update(void)
  946. {
  947. audio_block_t *new_left=NULL, *out_left=NULL;
  948. unsigned int dc, offset;
  949. int16_t s, *p, *end;
  950. // allocate new block (ok if NULL)
  951. new_left = allocate();
  952. __disable_irq();
  953. offset = block_offset;
  954. if (offset < AUDIO_BLOCK_SAMPLES) {
  955. // the DMA didn't fill a block
  956. if (new_left != NULL) {
  957. // but we allocated a block
  958. if (block_left == NULL) {
  959. // the DMA doesn't have any blocks to fill, so
  960. // give it the one we just allocated
  961. block_left = new_left;
  962. block_offset = 0;
  963. __enable_irq();
  964. //Serial.println("fail1");
  965. } else {
  966. // the DMA already has blocks, doesn't need this
  967. __enable_irq();
  968. release(new_left);
  969. //Serial.print("fail2, offset=");
  970. //Serial.println(offset);
  971. }
  972. } else {
  973. // The DMA didn't fill a block, and we could not allocate
  974. // memory... the system is likely starving for memory!
  975. // Sadly, there's nothing we can do.
  976. __enable_irq();
  977. //Serial.println("fail3");
  978. }
  979. return;
  980. }
  981. // the DMA filled a block, so grab it and get the
  982. // new block to the DMA, as quickly as possible
  983. out_left = block_left;
  984. block_left = new_left;
  985. block_offset = 0;
  986. __enable_irq();
  987. // find and subtract DC offset....
  988. // TODO: this may not be correct, needs testing with more types of signals
  989. dc = dc_average;
  990. p = out_left->data;
  991. end = p + AUDIO_BLOCK_SAMPLES;
  992. do {
  993. s = (uint16_t)(*p) - dc; // TODO: should be saturating subtract
  994. *p++ = s;
  995. dc += s >> 13; // approx 5.38 Hz high pass filter
  996. } while (p < end);
  997. dc_average = dc;
  998. // then transmit the AC data
  999. transmit(out_left);
  1000. release(out_left);
  1001. }
  1002. /******************************************************************/
  1003. // #define PDB_CONFIG (PDB_SC_TRGSEL(15) | PDB_SC_PDBEN | PDB_SC_CONT)
  1004. // #define PDB_PERIOD 1087 // 48e6 / 44100
  1005. #if defined(__MK20DX256__) && defined(DMA_TCD4_SADDR)
  1006. DMAMEM static uint16_t dac_buffer[AUDIO_BLOCK_SAMPLES*2];
  1007. audio_block_t * AudioOutputAnalog::block_left_1st = NULL;
  1008. audio_block_t * AudioOutputAnalog::block_left_2nd = NULL;
  1009. bool AudioOutputAnalog::update_responsibility = false;
  1010. void AudioOutputAnalog::begin(void)
  1011. {
  1012. SIM_SCGC2 |= SIM_SCGC2_DAC0;
  1013. DAC0_C0 = DAC_C0_DACEN | DAC_C0_DACRFS; // 3.3V VDDA is DACREF_2
  1014. // slowly ramp up to DC voltage, approx 1/4 second
  1015. for (int16_t i=0; i<128; i++) {
  1016. analogWrite(A14, i);
  1017. delay(2);
  1018. }
  1019. // set the programmable delay block to trigger DMA requests
  1020. SIM_SCGC6 |= SIM_SCGC6_PDB;
  1021. PDB0_IDLY = 1;
  1022. PDB0_MOD = PDB_PERIOD;
  1023. PDB0_SC = PDB_CONFIG | PDB_SC_LDOK;
  1024. PDB0_SC = PDB_CONFIG | PDB_SC_SWTRIG | PDB_SC_PDBIE | PDB_SC_DMAEN;
  1025. SIM_SCGC7 |= SIM_SCGC7_DMA;
  1026. SIM_SCGC6 |= SIM_SCGC6_DMAMUX;
  1027. DMA_CR = 0;
  1028. DMA_TCD4_SADDR = dac_buffer;
  1029. DMA_TCD4_SOFF = 2;
  1030. DMA_TCD4_ATTR = DMA_TCD_ATTR_SSIZE(1) | DMA_TCD_ATTR_DSIZE(1);
  1031. DMA_TCD4_NBYTES_MLNO = 2;
  1032. DMA_TCD4_SLAST = -sizeof(dac_buffer);
  1033. DMA_TCD4_DADDR = &DAC0_DAT0L;
  1034. DMA_TCD4_DOFF = 0;
  1035. DMA_TCD4_CITER_ELINKNO = sizeof(dac_buffer) / 2;
  1036. DMA_TCD4_DLASTSGA = 0;
  1037. DMA_TCD4_BITER_ELINKNO = sizeof(dac_buffer) / 2;
  1038. DMA_TCD4_CSR = DMA_TCD_CSR_INTHALF | DMA_TCD_CSR_INTMAJOR;
  1039. DMAMUX0_CHCFG4 = DMAMUX_DISABLE;
  1040. DMAMUX0_CHCFG4 = DMAMUX_SOURCE_PDB | DMAMUX_ENABLE;
  1041. update_responsibility = update_setup();
  1042. DMA_SERQ = 4;
  1043. NVIC_ENABLE_IRQ(IRQ_DMA_CH4);
  1044. }
  1045. void AudioOutputAnalog::analogReference(int ref)
  1046. {
  1047. // TODO: this should ramp gradually to the new DC level
  1048. if (ref == INTERNAL) {
  1049. DAC0_C0 &= ~DAC_C0_DACRFS; // 1.2V
  1050. } else {
  1051. DAC0_C0 |= DAC_C0_DACRFS; // 3.3V
  1052. }
  1053. }
  1054. void AudioOutputAnalog::update(void)
  1055. {
  1056. audio_block_t *block;
  1057. block = receiveReadOnly(0); // input 0
  1058. if (block) {
  1059. __disable_irq();
  1060. if (block_left_1st == NULL) {
  1061. block_left_1st = block;
  1062. __enable_irq();
  1063. } else if (block_left_2nd == NULL) {
  1064. block_left_2nd = block;
  1065. __enable_irq();
  1066. } else {
  1067. audio_block_t *tmp = block_left_1st;
  1068. block_left_1st = block_left_2nd;
  1069. block_left_2nd = block;
  1070. __enable_irq();
  1071. release(tmp);
  1072. }
  1073. }
  1074. }
  1075. // TODO: the DAC has much higher bandwidth than the datasheet says
  1076. // can we output a 2X oversampled output, for easier filtering?
  1077. void dma_ch4_isr(void)
  1078. {
  1079. const int16_t *src, *end;
  1080. int16_t *dest;
  1081. audio_block_t *block;
  1082. uint32_t saddr, offset;
  1083. saddr = (uint32_t)DMA_TCD4_SADDR;
  1084. DMA_CINT = 4;
  1085. if (saddr < (uint32_t)dac_buffer + sizeof(dac_buffer) / 2) {
  1086. // DMA is transmitting the first half of the buffer
  1087. // so we must fill the second half
  1088. dest = (int16_t *)&dac_buffer[AUDIO_BLOCK_SAMPLES];
  1089. end = (int16_t *)&dac_buffer[AUDIO_BLOCK_SAMPLES*2];
  1090. } else {
  1091. // DMA is transmitting the second half of the buffer
  1092. // so we must fill the first half
  1093. dest = (int16_t *)dac_buffer;
  1094. end = (int16_t *)&dac_buffer[AUDIO_BLOCK_SAMPLES];
  1095. }
  1096. block = AudioOutputAnalog::block_left_1st;
  1097. if (block) {
  1098. src = &block->data[offset];
  1099. do {
  1100. // TODO: this should probably dither
  1101. *dest++ = ((*src++) + 32767) >> 4;
  1102. } while (dest < end);
  1103. AudioStream::release(block);
  1104. AudioOutputAnalog::block_left_1st = AudioOutputAnalog::block_left_2nd;
  1105. AudioOutputAnalog::block_left_2nd = NULL;
  1106. } else {
  1107. do {
  1108. *dest++ = 2047;
  1109. } while (dest < end);
  1110. }
  1111. if (AudioOutputAnalog::update_responsibility) AudioStream::update_all();
  1112. }
  1113. #else
  1114. void AudioOutputAnalog::begin(void)
  1115. {
  1116. }
  1117. void AudioOutputAnalog::update(void)
  1118. {
  1119. audio_block_t *block;
  1120. block = receiveReadOnly(0); // input 0
  1121. if (block) release(block);
  1122. }
  1123. #endif // defined(__MK20DX256__) && defined(DMA_TCD4_SADDR)
  1124. /******************************************************************/
  1125. #define STATE_DIRECT_8BIT_MONO 0 // playing mono at native sample rate
  1126. #define STATE_DIRECT_8BIT_STEREO 1 // playing stereo at native sample rate
  1127. #define STATE_DIRECT_16BIT_MONO 2 // playing mono at native sample rate
  1128. #define STATE_DIRECT_16BIT_STEREO 3 // playing stereo at native sample rate
  1129. #define STATE_CONVERT_8BIT_MONO 4 // playing mono, converting sample rate
  1130. #define STATE_CONVERT_8BIT_STEREO 5 // playing stereo, converting sample rate
  1131. #define STATE_CONVERT_16BIT_MONO 6 // playing mono, converting sample rate
  1132. #define STATE_CONVERT_16BIT_STEREO 7 // playing stereo, converting sample rate
  1133. #define STATE_PARSE1 8 // looking for 20 byte ID header
  1134. #define STATE_PARSE2 9 // looking for 16 byte format header
  1135. #define STATE_PARSE3 10 // looking for 8 byte data header
  1136. #define STATE_PARSE4 11 // ignoring unknown chunk
  1137. #define STATE_STOP 12
  1138. void AudioPlaySDcardWAV::begin(void)
  1139. {
  1140. state = STATE_STOP;
  1141. state_play = STATE_STOP;
  1142. data_length = 0;
  1143. if (block_left) {
  1144. release(block_left);
  1145. block_left = NULL;
  1146. }
  1147. if (block_right) {
  1148. release(block_right);
  1149. block_right = NULL;
  1150. }
  1151. }
  1152. bool AudioPlaySDcardWAV::play(const char *filename)
  1153. {
  1154. stop();
  1155. wavfile = SD.open(filename);
  1156. if (!wavfile) return false;
  1157. buffer_remaining = 0;
  1158. state_play = STATE_STOP;
  1159. data_length = 0;
  1160. state = STATE_PARSE1;
  1161. return true;
  1162. }
  1163. void AudioPlaySDcardWAV::stop(void)
  1164. {
  1165. __disable_irq();
  1166. if (state != STATE_STOP) {
  1167. audio_block_t *b1 = block_left;
  1168. block_left = NULL;
  1169. audio_block_t *b2 = block_right;
  1170. block_right = NULL;
  1171. state = STATE_STOP;
  1172. __enable_irq();
  1173. if (b1) release(b1);
  1174. if (b2) release(b2);
  1175. wavfile.close();
  1176. } else {
  1177. __enable_irq();
  1178. }
  1179. }
  1180. bool AudioPlaySDcardWAV::start(void)
  1181. {
  1182. __disable_irq();
  1183. if (state == STATE_STOP) {
  1184. if (state_play == STATE_STOP) {
  1185. __enable_irq();
  1186. return false;
  1187. }
  1188. state = state_play;
  1189. }
  1190. __enable_irq();
  1191. return true;
  1192. }
  1193. void AudioPlaySDcardWAV::update(void)
  1194. {
  1195. // only update if we're playing
  1196. if (state == STATE_STOP) return;
  1197. // allocate the audio blocks to transmit
  1198. block_left = allocate();
  1199. if (block_left == NULL) return;
  1200. if (state < 8 && (state & 1) == 1) {
  1201. // if we're playing stereo, allocate another
  1202. // block for the right channel output
  1203. block_right = allocate();
  1204. if (block_right == NULL) {
  1205. release(block_left);
  1206. return;
  1207. }
  1208. } else {
  1209. // if we're playing mono or just parsing
  1210. // the WAV file header, no right-side block
  1211. block_right = NULL;
  1212. }
  1213. block_offset = 0;
  1214. //Serial.println("update");
  1215. // is there buffered data?
  1216. if (buffer_remaining > 0) {
  1217. // we have buffered data
  1218. if (consume()) return; // it was enough to transmit audio
  1219. }
  1220. // we only get to this point when buffer[512] is empty
  1221. if (state != STATE_STOP && wavfile.available()) {
  1222. // we can read more data from the file...
  1223. buffer_remaining = wavfile.read(buffer, 512);
  1224. if (consume()) {
  1225. // good, it resulted in audio transmit
  1226. return;
  1227. } else {
  1228. // not good, no audio was transmitted
  1229. buffer_remaining = 0;
  1230. if (block_left) {
  1231. release(block_left);
  1232. block_left = NULL;
  1233. }
  1234. if (block_right) {
  1235. release(block_right);
  1236. block_right = NULL;
  1237. }
  1238. // if we're still playing, well, there's going to
  1239. // be a gap in output, but we can't keep burning
  1240. // time trying to read more data. Hopefully things
  1241. // will go better next time?
  1242. if (state != STATE_STOP) return;
  1243. }
  1244. }
  1245. // end of file reached or other reason to stop
  1246. wavfile.close();
  1247. if (block_left) {
  1248. release(block_left);
  1249. block_left = NULL;
  1250. }
  1251. if (block_right) {
  1252. release(block_right);
  1253. block_right = NULL;
  1254. }
  1255. state_play = STATE_STOP;
  1256. state = STATE_STOP;
  1257. }
  1258. // https://ccrma.stanford.edu/courses/422/projects/WaveFormat/
  1259. // Consume already buffered data. Returns true if audio transmitted.
  1260. bool AudioPlaySDcardWAV::consume(void)
  1261. {
  1262. uint32_t len, size;
  1263. uint8_t lsb, msb;
  1264. const uint8_t *p;
  1265. size = buffer_remaining;
  1266. p = buffer + 512 - size;
  1267. start:
  1268. if (size == 0) return false;
  1269. //Serial.print("AudioPlaySDcardWAV write, size = ");
  1270. //Serial.print(size);
  1271. //Serial.print(", data_length = ");
  1272. //Serial.print(data_length);
  1273. //Serial.print(", state = ");
  1274. //Serial.println(state);
  1275. switch (state) {
  1276. // parse wav file header, is this really a .wav file?
  1277. case STATE_PARSE1:
  1278. len = 20 - data_length;
  1279. if (size < len) len = size;
  1280. memcpy((uint8_t *)header + data_length, p, len);
  1281. data_length += len;
  1282. if (data_length < 20) return false;
  1283. // parse the header...
  1284. if (header[0] == 0x46464952 && header[2] == 0x45564157
  1285. && header[3] == 0x20746D66 && header[4] == 16) {
  1286. //Serial.println("header ok");
  1287. state = STATE_PARSE2;
  1288. p += len;
  1289. size -= len;
  1290. data_length = 0;
  1291. goto start;
  1292. }
  1293. //Serial.println("unknown WAV header");
  1294. break;
  1295. // check & extract key audio parameters
  1296. case STATE_PARSE2:
  1297. len = 16 - data_length;
  1298. if (size < len) len = size;
  1299. memcpy((uint8_t *)header + data_length, p, len);
  1300. data_length += len;
  1301. if (data_length < 16) return false;
  1302. if (parse_format()) {
  1303. //Serial.println("audio format ok");
  1304. p += len;
  1305. size -= len;
  1306. data_length = 0;
  1307. state = STATE_PARSE3;
  1308. goto start;
  1309. }
  1310. //Serial.println("unknown audio format");
  1311. break;
  1312. // find the data chunk
  1313. case STATE_PARSE3:
  1314. len = 8 - data_length;
  1315. if (size < len) len = size;
  1316. memcpy((uint8_t *)header + data_length, p, len);
  1317. data_length += len;
  1318. if (data_length < 8) return false;
  1319. //Serial.print("chunk id = ");
  1320. //Serial.print(header[0], HEX);
  1321. //Serial.print(", length = ");
  1322. //Serial.println(header[1]);
  1323. p += len;
  1324. size -= len;
  1325. data_length = header[1];
  1326. if (header[0] == 0x61746164) {
  1327. //Serial.println("found data chunk");
  1328. // TODO: verify offset in file is an even number
  1329. // as required by WAV format. abort if odd. Code
  1330. // below will depend upon this and fail if not even.
  1331. leftover_bytes = 0;
  1332. state = state_play;
  1333. if (state & 1) {
  1334. // if we're going to start stereo
  1335. // better allocate another output block
  1336. block_right = allocate();
  1337. if (!block_right) return false;
  1338. }
  1339. } else {
  1340. state = STATE_PARSE4;
  1341. }
  1342. goto start;
  1343. // ignore any extra unknown chunks (title & artist info)
  1344. case STATE_PARSE4:
  1345. if (size < data_length) {
  1346. data_length -= size;
  1347. return false;
  1348. }
  1349. p += data_length;
  1350. size -= data_length;
  1351. data_length = 0;
  1352. state = STATE_PARSE3;
  1353. goto start;
  1354. // playing mono at native sample rate
  1355. case STATE_DIRECT_8BIT_MONO:
  1356. return false;
  1357. // playing stereo at native sample rate
  1358. case STATE_DIRECT_8BIT_STEREO:
  1359. return false;
  1360. // playing mono at native sample rate
  1361. case STATE_DIRECT_16BIT_MONO:
  1362. if (size > data_length) size = data_length;
  1363. data_length -= size;
  1364. while (1) {
  1365. lsb = *p++;
  1366. msb = *p++;
  1367. size -= 2;
  1368. block_left->data[block_offset++] = (msb << 8) | lsb;
  1369. if (block_offset >= AUDIO_BLOCK_SAMPLES) {
  1370. transmit(block_left, 0);
  1371. transmit(block_left, 1);
  1372. //Serial1.print('%');
  1373. //delayMicroseconds(90);
  1374. release(block_left);
  1375. block_left = NULL;
  1376. data_length += size;
  1377. buffer_remaining = size;
  1378. if (block_right) release(block_right);
  1379. return true;
  1380. }
  1381. if (size == 0) {
  1382. if (data_length == 0) break;
  1383. return false;
  1384. }
  1385. }
  1386. // end of file reached
  1387. if (block_offset > 0) {
  1388. // TODO: fill remainder of last block with zero and transmit
  1389. }
  1390. state = STATE_STOP;
  1391. return false;
  1392. // playing stereo at native sample rate
  1393. case STATE_DIRECT_16BIT_STEREO:
  1394. if (size > data_length) size = data_length;
  1395. data_length -= size;
  1396. if (leftover_bytes) {
  1397. block_left->data[block_offset] = header[0];
  1398. goto right16;
  1399. }
  1400. while (1) {
  1401. lsb = *p++;
  1402. msb = *p++;
  1403. size -= 2;
  1404. if (size == 0) {
  1405. if (data_length == 0) break;
  1406. header[0] = (msb << 8) | lsb;
  1407. leftover_bytes = 2;
  1408. return false;
  1409. }
  1410. block_left->data[block_offset] = (msb << 8) | lsb;
  1411. right16:
  1412. lsb = *p++;
  1413. msb = *p++;
  1414. size -= 2;
  1415. block_right->data[block_offset++] = (msb << 8) | lsb;
  1416. if (block_offset >= AUDIO_BLOCK_SAMPLES) {
  1417. transmit(block_left, 0);
  1418. release(block_left);
  1419. block_left = NULL;
  1420. transmit(block_right, 1);
  1421. release(block_right);
  1422. block_right = NULL;
  1423. data_length += size;
  1424. buffer_remaining = size;
  1425. return true;
  1426. }
  1427. if (size == 0) {
  1428. if (data_length == 0) break;
  1429. leftover_bytes = 0;
  1430. return false;
  1431. }
  1432. }
  1433. // end of file reached
  1434. if (block_offset > 0) {
  1435. // TODO: fill remainder of last block with zero and transmit
  1436. }
  1437. state = STATE_STOP;
  1438. return false;
  1439. // playing mono, converting sample rate
  1440. case STATE_CONVERT_8BIT_MONO :
  1441. return false;
  1442. // playing stereo, converting sample rate
  1443. case STATE_CONVERT_8BIT_STEREO:
  1444. return false;
  1445. // playing mono, converting sample rate
  1446. case STATE_CONVERT_16BIT_MONO:
  1447. return false;
  1448. // playing stereo, converting sample rate
  1449. case STATE_CONVERT_16BIT_STEREO:
  1450. return false;
  1451. // ignore any extra data after playing
  1452. // or anything following any error
  1453. case STATE_STOP:
  1454. return false;
  1455. // this is not supposed to happen!
  1456. //default:
  1457. //Serial.println("AudioPlaySDcardWAV, unknown state");
  1458. }
  1459. state_play = STATE_STOP;
  1460. state = STATE_STOP;
  1461. return false;
  1462. }
  1463. /*
  1464. 00000000 52494646 66EA6903 57415645 666D7420 RIFFf.i.WAVEfmt
  1465. 00000010 10000000 01000200 44AC0000 10B10200 ........D.......
  1466. 00000020 04001000 4C495354 3A000000 494E464F ....LIST:...INFO
  1467. 00000030 494E414D 14000000 49205761 6E742054 INAM....I Want T
  1468. 00000040 6F20436F 6D65204F 76657200 49415254 o Come Over.IART
  1469. 00000050 12000000 4D656C69 73736120 45746865 ....Melissa Ethe
  1470. 00000060 72696467 65006461 746100EA 69030100 ridge.data..i...
  1471. 00000070 FEFF0300 FCFF0400 FDFF0200 0000FEFF ................
  1472. 00000080 0300FDFF 0200FFFF 00000100 FEFF0300 ................
  1473. 00000090 FDFF0300 FDFF0200 FFFF0100 0000FFFF ................
  1474. */
  1475. // SD library on Teensy3 at 96 MHz
  1476. // 256 byte chunks, speed is 443272 bytes/sec
  1477. // 512 byte chunks, speed is 468023 bytes/sec
  1478. bool AudioPlaySDcardWAV::parse_format(void)
  1479. {
  1480. uint8_t num = 0;
  1481. uint16_t format;
  1482. uint16_t channels;
  1483. uint32_t rate;
  1484. uint16_t bits;
  1485. format = header[0];
  1486. //Serial.print(" format = ");
  1487. //Serial.println(format);
  1488. if (format != 1) return false;
  1489. channels = header[0] >> 16;
  1490. //Serial.print(" channels = ");
  1491. //Serial.println(channels);
  1492. if (channels == 1) {
  1493. } else if (channels == 2) {
  1494. num = 1;
  1495. } else {
  1496. return false;
  1497. }
  1498. bits = header[3] >> 16;
  1499. //Serial.print(" bits = ");
  1500. //Serial.println(bits);
  1501. if (bits == 8) {
  1502. } else if (bits == 16) {
  1503. num |= 2;
  1504. } else {
  1505. return false;
  1506. }
  1507. rate = header[1];
  1508. //Serial.print(" rate = ");
  1509. //Serial.println(rate);
  1510. if (rate == AUDIO_SAMPLE_RATE) {
  1511. } else if (rate >= 8000 && rate <= 48000) {
  1512. num |= 4;
  1513. } else {
  1514. return false;
  1515. }
  1516. // we're not checking the byte rate and block align fields
  1517. // if they're not the expected values, all we could do is
  1518. // return false. Do any real wav files have unexpected
  1519. // values in these other fields?
  1520. state_play = num;
  1521. return true;
  1522. }
  1523. /******************************************************************/
  1524. void AudioPlaySDcardRAW::begin(void)
  1525. {
  1526. playing = false;
  1527. if (block) {
  1528. release(block);
  1529. block = NULL;
  1530. }
  1531. }
  1532. bool AudioPlaySDcardRAW::play(const char *filename)
  1533. {
  1534. stop();
  1535. rawfile = SD.open(filename);
  1536. if (!rawfile) {
  1537. Serial.println("unable to open file");
  1538. return false;
  1539. }
  1540. Serial.println("able to open file");
  1541. playing = true;
  1542. return true;
  1543. }
  1544. void AudioPlaySDcardRAW::stop(void)
  1545. {
  1546. __disable_irq();
  1547. if (playing) {
  1548. playing = false;
  1549. __enable_irq();
  1550. rawfile.close();
  1551. } else {
  1552. __enable_irq();
  1553. }
  1554. }
  1555. void AudioPlaySDcardRAW::update(void)
  1556. {
  1557. unsigned int i, n;
  1558. // only update if we're playing
  1559. if (!playing) return;
  1560. // allocate the audio blocks to transmit
  1561. block = allocate();
  1562. if (block == NULL) return;
  1563. if (rawfile.available()) {
  1564. // we can read more data from the file...
  1565. n = rawfile.read(block->data, AUDIO_BLOCK_SAMPLES*2);
  1566. for (i=n/2; i < AUDIO_BLOCK_SAMPLES; i++) {
  1567. block->data[i] = 0;
  1568. }
  1569. transmit(block);
  1570. release(block);
  1571. } else {
  1572. rawfile.close();
  1573. playing = false;
  1574. }
  1575. }
  1576. /******************************************************************/
  1577. void AudioPlayMemory::play(const unsigned int *data)
  1578. {
  1579. uint32_t format;
  1580. playing = 0;
  1581. prior = 0;
  1582. format = *data++;
  1583. next = data;
  1584. length = format & 0xFFFFFF;
  1585. playing = format >> 24;
  1586. }
  1587. void AudioPlayMemory::stop(void)
  1588. {
  1589. playing = 0;
  1590. }
  1591. extern "C" {
  1592. extern const int16_t ulaw_decode_table[256];
  1593. };
  1594. void AudioPlayMemory::update(void)
  1595. {
  1596. audio_block_t *block;
  1597. const unsigned int *in;
  1598. int16_t *out;
  1599. uint32_t tmp32, consumed;
  1600. int16_t s0, s1, s2, s3, s4;
  1601. int i;
  1602. if (!playing) return;
  1603. block = allocate();
  1604. if (block == NULL) return;
  1605. //Serial.write('.');
  1606. out = block->data;
  1607. in = next;
  1608. s0 = prior;
  1609. switch (playing) {
  1610. case 0x01: // u-law encoded, 44100 Hz
  1611. for (i=0; i < AUDIO_BLOCK_SAMPLES; i += 4) {
  1612. tmp32 = *in++;
  1613. *out++ = ulaw_decode_table[(tmp32 >> 0) & 255];
  1614. *out++ = ulaw_decode_table[(tmp32 >> 8) & 255];
  1615. *out++ = ulaw_decode_table[(tmp32 >> 16) & 255];
  1616. *out++ = ulaw_decode_table[(tmp32 >> 24) & 255];
  1617. }
  1618. consumed = 128;
  1619. break;
  1620. case 0x81: // 16 bit PCM, 44100 Hz
  1621. for (i=0; i < AUDIO_BLOCK_SAMPLES; i += 2) {
  1622. tmp32 = *in++;
  1623. *out++ = (int16_t)(tmp32 & 65535);
  1624. *out++ = (int16_t)(tmp32 >> 16);
  1625. }
  1626. consumed = 128;
  1627. break;
  1628. case 0x02: // u-law encoded, 22050 Hz
  1629. for (i=0; i < AUDIO_BLOCK_SAMPLES; i += 8) {
  1630. tmp32 = *in++;
  1631. s1 = ulaw_decode_table[(tmp32 >> 0) & 255];
  1632. s2 = ulaw_decode_table[(tmp32 >> 8) & 255];
  1633. s3 = ulaw_decode_table[(tmp32 >> 16) & 255];
  1634. s4 = ulaw_decode_table[(tmp32 >> 24) & 255];
  1635. *out++ = (s0 + s1) >> 1;
  1636. *out++ = s1;
  1637. *out++ = (s1 + s2) >> 1;
  1638. *out++ = s2;
  1639. *out++ = (s2 + s3) >> 1;
  1640. *out++ = s3;
  1641. *out++ = (s3 + s4) >> 1;
  1642. *out++ = s4;
  1643. s0 = s4;
  1644. }
  1645. consumed = 64;
  1646. break;
  1647. case 0x82: // 16 bits PCM, 22050 Hz
  1648. for (i=0; i < AUDIO_BLOCK_SAMPLES; i += 4) {
  1649. tmp32 = *in++;
  1650. s1 = (int16_t)(tmp32 & 65535);
  1651. s2 = (int16_t)(tmp32 >> 16);
  1652. *out++ = (s0 + s1) >> 1;
  1653. *out++ = s1;
  1654. *out++ = (s1 + s2) >> 1;
  1655. *out++ = s2;
  1656. s0 = s2;
  1657. }
  1658. consumed = 64;
  1659. break;
  1660. case 0x03: // u-law encoded, 11025 Hz
  1661. for (i=0; i < AUDIO_BLOCK_SAMPLES; i += 16) {
  1662. tmp32 = *in++;
  1663. s1 = ulaw_decode_table[(tmp32 >> 0) & 255];
  1664. s2 = ulaw_decode_table[(tmp32 >> 8) & 255];
  1665. s3 = ulaw_decode_table[(tmp32 >> 16) & 255];
  1666. s4 = ulaw_decode_table[(tmp32 >> 24) & 255];
  1667. *out++ = (s0 * 3 + s1) >> 2;
  1668. *out++ = (s0 + s1) >> 1;
  1669. *out++ = (s0 + s1 * 3) >> 2;
  1670. *out++ = s1;
  1671. *out++ = (s1 * 3 + s2) >> 2;
  1672. *out++ = (s1 + s2) >> 1;
  1673. *out++ = (s1 + s2 * 3) >> 2;
  1674. *out++ = s2;
  1675. *out++ = (s2 * 3 + s3) >> 2;
  1676. *out++ = (s2 + s3) >> 1;
  1677. *out++ = (s2 + s3 * 3) >> 2;
  1678. *out++ = s3;
  1679. *out++ = (s3 * 3 + s4) >> 2;
  1680. *out++ = (s3 + s4) >> 1;
  1681. *out++ = (s3 + s4 * 3) >> 2;
  1682. *out++ = s4;
  1683. s0 = s4;
  1684. }
  1685. consumed = 32;
  1686. break;
  1687. case 0x83: // 16 bit PCM, 11025 Hz
  1688. for (i=0; i < AUDIO_BLOCK_SAMPLES; i += 8) {
  1689. tmp32 = *in++;
  1690. s1 = (int16_t)(tmp32 & 65535);
  1691. s2 = (int16_t)(tmp32 >> 16);
  1692. *out++ = (s0 * 3 + s1) >> 2;
  1693. *out++ = (s0 + s1) >> 1;
  1694. *out++ = (s0 + s1 * 3) >> 2;
  1695. *out++ = s1;
  1696. *out++ = (s1 * 3 + s2) >> 2;
  1697. *out++ = (s1 + s2) >> 1;
  1698. *out++ = (s1 + s2 * 3) >> 2;
  1699. *out++ = s2;
  1700. s0 = s2;
  1701. }
  1702. consumed = 32;
  1703. break;
  1704. default:
  1705. release(block);
  1706. playing = 0;
  1707. return;
  1708. }
  1709. prior = s0;
  1710. next = in;
  1711. if (length > consumed) {
  1712. length -= consumed;
  1713. } else {
  1714. playing = 0;
  1715. }
  1716. transmit(block);
  1717. release(block);
  1718. }
  1719. /******************************************************************/
  1720. // computes ((a[31:0] * b[15:0]) >> 16)
  1721. static inline int32_t signed_multiply_32x16b(int32_t a, uint32_t b) __attribute__((always_inline));
  1722. static inline int32_t signed_multiply_32x16b(int32_t a, uint32_t b)
  1723. {
  1724. int32_t out;
  1725. asm volatile("smulwb %0, %1, %2" : "=r" (out) : "r" (a), "r" (b));
  1726. return out;
  1727. }
  1728. // computes ((a[31:0] * b[31:16]) >> 16)
  1729. static inline int32_t signed_multiply_32x16t(int32_t a, uint32_t b) __attribute__((always_inline));
  1730. static inline int32_t signed_multiply_32x16t(int32_t a, uint32_t b)
  1731. {
  1732. int32_t out;
  1733. asm volatile("smulwt %0, %1, %2" : "=r" (out) : "r" (a), "r" (b));
  1734. return out;
  1735. }
  1736. // computes (((int64_t)a[31:0] * (int64_t)b[31:0]) >> 32)
  1737. static inline int32_t multiply_32x32_rshift32(int32_t a, int32_t b) __attribute__((always_inline));
  1738. static inline int32_t multiply_32x32_rshift32(int32_t a, int32_t b)
  1739. {
  1740. int32_t out;
  1741. asm volatile("smmul %0, %1, %2" : "=r" (out) : "r" (a), "r" (b));
  1742. return out;
  1743. }
  1744. // computes (((int64_t)a[31:0] * (int64_t)b[31:0] + 0x8000000) >> 32)
  1745. static inline int32_t multiply_32x32_rshift32_rounded(int32_t a, int32_t b) __attribute__((always_inline));
  1746. static inline int32_t multiply_32x32_rshift32_rounded(int32_t a, int32_t b)
  1747. {
  1748. int32_t out;
  1749. asm volatile("smmulr %0, %1, %2" : "=r" (out) : "r" (a), "r" (b));
  1750. return out;
  1751. }
  1752. // computes sum + (((int64_t)a[31:0] * (int64_t)b[31:0] + 0x8000000) >> 32)
  1753. static inline int32_t multiply_accumulate_32x32_rshift32_rounded(int32_t sum, int32_t a, int32_t b) __attribute__((always_inline));
  1754. static inline int32_t multiply_accumulate_32x32_rshift32_rounded(int32_t sum, int32_t a, int32_t b)
  1755. {
  1756. int32_t out;
  1757. asm volatile("smmlar %0, %2, %3, %1" : "=r" (out) : "r" (sum), "r" (a), "r" (b));
  1758. return out;
  1759. }
  1760. // computes sum - (((int64_t)a[31:0] * (int64_t)b[31:0] + 0x8000000) >> 32)
  1761. static inline int32_t multiply_subtract_32x32_rshift32_rounded(int32_t sum, int32_t a, int32_t b) __attribute__((always_inline));
  1762. static inline int32_t multiply_subtract_32x32_rshift32_rounded(int32_t sum, int32_t a, int32_t b)
  1763. {
  1764. int32_t out;
  1765. asm volatile("smmlsr %0, %2, %3, %1" : "=r" (out) : "r" (sum), "r" (a), "r" (b));
  1766. return out;
  1767. }
  1768. // computes ((a[15:0] << 16) | b[15:0])
  1769. static inline uint32_t pack_16x16(int32_t a, int32_t b) __attribute__((always_inline));
  1770. static inline uint32_t pack_16x16(int32_t a, int32_t b)
  1771. {
  1772. int32_t out;
  1773. asm volatile("pkhbt %0, %1, %2, lsl #16" : "=r" (out) : "r" (b), "r" (a));
  1774. return out;
  1775. }
  1776. // computes (((a[31:16] + b[31:16]) << 16) | (a[15:0 + b[15:0]))
  1777. static inline uint32_t signed_add_16_and_16(uint32_t a, uint32_t b) __attribute__((always_inline));
  1778. static inline uint32_t signed_add_16_and_16(uint32_t a, uint32_t b)
  1779. {
  1780. int32_t out;
  1781. asm volatile("qadd16 %0, %1, %2" : "=r" (out) : "r" (a), "r" (b));
  1782. return out;
  1783. }
  1784. // computes (sum + ((a[31:0] * b[15:0]) >> 16))
  1785. static inline int32_t signed_multiply_accumulate_32x16b(int32_t sum, int32_t a, uint32_t b)
  1786. {
  1787. int32_t out;
  1788. asm volatile("smlawb %0, %2, %3, %1" : "=r" (out) : "r" (sum), "r" (a), "r" (b));
  1789. return out;
  1790. }
  1791. // computes (sum + ((a[31:0] * b[31:16]) >> 16))
  1792. static inline int32_t signed_multiply_accumulate_32x16t(int32_t sum, int32_t a, uint32_t b)
  1793. {
  1794. int32_t out;
  1795. asm volatile("smlawt %0, %2, %3, %1" : "=r" (out) : "r" (sum), "r" (a), "r" (b));
  1796. return out;
  1797. }
  1798. // computes logical and, forces compiler to allocate register and use single cycle instruction
  1799. static inline uint32_t logical_and(uint32_t a, uint32_t b)
  1800. {
  1801. asm volatile("and %0, %1" : "+r" (a) : "r" (b));
  1802. return a;
  1803. }
  1804. void applyGain(int16_t *data, int32_t mult)
  1805. {
  1806. uint32_t *p = (uint32_t *)data;
  1807. const uint32_t *end = (uint32_t *)(data + AUDIO_BLOCK_SAMPLES);
  1808. do {
  1809. uint32_t tmp32 = *p; // read 2 samples from *data
  1810. int32_t val1 = signed_multiply_32x16b(mult, tmp32);
  1811. int32_t val2 = signed_multiply_32x16t(mult, tmp32);
  1812. val1 = signed_saturate_rshift(val1, 16, 0);
  1813. val2 = signed_saturate_rshift(val2, 16, 0);
  1814. *p++ = pack_16x16(val2, val1);
  1815. } while (p < end);
  1816. }
  1817. // page 133
  1818. void applyGainThenAdd(int16_t *data, const int16_t *in, int32_t mult)
  1819. {
  1820. uint32_t *dst = (uint32_t *)data;
  1821. const uint32_t *src = (uint32_t *)in;
  1822. const uint32_t *end = (uint32_t *)(data + AUDIO_BLOCK_SAMPLES);
  1823. if (mult == 65536) {
  1824. do {
  1825. uint32_t tmp32 = *dst;
  1826. *dst++ = signed_add_16_and_16(tmp32, *src++);
  1827. tmp32 = *dst;
  1828. *dst++ = signed_add_16_and_16(tmp32, *src++);
  1829. } while (dst < end);
  1830. } else {
  1831. do {
  1832. uint32_t tmp32 = *src++; // read 2 samples from *data
  1833. int32_t val1 = signed_multiply_32x16b(mult, tmp32);
  1834. int32_t val2 = signed_multiply_32x16t(mult, tmp32);
  1835. val1 = signed_saturate_rshift(val1, 16, 0);
  1836. val2 = signed_saturate_rshift(val2, 16, 0);
  1837. tmp32 = pack_16x16(val2, val1);
  1838. uint32_t tmp32b = *dst;
  1839. *dst++ = signed_add_16_and_16(tmp32, tmp32b);
  1840. } while (dst < end);
  1841. }
  1842. }
  1843. void AudioMixer4::update(void)
  1844. {
  1845. audio_block_t *in, *out=NULL;
  1846. unsigned int channel;
  1847. for (channel=0; channel < 4; channel++) {
  1848. if (!out) {
  1849. out = receiveWritable(channel);
  1850. if (out) {
  1851. int32_t mult = multiplier[channel];
  1852. if (mult != 65536) applyGain(out->data, mult);
  1853. }
  1854. } else {
  1855. in = receiveReadOnly(channel);
  1856. if (in) {
  1857. applyGainThenAdd(out->data, in->data, multiplier[channel]);
  1858. release(in);
  1859. }
  1860. }
  1861. }
  1862. if (out) {
  1863. transmit(out);
  1864. release(out);
  1865. }
  1866. }
  1867. /******************************************************************/
  1868. void AudioFilterBiquad::update(void)
  1869. {
  1870. audio_block_t *block;
  1871. int32_t a0, a1, a2, b1, b2, sum;
  1872. uint32_t in2, out2, aprev, bprev, flag;
  1873. uint32_t *data, *end;
  1874. int32_t *state;
  1875. block = receiveWritable();
  1876. if (!block) return;
  1877. data = (uint32_t *)(block->data);
  1878. end = data + AUDIO_BLOCK_SAMPLES/2;
  1879. state = (int32_t *)definition;
  1880. do {
  1881. a0 = *state++;
  1882. a1 = *state++;
  1883. a2 = *state++;
  1884. b1 = *state++;
  1885. b2 = *state++;
  1886. aprev = *state++;
  1887. bprev = *state++;
  1888. sum = *state & 0x3FFF;
  1889. do {
  1890. in2 = *data;
  1891. sum = signed_multiply_accumulate_32x16b(sum, a0, in2);
  1892. sum = signed_multiply_accumulate_32x16t(sum, a1, aprev);
  1893. sum = signed_multiply_accumulate_32x16b(sum, a2, aprev);
  1894. sum = signed_multiply_accumulate_32x16t(sum, b1, bprev);
  1895. sum = signed_multiply_accumulate_32x16b(sum, b2, bprev);
  1896. out2 = (uint32_t)sum >> 14;
  1897. sum &= 0x3FFF;
  1898. sum = signed_multiply_accumulate_32x16t(sum, a0, in2);
  1899. sum = signed_multiply_accumulate_32x16b(sum, a1, in2);
  1900. sum = signed_multiply_accumulate_32x16t(sum, a2, aprev);
  1901. sum = signed_multiply_accumulate_32x16b(sum, b1, out2);
  1902. sum = signed_multiply_accumulate_32x16t(sum, b2, bprev);
  1903. aprev = in2;
  1904. bprev = pack_16x16(sum >> 14, out2);
  1905. sum &= 0x3FFF;
  1906. aprev = in2;
  1907. *data++ = bprev;
  1908. } while (data < end);
  1909. flag = *state & 0x80000000;
  1910. *state++ = sum | flag;
  1911. *(state-2) = bprev;
  1912. *(state-3) = aprev;
  1913. } while (flag);
  1914. transmit(block);
  1915. release(block);
  1916. }
  1917. void AudioFilterBiquad::updateCoefs(int *source, bool doReset)
  1918. {
  1919. int32_t *dest=(int32_t *)definition;
  1920. int32_t *src=(int32_t *)source;
  1921. __disable_irq();
  1922. for(uint8_t index=0;index<5;index++)
  1923. {
  1924. *dest++=*src++;
  1925. }
  1926. if(doReset)
  1927. {
  1928. *dest++=0;
  1929. *dest++=0;
  1930. *dest++=0;
  1931. }
  1932. __enable_irq();
  1933. }
  1934. void AudioFilterBiquad::updateCoefs(int *source)
  1935. {
  1936. updateCoefs(source,false);
  1937. }
  1938. /******************************************************************/
  1939. extern "C" {
  1940. extern const int16_t fader_table[256];
  1941. };
  1942. void AudioEffectFade::update(void)
  1943. {
  1944. audio_block_t *block;
  1945. uint32_t i, pos, inc, index, scale;
  1946. int32_t val1, val2, val, sample;
  1947. uint8_t dir;
  1948. pos = position;
  1949. if (pos == 0) {
  1950. // output is silent
  1951. block = receiveReadOnly();
  1952. if (block) release(block);
  1953. return;
  1954. } else if (pos == 0xFFFFFFFF) {
  1955. // output is 100%
  1956. block = receiveReadOnly();
  1957. if (!block) return;
  1958. transmit(block);
  1959. release(block);
  1960. return;
  1961. }
  1962. block = receiveWritable();
  1963. if (!block) return;
  1964. inc = rate;
  1965. dir = direction;
  1966. for (i=0; i < AUDIO_BLOCK_SAMPLES; i++) {
  1967. index = pos >> 24;
  1968. val1 = fader_table[index];
  1969. val2 = fader_table[index+1];
  1970. scale = (pos >> 8) & 0xFFFF;
  1971. val2 *= scale;
  1972. val1 *= 0x10000 - scale;
  1973. val = (val1 + val2) >> 16;
  1974. sample = block->data[i];
  1975. sample = (sample * val) >> 15;
  1976. block->data[i] = sample;
  1977. if (dir > 0) {
  1978. // output is increasing
  1979. if (inc < 0xFFFFFFFF - pos) pos += inc;
  1980. else pos = 0xFFFFFFFF;
  1981. } else {
  1982. // output is decreasing
  1983. if (inc < pos) pos -= inc;
  1984. else pos = 0;
  1985. }
  1986. }
  1987. position = pos;
  1988. transmit(block);
  1989. release(block);
  1990. }
  1991. void AudioEffectFade::fadeBegin(uint32_t newrate, uint8_t dir)
  1992. {
  1993. __disable_irq();
  1994. uint32_t pos = position;
  1995. if (pos == 0) position = 1;
  1996. else if (pos == 0xFFFFFFFF) position = 0xFFFFFFFE;
  1997. rate = newrate;
  1998. direction = dir;
  1999. __enable_irq();
  2000. }
  2001. /******************************************************************/
  2002. static inline int32_t multiply_32x32_rshift30(int32_t a, int32_t b) __attribute__((always_inline));
  2003. static inline int32_t multiply_32x32_rshift30(int32_t a, int32_t b)
  2004. {
  2005. return ((int64_t)a * (int64_t)b) >> 30;
  2006. }
  2007. //#define TONE_DETECT_FAST
  2008. void AudioAnalyzeToneDetect::update(void)
  2009. {
  2010. audio_block_t *block;
  2011. int32_t q0, q1, q2, coef;
  2012. const int16_t *p, *end;
  2013. uint16_t n;
  2014. block = receiveReadOnly();
  2015. if (!block) return;
  2016. if (!enabled) {
  2017. release(block);
  2018. return;
  2019. }
  2020. p = block->data;
  2021. end = p + AUDIO_BLOCK_SAMPLES;
  2022. n = count;
  2023. coef = coefficient;
  2024. q1 = s1;
  2025. q2 = s2;
  2026. do {
  2027. // the Goertzel algorithm is kinda magical ;-)
  2028. #ifdef TONE_DETECT_FAST
  2029. q0 = (*p++) + (multiply_32x32_rshift32_rounded(coef, q1) << 2) - q2;
  2030. #else
  2031. q0 = (*p++) + multiply_32x32_rshift30(coef, q1) - q2;
  2032. // TODO: is this only 1 cycle slower? if so, always use it
  2033. #endif
  2034. q2 = q1;
  2035. q1 = q0;
  2036. if (--n == 0) {
  2037. out1 = q1;
  2038. out2 = q2;
  2039. q1 = 0; // TODO: does clearing these help or hinder?
  2040. q2 = 0;
  2041. new_output = true;
  2042. n = length;
  2043. }
  2044. } while (p < end);
  2045. count = n;
  2046. s1 = q1;
  2047. s2 = q2;
  2048. release(block);
  2049. }
  2050. void AudioAnalyzeToneDetect::set_params(int32_t coef, uint16_t cycles, uint16_t len)
  2051. {
  2052. __disable_irq();
  2053. coefficient = coef;
  2054. ncycles = cycles;
  2055. length = len;
  2056. count = len;
  2057. s1 = 0;
  2058. s2 = 0;
  2059. enabled = true;
  2060. __enable_irq();
  2061. //Serial.printf("Tone: coef=%d, ncycles=%d, length=%d\n", coefficient, ncycles, length);
  2062. }
  2063. float AudioAnalyzeToneDetect::read(void)
  2064. {
  2065. int32_t coef, q1, q2, power;
  2066. uint16_t len;
  2067. __disable_irq();
  2068. coef = coefficient;
  2069. q1 = out1;
  2070. q2 = out2;
  2071. len = length;
  2072. __enable_irq();
  2073. #ifdef TONE_DETECT_FAST
  2074. power = multiply_32x32_rshift32_rounded(q2, q2);
  2075. power = multiply_accumulate_32x32_rshift32_rounded(power, q1, q1);
  2076. power = multiply_subtract_32x32_rshift32_rounded(power,
  2077. multiply_32x32_rshift30(q1, q2), coef);
  2078. power <<= 4;
  2079. #else
  2080. int64_t power64;
  2081. power64 = (int64_t)q2 * (int64_t)q2;
  2082. power64 += (int64_t)q1 * (int64_t)q1;
  2083. power64 -= (((int64_t)q1 * (int64_t)q2) >> 30) * (int64_t)coef;
  2084. power = power64 >> 28;
  2085. #endif
  2086. return sqrtf((float)power) / (float)len;
  2087. }
  2088. AudioAnalyzeToneDetect::operator bool()
  2089. {
  2090. int32_t coef, q1, q2, power, trigger;
  2091. uint16_t len;
  2092. __disable_irq();
  2093. coef = coefficient;
  2094. q1 = out1;
  2095. q2 = out2;
  2096. len = length;
  2097. __enable_irq();
  2098. #ifdef TONE_DETECT_FAST
  2099. power = multiply_32x32_rshift32_rounded(q2, q2);
  2100. power = multiply_accumulate_32x32_rshift32_rounded(power, q1, q1);
  2101. power = multiply_subtract_32x32_rshift32_rounded(power,
  2102. multiply_32x32_rshift30(q1, q2), coef);
  2103. power <<= 4;
  2104. #else
  2105. int64_t power64;
  2106. power64 = (int64_t)q2 * (int64_t)q2;
  2107. power64 += (int64_t)q1 * (int64_t)q1;
  2108. power64 -= (((int64_t)q1 * (int64_t)q2) >> 30) * (int64_t)coef;
  2109. power = power64 >> 28;
  2110. #endif
  2111. trigger = (uint32_t)len * thresh;
  2112. trigger = multiply_32x32_rshift32(trigger, trigger);
  2113. Serial.printf("bool: power=%d, trig=%d\n", power, trigger);
  2114. return (power >= trigger);
  2115. }
  2116. /******************************************************************/
  2117. #include "Wire.h"
  2118. #define WM8731_I2C_ADDR 0x1A
  2119. //#define WM8731_I2C_ADDR 0x1B
  2120. #define WM8731_REG_LLINEIN 0
  2121. #define WM8731_REG_RLINEIN 1
  2122. #define WM8731_REG_LHEADOUT 2
  2123. #define WM8731_REG_RHEADOUT 3
  2124. #define WM8731_REG_ANALOG 4
  2125. #define WM8731_REG_DIGITAL 5
  2126. #define WM8731_REG_POWERDOWN 6
  2127. #define WM8731_REG_INTERFACE 7
  2128. #define WM8731_REG_SAMPLING 8
  2129. #define WM8731_REG_ACTIVE 9
  2130. #define WM8731_REG_RESET 15
  2131. bool AudioControlWM8731::enable(void)
  2132. {
  2133. Wire.begin();
  2134. delay(5);
  2135. //write(WM8731_REG_RESET, 0);
  2136. write(WM8731_REG_INTERFACE, 0x02); // I2S, 16 bit, MCLK slave
  2137. write(WM8731_REG_SAMPLING, 0x20); // 256*Fs, 44.1 kHz, MCLK/1
  2138. // In order to prevent pops, the DAC should first be soft-muted (DACMU),
  2139. // the output should then be de-selected from the line and headphone output
  2140. // (DACSEL), then the DAC powered down (DACPD).
  2141. write(WM8731_REG_DIGITAL, 0x08); // DAC soft mute
  2142. write(WM8731_REG_ANALOG, 0x00); // disable all
  2143. write(WM8731_REG_POWERDOWN, 0x00); // codec powerdown
  2144. write(WM8731_REG_LHEADOUT, 0x80); // volume off
  2145. write(WM8731_REG_RHEADOUT, 0x80);
  2146. delay(100); // how long to power up?
  2147. write(WM8731_REG_ACTIVE, 1);
  2148. delay(5);
  2149. write(WM8731_REG_DIGITAL, 0x00); // DAC unmuted
  2150. write(WM8731_REG_ANALOG, 0x10); // DAC selected
  2151. return true;
  2152. }
  2153. bool AudioControlWM8731::write(unsigned int reg, unsigned int val)
  2154. {
  2155. Wire.beginTransmission(WM8731_I2C_ADDR);
  2156. Wire.write((reg << 1) | ((val >> 8) & 1));
  2157. Wire.write(val & 0xFF);
  2158. Wire.endTransmission();
  2159. return true;
  2160. }
  2161. bool AudioControlWM8731::volumeInteger(unsigned int n)
  2162. {
  2163. if (n > 127) n = 127;
  2164. //Serial.print("volumeInteger, n = ");
  2165. //Serial.println(n);
  2166. write(WM8731_REG_LHEADOUT, n | 0x180);
  2167. write(WM8731_REG_RHEADOUT, n | 0x80);
  2168. return true;
  2169. }
  2170. /******************************************************************/
  2171. bool AudioControlWM8731master::enable(void)
  2172. {
  2173. Wire.begin();
  2174. delay(5);
  2175. //write(WM8731_REG_RESET, 0);
  2176. write(WM8731_REG_INTERFACE, 0x42); // I2S, 16 bit, MCLK master
  2177. write(WM8731_REG_SAMPLING, 0x20); // 256*Fs, 44.1 kHz, MCLK/1
  2178. // In order to prevent pops, the DAC should first be soft-muted (DACMU),
  2179. // the output should then be de-selected from the line and headphone output
  2180. // (DACSEL), then the DAC powered down (DACPD).
  2181. write(WM8731_REG_DIGITAL, 0x08); // DAC soft mute
  2182. write(WM8731_REG_ANALOG, 0x00); // disable all
  2183. write(WM8731_REG_POWERDOWN, 0x00); // codec powerdown
  2184. write(WM8731_REG_LHEADOUT, 0x80); // volume off
  2185. write(WM8731_REG_RHEADOUT, 0x80);
  2186. delay(100); // how long to power up?
  2187. write(WM8731_REG_ACTIVE, 1);
  2188. delay(5);
  2189. write(WM8731_REG_DIGITAL, 0x00); // DAC unmuted
  2190. write(WM8731_REG_ANALOG, 0x10); // DAC selected
  2191. return true;
  2192. }
  2193. /******************************************************************/
  2194. #define CHIP_ID 0x0000
  2195. // 15:8 PARTID 0xA0 - 8 bit identifier for SGTL5000
  2196. // 7:0 REVID 0x00 - revision number for SGTL5000.
  2197. #define CHIP_DIG_POWER 0x0002
  2198. // 6 ADC_POWERUP 1=Enable, 0=disable the ADC block, both digital & analog,
  2199. // 5 DAC_POWERUP 1=Enable, 0=disable the DAC block, both analog and digital
  2200. // 4 DAP_POWERUP 1=Enable, 0=disable the DAP block
  2201. // 1 I2S_OUT_POWERUP 1=Enable, 0=disable the I2S data output
  2202. // 0 I2S_IN_POWERUP 1=Enable, 0=disable the I2S data input
  2203. #define CHIP_CLK_CTRL 0x0004
  2204. // 5:4 RATE_MODE Sets the sample rate mode. MCLK_FREQ is still specified
  2205. // relative to the rate in SYS_FS
  2206. // 0x0 = SYS_FS specifies the rate
  2207. // 0x1 = Rate is 1/2 of the SYS_FS rate
  2208. // 0x2 = Rate is 1/4 of the SYS_FS rate
  2209. // 0x3 = Rate is 1/6 of the SYS_FS rate
  2210. // 3:2 SYS_FS Sets the internal system sample rate (default=2)
  2211. // 0x0 = 32 kHz
  2212. // 0x1 = 44.1 kHz
  2213. // 0x2 = 48 kHz
  2214. // 0x3 = 96 kHz
  2215. // 1:0 MCLK_FREQ Identifies incoming SYS_MCLK frequency and if the PLL should be used
  2216. // 0x0 = 256*Fs
  2217. // 0x1 = 384*Fs
  2218. // 0x2 = 512*Fs
  2219. // 0x3 = Use PLL
  2220. // The 0x3 (Use PLL) setting must be used if the SYS_MCLK is not
  2221. // a standard multiple of Fs (256, 384, or 512). This setting can
  2222. // also be used if SYS_MCLK is a standard multiple of Fs.
  2223. // Before this field is set to 0x3 (Use PLL), the PLL must be
  2224. // powered up by setting CHIP_ANA_POWER->PLL_POWERUP and
  2225. // CHIP_ANA_POWER->VCOAMP_POWERUP. Also, the PLL dividers must
  2226. // be calculated based on the external MCLK rate and
  2227. // CHIP_PLL_CTRL register must be set (see CHIP_PLL_CTRL register
  2228. // description details on how to calculate the divisors).
  2229. #define CHIP_I2S_CTRL 0x0006
  2230. // 8 SCLKFREQ Sets frequency of I2S_SCLK when in master mode (MS=1). When in slave
  2231. // mode (MS=0), this field must be set appropriately to match SCLK input
  2232. // rate.
  2233. // 0x0 = 64Fs
  2234. // 0x1 = 32Fs - Not supported for RJ mode (I2S_MODE = 1)
  2235. // 7 MS Configures master or slave of I2S_LRCLK and I2S_SCLK.
  2236. // 0x0 = Slave: I2S_LRCLK an I2S_SCLK are inputs
  2237. // 0x1 = Master: I2S_LRCLK and I2S_SCLK are outputs
  2238. // NOTE: If the PLL is used (CHIP_CLK_CTRL->MCLK_FREQ==0x3),
  2239. // the SGTL5000 must be a master of the I2S port (MS==1)
  2240. // 6 SCLK_INV Sets the edge that data (input and output) is clocked in on for I2S_SCLK
  2241. // 0x0 = data is valid on rising edge of I2S_SCLK
  2242. // 0x1 = data is valid on falling edge of I2S_SCLK
  2243. // 5:4 DLEN I2S data length (default=1)
  2244. // 0x0 = 32 bits (only valid when SCLKFREQ=0),
  2245. // not valid for Right Justified Mode
  2246. // 0x1 = 24 bits (only valid when SCLKFREQ=0)
  2247. // 0x2 = 20 bits
  2248. // 0x3 = 16 bits
  2249. // 3:2 I2S_MODE Sets the mode for the I2S port
  2250. // 0x0 = I2S mode or Left Justified (Use LRALIGN to select)
  2251. // 0x1 = Right Justified Mode
  2252. // 0x2 = PCM Format A/B
  2253. // 0x3 = RESERVED
  2254. // 1 LRALIGN I2S_LRCLK Alignment to data word. Not used for Right Justified mode
  2255. // 0x0 = Data word starts 1 I2S_SCLK delay after I2S_LRCLK
  2256. // transition (I2S format, PCM format A)
  2257. // 0x1 = Data word starts after I2S_LRCLK transition (left
  2258. // justified format, PCM format B)
  2259. // 0 LRPOL I2S_LRCLK Polarity when data is presented.
  2260. // 0x0 = I2S_LRCLK = 0 - Left, 1 - Right
  2261. // 1x0 = I2S_LRCLK = 0 - Right, 1 - Left
  2262. // The left subframe should be presented first regardless of
  2263. // the setting of LRPOL.
  2264. #define CHIP_SSS_CTRL 0x000A
  2265. // 14 DAP_MIX_LRSWAP DAP Mixer Input Swap
  2266. // 0x0 = Normal Operation
  2267. // 0x1 = Left and Right channels for the DAP MIXER Input are swapped.
  2268. // 13 DAP_LRSWAP DAP Mixer Input Swap
  2269. // 0x0 = Normal Operation
  2270. // 0x1 = Left and Right channels for the DAP Input are swapped
  2271. // 12 DAC_LRSWAP DAC Input Swap
  2272. // 0x0 = Normal Operation
  2273. // 0x1 = Left and Right channels for the DAC are swapped
  2274. // 10 I2S_LRSWAP I2S_DOUT Swap
  2275. // 0x0 = Normal Operation
  2276. // 0x1 = Left and Right channels for the I2S_DOUT are swapped
  2277. // 9:8 DAP_MIX_SELECT Select data source for DAP mixer
  2278. // 0x0 = ADC
  2279. // 0x1 = I2S_IN
  2280. // 0x2 = Reserved
  2281. // 0x3 = Reserved
  2282. // 7:6 DAP_SELECT Select data source for DAP
  2283. // 0x0 = ADC
  2284. // 0x1 = I2S_IN
  2285. // 0x2 = Reserved
  2286. // 0x3 = Reserved
  2287. // 5:4 DAC_SELECT Select data source for DAC (default=1)
  2288. // 0x0 = ADC
  2289. // 0x1 = I2S_IN
  2290. // 0x2 = Reserved
  2291. // 0x3 = DAP
  2292. // 1:0 I2S_SELECT Select data source for I2S_DOUT
  2293. // 0x0 = ADC
  2294. // 0x1 = I2S_IN
  2295. // 0x2 = Reserved
  2296. // 0x3 = DAP
  2297. #define CHIP_ADCDAC_CTRL 0x000E
  2298. // 13 VOL_BUSY_DAC_RIGHT Volume Busy DAC Right
  2299. // 0x0 = Ready
  2300. // 0x1 = Busy - This indicates the channel has not reached its
  2301. // programmed volume/mute level
  2302. // 12 VOL_BUSY_DAC_LEFT Volume Busy DAC Left
  2303. // 0x0 = Ready
  2304. // 0x1 = Busy - This indicates the channel has not reached its
  2305. // programmed volume/mute level
  2306. // 9 VOL_RAMP_EN Volume Ramp Enable (default=1)
  2307. // 0x0 = Disables volume ramp. New volume settings take immediate
  2308. // effect without a ramp
  2309. // 0x1 = Enables volume ramp
  2310. // This field affects DAC_VOL. The volume ramp effects both
  2311. // volume settings and mute When set to 1 a soft mute is enabled.
  2312. // 8 VOL_EXPO_RAMP Exponential Volume Ramp Enable
  2313. // 0x0 = Linear ramp over top 4 volume octaves
  2314. // 0x1 = Exponential ramp over full volume range
  2315. // This bit only takes effect if VOL_RAMP_EN is 1.
  2316. // 3 DAC_MUTE_RIGHT DAC Right Mute (default=1)
  2317. // 0x0 = Unmute
  2318. // 0x1 = Muted
  2319. // If VOL_RAMP_EN = 1, this is a soft mute.
  2320. // 2 DAC_MUTE_LEFT DAC Left Mute (default=1)
  2321. // 0x0 = Unmute
  2322. // 0x1 = Muted
  2323. // If VOL_RAMP_EN = 1, this is a soft mute.
  2324. // 1 ADC_HPF_FREEZE ADC High Pass Filter Freeze
  2325. // 0x0 = Normal operation
  2326. // 0x1 = Freeze the ADC high-pass filter offset register. The
  2327. // offset continues to be subtracted from the ADC data stream.
  2328. // 0 ADC_HPF_BYPASS ADC High Pass Filter Bypass
  2329. // 0x0 = Normal operation
  2330. // 0x1 = Bypassed and offset not updated
  2331. #define CHIP_DAC_VOL 0x0010
  2332. // 15:8 DAC_VOL_RIGHT DAC Right Channel Volume. Set the Right channel DAC volume
  2333. // with 0.5017 dB steps from 0 to -90 dB
  2334. // 0x3B and less = Reserved
  2335. // 0x3C = 0 dB
  2336. // 0x3D = -0.5 dB
  2337. // 0xF0 = -90 dB
  2338. // 0xFC and greater = Muted
  2339. // If VOL_RAMP_EN = 1, there is an automatic ramp to the
  2340. // new volume setting.
  2341. // 7:0 DAC_VOL_LEFT DAC Left Channel Volume. Set the Left channel DAC volume
  2342. // with 0.5017 dB steps from 0 to -90 dB
  2343. // 0x3B and less = Reserved
  2344. // 0x3C = 0 dB
  2345. // 0x3D = -0.5 dB
  2346. // 0xF0 = -90 dB
  2347. // 0xFC and greater = Muted
  2348. // If VOL_RAMP_EN = 1, there is an automatic ramp to the
  2349. // new volume setting.
  2350. #define CHIP_PAD_STRENGTH 0x0014
  2351. // 9:8 I2S_LRCLK I2S LRCLK Pad Drive Strength (default=1)
  2352. // Sets drive strength for output pads per the table below.
  2353. // VDDIO 1.8 V 2.5 V 3.3 V
  2354. // 0x0 = Disable
  2355. // 0x1 = 1.66 mA 2.87 mA 4.02 mA
  2356. // 0x2 = 3.33 mA 5.74 mA 8.03 mA
  2357. // 0x3 = 4.99 mA 8.61 mA 12.05 mA
  2358. // 7:6 I2S_SCLK I2S SCLK Pad Drive Strength (default=1)
  2359. // 5:4 I2S_DOUT I2S DOUT Pad Drive Strength (default=1)
  2360. // 3:2 CTRL_DATA I2C DATA Pad Drive Strength (default=3)
  2361. // 1:0 CTRL_CLK I2C CLK Pad Drive Strength (default=3)
  2362. // (all use same table as I2S_LRCLK)
  2363. #define CHIP_ANA_ADC_CTRL 0x0020
  2364. // 8 ADC_VOL_M6DB ADC Volume Range Reduction
  2365. // This bit shifts both right and left analog ADC volume
  2366. // range down by 6.0 dB.
  2367. // 0x0 = No change in ADC range
  2368. // 0x1 = ADC range reduced by 6.0 dB
  2369. // 7:4 ADC_VOL_RIGHT ADC Right Channel Volume
  2370. // Right channel analog ADC volume control in 1.5 dB steps.
  2371. // 0x0 = 0 dB
  2372. // 0x1 = +1.5 dB
  2373. // ...
  2374. // 0xF = +22.5 dB
  2375. // This range is -6.0 dB to +16.5 dB if ADC_VOL_M6DB is set to 1.
  2376. // 3:0 ADC_VOL_LEFT ADC Left Channel Volume
  2377. // (same scale as ADC_VOL_RIGHT)
  2378. #define CHIP_ANA_HP_CTRL 0x0022
  2379. // 14:8 HP_VOL_RIGHT Headphone Right Channel Volume (default 0x18)
  2380. // Right channel headphone volume control with 0.5 dB steps.
  2381. // 0x00 = +12 dB
  2382. // 0x01 = +11.5 dB
  2383. // 0x18 = 0 dB
  2384. // ...
  2385. // 0x7F = -51.5 dB
  2386. // 6:0 HP_VOL_LEFT Headphone Left Channel Volume (default 0x18)
  2387. // (same scale as HP_VOL_RIGHT)
  2388. #define CHIP_ANA_CTRL 0x0024
  2389. // 8 MUTE_LO LINEOUT Mute, 0 = Unmute, 1 = Mute (default 1)
  2390. // 6 SELECT_HP Select the headphone input, 0 = DAC, 1 = LINEIN
  2391. // 5 EN_ZCD_HP Enable the headphone zero cross detector (ZCD)
  2392. // 0x0 = HP ZCD disabled
  2393. // 0x1 = HP ZCD enabled
  2394. // 4 MUTE_HP Mute the headphone outputs, 0 = Unmute, 1 = Mute (default)
  2395. // 2 SELECT_ADC Select the ADC input, 0 = Microphone, 1 = LINEIN
  2396. // 1 EN_ZCD_ADC Enable the ADC analog zero cross detector (ZCD)
  2397. // 0x0 = ADC ZCD disabled
  2398. // 0x1 = ADC ZCD enabled
  2399. // 0 MUTE_ADC Mute the ADC analog volume, 0 = Unmute, 1 = Mute (default)
  2400. #define CHIP_LINREG_CTRL 0x0026
  2401. // 6 VDDC_MAN_ASSN Determines chargepump source when VDDC_ASSN_OVRD is set.
  2402. // 0x0 = VDDA
  2403. // 0x1 = VDDIO
  2404. // 5 VDDC_ASSN_OVRD Charge pump Source Assignment Override
  2405. // 0x0 = Charge pump source is automatically assigned based
  2406. // on higher of VDDA and VDDIO
  2407. // 0x1 = the source of charge pump is manually assigned by
  2408. // VDDC_MAN_ASSN If VDDIO and VDDA are both the same
  2409. // and greater than 3.1 V, VDDC_ASSN_OVRD and
  2410. // VDDC_MAN_ASSN should be used to manually assign
  2411. // VDDIO as the source for charge pump.
  2412. // 3:0 D_PROGRAMMING Sets the VDDD linear regulator output voltage in 50 mV steps.
  2413. // Must clear the LINREG_SIMPLE_POWERUP and STARTUP_POWERUP bits
  2414. // in the 0x0030 (CHIP_ANA_POWER) register after power-up, for
  2415. // this setting to produce the proper VDDD voltage.
  2416. // 0x0 = 1.60
  2417. // 0xF = 0.85
  2418. #define CHIP_REF_CTRL 0x0028 // bandgap reference bias voltage and currents
  2419. // 8:4 VAG_VAL Analog Ground Voltage Control
  2420. // These bits control the analog ground voltage in 25 mV steps.
  2421. // This should usually be set to VDDA/2 or lower for best
  2422. // performance (maximum output swing at minimum THD). This VAG
  2423. // reference is also used for the DAC and ADC voltage reference.
  2424. // So changing this voltage scales the output swing of the DAC
  2425. // and the output signal of the ADC.
  2426. // 0x00 = 0.800 V
  2427. // 0x1F = 1.575 V
  2428. // 3:1 BIAS_CTRL Bias control
  2429. // These bits adjust the bias currents for all of the analog
  2430. // blocks. By lowering the bias current a lower quiescent power
  2431. // is achieved. It should be noted that this mode can affect
  2432. // performance by 3-4 dB.
  2433. // 0x0 = Nominal
  2434. // 0x1-0x3=+12.5%
  2435. // 0x4=-12.5%
  2436. // 0x5=-25%
  2437. // 0x6=-37.5%
  2438. // 0x7=-50%
  2439. // 0 SMALL_POP VAG Ramp Control
  2440. // Setting this bit slows down the VAG ramp from ~200 to ~400 ms
  2441. // to reduce the startup pop, but increases the turn on/off time.
  2442. // 0x0 = Normal VAG ramp
  2443. // 0x1 = Slow down VAG ramp
  2444. #define CHIP_MIC_CTRL 0x002A // microphone gain & internal microphone bias
  2445. // 9:8 BIAS_RESISTOR MIC Bias Output Impedance Adjustment
  2446. // Controls an adjustable output impedance for the microphone bias.
  2447. // If this is set to zero the micbias block is powered off and
  2448. // the output is highZ.
  2449. // 0x0 = Powered off
  2450. // 0x1 = 2.0 kohm
  2451. // 0x2 = 4.0 kohm
  2452. // 0x3 = 8.0 kohm
  2453. // 6:4 BIAS_VOLT MIC Bias Voltage Adjustment
  2454. // Controls an adjustable bias voltage for the microphone bias
  2455. // amp in 250 mV steps. This bias voltage setting should be no
  2456. // more than VDDA-200 mV for adequate power supply rejection.
  2457. // 0x0 = 1.25 V
  2458. // ...
  2459. // 0x7 = 3.00 V
  2460. // 1:0 GAIN MIC Amplifier Gain
  2461. // Sets the microphone amplifier gain. At 0 dB setting the THD
  2462. // can be slightly higher than other paths- typically around
  2463. // ~65 dB. At other gain settings the THD are better.
  2464. // 0x0 = 0 dB
  2465. // 0x1 = +20 dB
  2466. // 0x2 = +30 dB
  2467. // 0x3 = +40 dB
  2468. #define CHIP_LINE_OUT_CTRL 0x002C
  2469. // 11:8 OUT_CURRENT Controls the output bias current for the LINEOUT amplifiers. The
  2470. // nominal recommended setting for a 10 kohm load with 1.0 nF load cap
  2471. // is 0x3. There are only 5 valid settings.
  2472. // 0x0=0.18 mA
  2473. // 0x1=0.27 mA
  2474. // 0x3=0.36 mA
  2475. // 0x7=0.45 mA
  2476. // 0xF=0.54 mA
  2477. // 5:0 LO_VAGCNTRL LINEOUT Amplifier Analog Ground Voltage
  2478. // Controls the analog ground voltage for the LINEOUT amplifiers
  2479. // in 25 mV steps. This should usually be set to VDDIO/2.
  2480. // 0x00 = 0.800 V
  2481. // ...
  2482. // 0x1F = 1.575 V
  2483. // ...
  2484. // 0x23 = 1.675 V
  2485. // 0x24-0x3F are invalid
  2486. #define CHIP_LINE_OUT_VOL 0x002E
  2487. // 12:8 LO_VOL_RIGHT LINEOUT Right Channel Volume (default=4)
  2488. // Controls the right channel LINEOUT volume in 0.5 dB steps.
  2489. // Higher codes have more attenuation.
  2490. // 4:0 LO_VOL_LEFT LINEOUT Left Channel Output Level (default=4)
  2491. // Used to normalize the output level of the left line output
  2492. // to full scale based on the values used to set
  2493. // LINE_OUT_CTRL->LO_VAGCNTRL and CHIP_REF_CTRL->VAG_VAL.
  2494. // In general this field should be set to:
  2495. // 40*log((VAG_VAL)/(LO_VAGCNTRL)) + 15
  2496. // Suggested values based on typical VDDIO and VDDA voltages.
  2497. // VDDA VAG_VAL VDDIO LO_VAGCNTRL LO_VOL_*
  2498. // 1.8 V 0.9 3.3 V 1.55 0x06
  2499. // 1.8 V 0.9 1.8 V 0.9 0x0F
  2500. // 3.3 V 1.55 1.8 V 0.9 0x19
  2501. // 3.3 V 1.55 3.3 V 1.55 0x0F
  2502. // After setting to the nominal voltage, this field can be used
  2503. // to adjust the output level in +/-0.5 dB increments by using
  2504. // values higher or lower than the nominal setting.
  2505. #define CHIP_ANA_POWER 0x0030 // power down controls for the analog blocks.
  2506. // The only other power-down controls are BIAS_RESISTOR in the MIC_CTRL register
  2507. // and the EN_ZCD control bits in ANA_CTRL.
  2508. // 14 DAC_MONO While DAC_POWERUP is set, this allows the DAC to be put into left only
  2509. // mono operation for power savings. 0=mono, 1=stereo (default)
  2510. // 13 LINREG_SIMPLE_POWERUP Power up the simple (low power) digital supply regulator.
  2511. // After reset, this bit can be cleared IF VDDD is driven
  2512. // externally OR the primary digital linreg is enabled with
  2513. // LINREG_D_POWERUP
  2514. // 12 STARTUP_POWERUP Power up the circuitry needed during the power up ramp and reset.
  2515. // After reset this bit can be cleared if VDDD is coming from
  2516. // an external source.
  2517. // 11 VDDC_CHRGPMP_POWERUP Power up the VDDC charge pump block. If neither VDDA or VDDIO
  2518. // is 3.0 V or larger this bit should be cleared before analog
  2519. // blocks are powered up.
  2520. // 10 PLL_POWERUP PLL Power Up, 0 = Power down, 1 = Power up
  2521. // When cleared, the PLL is turned off. This must be set before
  2522. // CHIP_CLK_CTRL->MCLK_FREQ is programmed to 0x3. The
  2523. // CHIP_PLL_CTRL register must be configured correctly before
  2524. // setting this bit.
  2525. // 9 LINREG_D_POWERUP Power up the primary VDDD linear regulator, 0 = Power down, 1 = Power up
  2526. // 8 VCOAMP_POWERUP Power up the PLL VCO amplifier, 0 = Power down, 1 = Power up
  2527. // 7 VAG_POWERUP Power up the VAG reference buffer.
  2528. // Setting this bit starts the power up ramp for the headphone
  2529. // and LINEOUT. The headphone (and/or LINEOUT) powerup should
  2530. // be set BEFORE clearing this bit. When this bit is cleared
  2531. // the power-down ramp is started. The headphone (and/or LINEOUT)
  2532. // powerup should stay set until the VAG is fully ramped down
  2533. // (200 to 400 ms after clearing this bit).
  2534. // 0x0 = Power down, 0x1 = Power up
  2535. // 6 ADC_MONO While ADC_POWERUP is set, this allows the ADC to be put into left only
  2536. // mono operation for power savings. This mode is useful when
  2537. // only using the microphone input.
  2538. // 0x0 = Mono (left only), 0x1 = Stereo
  2539. // 5 REFTOP_POWERUP Power up the reference bias currents
  2540. // 0x0 = Power down, 0x1 = Power up
  2541. // This bit can be cleared when the part is a sleep state
  2542. // to minimize analog power.
  2543. // 4 HEADPHONE_POWERUP Power up the headphone amplifiers
  2544. // 0x0 = Power down, 0x1 = Power up
  2545. // 3 DAC_POWERUP Power up the DACs
  2546. // 0x0 = Power down, 0x1 = Power up
  2547. // 2 CAPLESS_HEADPHONE_POWERUP Power up the capless headphone mode
  2548. // 0x0 = Power down, 0x1 = Power up
  2549. // 1 ADC_POWERUP Power up the ADCs
  2550. // 0x0 = Power down, 0x1 = Power up
  2551. // 0 LINEOUT_POWERUP Power up the LINEOUT amplifiers
  2552. // 0x0 = Power down, 0x1 = Power up
  2553. #define CHIP_PLL_CTRL 0x0032
  2554. // 15:11 INT_DIVISOR
  2555. // 10:0 FRAC_DIVISOR
  2556. #define CHIP_CLK_TOP_CTRL 0x0034
  2557. // 11 ENABLE_INT_OSC Setting this bit enables an internal oscillator to be used for the
  2558. // zero cross detectors, the short detect recovery, and the
  2559. // charge pump. This allows the I2S clock to be shut off while
  2560. // still operating an analog signal path. This bit can be kept
  2561. // on when the I2S clock is enabled, but the I2S clock is more
  2562. // accurate so it is preferred to clear this bit when I2S is present.
  2563. // 3 INPUT_FREQ_DIV2 SYS_MCLK divider before PLL input
  2564. // 0x0 = pass through
  2565. // 0x1 = SYS_MCLK is divided by 2 before entering PLL
  2566. // This must be set when the input clock is above 17 Mhz. This
  2567. // has no effect when the PLL is powered down.
  2568. #define CHIP_ANA_STATUS 0x0036
  2569. // 9 LRSHORT_STS This bit is high whenever a short is detected on the left or right
  2570. // channel headphone drivers.
  2571. // 8 CSHORT_STS This bit is high whenever a short is detected on the capless headphone
  2572. // common/center channel driver.
  2573. // 4 PLL_IS_LOCKED This bit goes high after the PLL is locked.
  2574. #define CHIP_ANA_TEST1 0x0038 // intended only for debug.
  2575. #define CHIP_ANA_TEST2 0x003A // intended only for debug.
  2576. #define CHIP_SHORT_CTRL 0x003C
  2577. // 14:12 LVLADJR Right channel headphone short detector in 25 mA steps.
  2578. // 0x3=25 mA
  2579. // 0x2=50 mA
  2580. // 0x1=75 mA
  2581. // 0x0=100 mA
  2582. // 0x4=125 mA
  2583. // 0x5=150 mA
  2584. // 0x6=175 mA
  2585. // 0x7=200 mA
  2586. // This trip point can vary by ~30% over process so leave plenty
  2587. // of guard band to avoid false trips. This short detect trip
  2588. // point is also effected by the bias current adjustments made
  2589. // by CHIP_REF_CTRL->BIAS_CTRL and by CHIP_ANA_TEST1->HP_IALL_ADJ.
  2590. // 10:8 LVLADJL Left channel headphone short detector in 25 mA steps.
  2591. // (same scale as LVLADJR)
  2592. // 6:4 LVLADJC Capless headphone center channel short detector in 50 mA steps.
  2593. // 0x3=50 mA
  2594. // 0x2=100 mA
  2595. // 0x1=150 mA
  2596. // 0x0=200 mA
  2597. // 0x4=250 mA
  2598. // 0x5=300 mA
  2599. // 0x6=350 mA
  2600. // 0x7=400 mA
  2601. // 3:2 MODE_LR Behavior of left/right short detection
  2602. // 0x0 = Disable short detector, reset short detect latch,
  2603. // software view non-latched short signal
  2604. // 0x1 = Enable short detector and reset the latch at timeout
  2605. // (every ~50 ms)
  2606. // 0x2 = This mode is not used/invalid
  2607. // 0x3 = Enable short detector with only manual reset (have
  2608. // to return to 0x0 to reset the latch)
  2609. // 1:0 MODE_CM Behavior of capless headphone central short detection
  2610. // (same settings as MODE_LR)
  2611. #define DAP_CONTROL 0x0100
  2612. #define DAP_PEQ 0x0102
  2613. #define DAP_BASS_ENHANCE 0x0104
  2614. #define DAP_BASS_ENHANCE_CTRL 0x0106
  2615. #define DAP_AUDIO_EQ 0x0108
  2616. #define DAP_SGTL_SURROUND 0x010A
  2617. #define DAP_FILTER_COEF_ACCESS 0x010C
  2618. #define DAP_COEF_WR_B0_MSB 0x010E
  2619. #define DAP_COEF_WR_B0_LSB 0x0110
  2620. #define DAP_AUDIO_EQ_BASS_BAND0 0x0116 // 115 Hz
  2621. #define DAP_AUDIO_EQ_BAND1 0x0118 // 330 Hz
  2622. #define DAP_AUDIO_EQ_BAND2 0x011A // 990 Hz
  2623. #define DAP_AUDIO_EQ_BAND3 0x011C // 3000 Hz
  2624. #define DAP_AUDIO_EQ_TREBLE_BAND4 0x011E // 9900 Hz
  2625. #define DAP_MAIN_CHAN 0x0120
  2626. #define DAP_MIX_CHAN 0x0122
  2627. #define DAP_AVC_CTRL 0x0124
  2628. #define DAP_AVC_THRESHOLD 0x0126
  2629. #define DAP_AVC_ATTACK 0x0128
  2630. #define DAP_AVC_DECAY 0x012A
  2631. #define DAP_COEF_WR_B1_MSB 0x012C
  2632. #define DAP_COEF_WR_B1_LSB 0x012E
  2633. #define DAP_COEF_WR_B2_MSB 0x0130
  2634. #define DAP_COEF_WR_B2_LSB 0x0132
  2635. #define DAP_COEF_WR_A1_MSB 0x0134
  2636. #define DAP_COEF_WR_A1_LSB 0x0136
  2637. #define DAP_COEF_WR_A2_MSB 0x0138
  2638. #define DAP_COEF_WR_A2_LSB 0x013A
  2639. #define SGTL5000_I2C_ADDR 0x0A // CTRL_ADR0_CS pin low (normal configuration)
  2640. //#define SGTL5000_I2C_ADDR 0x2A // CTRL_ADR0_CS pin high
  2641. bool AudioControlSGTL5000::enable(void)
  2642. {
  2643. //unsigned int n;
  2644. muted = true;
  2645. Wire.begin();
  2646. delay(5);
  2647. //Serial.print("chip ID = ");
  2648. //delay(5);
  2649. //n = read(CHIP_ID);
  2650. //Serial.println(n, HEX);
  2651. write(CHIP_ANA_POWER, 0x4060); // VDDD is externally driven with 1.8V
  2652. write(CHIP_LINREG_CTRL, 0x006C); // VDDA & VDDIO both over 3.1V
  2653. write(CHIP_REF_CTRL, 0x01F1); // VAG=1.575 slow ramp, normal bias current
  2654. write(CHIP_LINE_OUT_CTRL, 0x0322); // LO_VAGCNTRL=1.65V, OUT_CURRENT=0.36mA
  2655. write(CHIP_SHORT_CTRL, 0x4446); // allow up to 125mA
  2656. write(CHIP_ANA_CTRL, 0x0137); // enable zero cross detectors
  2657. write(CHIP_ANA_POWER, 0x40FF); // power up: lineout, hp, adc, dac
  2658. write(CHIP_DIG_POWER, 0x0073); // power up all digital stuff
  2659. delay(400);
  2660. // 40*log((1.575)/(1.65)) + 15 = 13.1391993746043 but it seems wrong, 5 is better...
  2661. write(CHIP_LINE_OUT_VOL, 0x0505); // TODO: correct value for 3.3V
  2662. write(CHIP_CLK_CTRL, 0x0004); // 44.1 kHz, 256*Fs
  2663. write(CHIP_I2S_CTRL, 0x0130); // SCLK=32*Fs, 16bit, I2S format
  2664. // default signal routing is ok?
  2665. write(CHIP_SSS_CTRL, 0x0010); // ADC->I2S, I2S->DAC
  2666. write(CHIP_ADCDAC_CTRL, 0x0000); // disable dac mute
  2667. write(CHIP_DAC_VOL, 0x3C3C); // digital gain, 0dB
  2668. write(CHIP_ANA_HP_CTRL, 0x7F7F); // set volume (lowest level)
  2669. write(CHIP_ANA_CTRL, 0x0136); // enable zero cross detectors
  2670. //mute = false;
  2671. return true;
  2672. }
  2673. unsigned int AudioControlSGTL5000::read(unsigned int reg)
  2674. {
  2675. unsigned int val;
  2676. Wire.beginTransmission(SGTL5000_I2C_ADDR);
  2677. Wire.write(reg >> 8);
  2678. Wire.write(reg);
  2679. if (Wire.endTransmission(false) != 0) return 0;
  2680. if (Wire.requestFrom(SGTL5000_I2C_ADDR, 2) < 2) return 0;
  2681. val = Wire.read() << 8;
  2682. val |= Wire.read();
  2683. return val;
  2684. }
  2685. bool AudioControlSGTL5000::write(unsigned int reg, unsigned int val)
  2686. {
  2687. if (reg == CHIP_ANA_CTRL) ana_ctrl = val;
  2688. Wire.beginTransmission(SGTL5000_I2C_ADDR);
  2689. Wire.write(reg >> 8);
  2690. Wire.write(reg);
  2691. Wire.write(val >> 8);
  2692. Wire.write(val);
  2693. if (Wire.endTransmission() == 0) return true;
  2694. return false;
  2695. }
  2696. unsigned int AudioControlSGTL5000::modify(unsigned int reg, unsigned int val, unsigned int iMask)
  2697. {
  2698. unsigned int val1 = (read(reg)&(~iMask))|val;
  2699. if(!write(reg,val1)) return 0;
  2700. return val1;
  2701. }
  2702. bool AudioControlSGTL5000::volumeInteger(unsigned int n)
  2703. {
  2704. if (n == 0) {
  2705. muted = true;
  2706. write(CHIP_ANA_HP_CTRL, 0x7F7F);
  2707. return muteHeadphone();
  2708. } else if (n > 0x80) {
  2709. n = 0;
  2710. } else {
  2711. n = 0x80 - n;
  2712. }
  2713. if (muted) {
  2714. muted = false;
  2715. unmuteHeadphone();
  2716. }
  2717. n = n | (n << 8);
  2718. return write(CHIP_ANA_HP_CTRL, n); // set volume
  2719. }
  2720. bool AudioControlSGTL5000::volume(float left, float right)
  2721. {
  2722. unsigned short m=((0x7F-calcVol(right,0x7F))<<8)|(0x7F-calcVol(left,0x7F));
  2723. return write(CHIP_ANA_HP_CTRL, m);
  2724. }
  2725. // CHIP_LINE_OUT_VOL
  2726. unsigned short AudioControlSGTL5000::lo_lvl(uint8_t n)
  2727. {
  2728. n&=31;
  2729. return modify(CHIP_LINE_OUT_VOL,(n<<8)|n,(31<<8)|31);
  2730. }
  2731. unsigned short AudioControlSGTL5000::lo_lvl(uint8_t left, uint8_t right)
  2732. {
  2733. left&=31;
  2734. right&=31;
  2735. return modify(CHIP_LINE_OUT_VOL,(right<<8)|left,(31<<8)|31);
  2736. }
  2737. unsigned short AudioControlSGTL5000::dac_vol(float n) // set both directly
  2738. {
  2739. if(read(CHIP_ADCDAC_CTRL)&(3<<2)!=((n>0 ? 0:3)<<2)) modify(CHIP_ADCDAC_CTRL,(n>0 ? 0:3)<<2,3<<2);
  2740. unsigned char m=calcVol(n,0xC0);
  2741. return modify(CHIP_DAC_VOL,((0xFC-m)<<8)|(0xFC-m),65535);
  2742. }
  2743. unsigned short AudioControlSGTL5000::dac_vol(float left, float right)
  2744. {
  2745. unsigned short adcdac=((right>0 ? 0:2)|(left>0 ? 0:1))<<2;
  2746. if(read(CHIP_ADCDAC_CTRL)&(3<<2)!=adcdac) modify(CHIP_ADCDAC_CTRL,adcdac,1<<2);
  2747. unsigned short m=(0xFC-calcVol(right,0xC0))<<8|(0xFC-calcVol(left,0xC0));
  2748. return modify(CHIP_DAC_VOL,m,65535);
  2749. }
  2750. // DAP_CONTROL
  2751. unsigned short AudioControlSGTL5000::dap_mix_enable(uint8_t n)
  2752. {
  2753. return modify(DAP_CONTROL,(n&1)<<4,1<<4);
  2754. }
  2755. unsigned short AudioControlSGTL5000::dap_enable(uint8_t n)
  2756. {
  2757. if(n) n=1;
  2758. unsigned char DAC=1+(2*n); // I2S_IN if n==0 else DAP
  2759. modify(DAP_CONTROL,n,1);
  2760. return modify(CHIP_SSS_CTRL,(0<<6)|(DAC<<4),(3<<6)|(3<<4));
  2761. }
  2762. unsigned short AudioControlSGTL5000::dap_enable(void)
  2763. {
  2764. return dap_enable(1);
  2765. }
  2766. // DAP_PEQ
  2767. unsigned short AudioControlSGTL5000::dap_peqs(uint8_t n) // valid to n&7, 0 thru 7 filters enabled.
  2768. {
  2769. return modify(DAP_PEQ,(n&7),7);
  2770. }
  2771. // DAP_AUDIO_EQ
  2772. unsigned short AudioControlSGTL5000::dap_audio_eq(uint8_t n) // 0=NONE, 1=PEQ (7 IIR Biquad filters), 2=TONE (tone), 3=GEQ (5 band EQ)
  2773. {
  2774. return modify(DAP_AUDIO_EQ,n&3,3);
  2775. }
  2776. /******************************************************************/
  2777. void AudioFilterFIR::begin(short *cp,int n_coeffs)
  2778. {
  2779. // pointer to coefficients
  2780. coeff_p = cp;
  2781. // Initialize FIR instances for the left and right channels
  2782. if(coeff_p && (coeff_p != FIR_PASSTHRU)) {
  2783. arm_fir_init_q15(&l_fir_inst, n_coeffs, coeff_p, &l_StateQ15[0], AUDIO_BLOCK_SAMPLES);
  2784. arm_fir_init_q15(&r_fir_inst, n_coeffs, coeff_p, &r_StateQ15[0], AUDIO_BLOCK_SAMPLES);
  2785. }
  2786. }
  2787. // This has the same effect as begin(NULL,0);
  2788. void AudioFilterFIR::stop(void)
  2789. {
  2790. coeff_p = NULL;
  2791. }
  2792. void AudioFilterFIR::update(void)
  2793. {
  2794. audio_block_t *block,*b_new;
  2795. // If there's no coefficient table, give up.
  2796. if(coeff_p == NULL)return;
  2797. // do passthru
  2798. if(coeff_p == FIR_PASSTHRU) {
  2799. // Just passthrough
  2800. block = receiveWritable(0);
  2801. if(block) {
  2802. transmit(block,0);
  2803. release(block);
  2804. }
  2805. block = receiveWritable(1);
  2806. if(block) {
  2807. transmit(block,1);
  2808. release(block);
  2809. }
  2810. return;
  2811. }
  2812. // Left Channel
  2813. block = receiveWritable(0);
  2814. // get a block for the FIR output
  2815. b_new = allocate();
  2816. if(block && b_new) {
  2817. arm_fir_q15(&l_fir_inst, (q15_t *)block->data, (q15_t *)b_new->data, AUDIO_BLOCK_SAMPLES);
  2818. // send the FIR output to the left channel
  2819. transmit(b_new,0);
  2820. }
  2821. if(block)release(block);
  2822. if(b_new)release(b_new);
  2823. // Right Channel
  2824. block = receiveWritable(1);
  2825. b_new = allocate();
  2826. if(block && b_new) {
  2827. arm_fir_q15(&r_fir_inst, (q15_t *)block->data, (q15_t *)b_new->data, AUDIO_BLOCK_SAMPLES);
  2828. transmit(b_new,1);
  2829. }
  2830. if(block)release(block);
  2831. if(b_new)release(b_new);
  2832. }
  2833. /******************************************************************/
  2834. // A u d i o E f f e c t F l a n g e
  2835. // Written by Pete (El Supremo) Jan 2014
  2836. // 140207 - fix calculation of delay_rate_incr which is expressed as
  2837. // a fraction of 2*PI
  2838. // 140207 - cosmetic fix to begin()
  2839. // circular addressing indices for left and right channels
  2840. short AudioEffectFlange::l_circ_idx;
  2841. short AudioEffectFlange::r_circ_idx;
  2842. short * AudioEffectFlange::l_delayline = NULL;
  2843. short * AudioEffectFlange::r_delayline = NULL;
  2844. // User-supplied offset for the delayed sample
  2845. // but start with passthru
  2846. int AudioEffectFlange::delay_offset_idx = DELAY_PASSTHRU;
  2847. int AudioEffectFlange::delay_length;
  2848. int AudioEffectFlange::delay_depth;
  2849. int AudioEffectFlange::delay_rate_incr;
  2850. unsigned int AudioEffectFlange::l_delay_rate_index;
  2851. unsigned int AudioEffectFlange::r_delay_rate_index;
  2852. // fails if the user provides unreasonable values but will
  2853. // coerce them and go ahead anyway. e.g. if the delay offset
  2854. // is >= CHORUS_DELAY_LENGTH, the code will force it to
  2855. // CHORUS_DELAY_LENGTH-1 and return false.
  2856. // delay_rate is the rate (in Hz) of the sine wave modulation
  2857. // delay_depth is the maximum variation around delay_offset
  2858. // i.e. the total offset is delay_offset + delay_depth * sin(delay_rate)
  2859. boolean AudioEffectFlange::begin(short *delayline,int d_length,int delay_offset,int d_depth,float delay_rate)
  2860. {
  2861. boolean all_ok = true;
  2862. if(0) {
  2863. Serial.print("AudioEffectFlange.begin(offset = ");
  2864. Serial.print(delay_offset);
  2865. Serial.print(", depth = ");
  2866. Serial.print(d_depth);
  2867. Serial.print(", rate = ");
  2868. Serial.print(delay_rate,3);
  2869. Serial.println(")");
  2870. Serial.print(" FLANGE_DELAY_LENGTH = ");
  2871. Serial.println(d_length);
  2872. }
  2873. delay_length = d_length/2;
  2874. l_delayline = delayline;
  2875. r_delayline = delayline + delay_length;
  2876. delay_depth = d_depth;
  2877. // initial index
  2878. l_delay_rate_index = 0;
  2879. r_delay_rate_index = 0;
  2880. l_circ_idx = 0;
  2881. r_circ_idx = 0;
  2882. delay_rate_incr = delay_rate/44100.*2147483648.;
  2883. //Serial.println(delay_rate_incr,HEX);
  2884. delay_offset_idx = delay_offset;
  2885. // Allow the passthru code to go through
  2886. if(delay_offset_idx < -1) {
  2887. delay_offset_idx = 0;
  2888. all_ok = false;
  2889. }
  2890. if(delay_offset_idx >= delay_length) {
  2891. delay_offset_idx = delay_length - 1;
  2892. all_ok = false;
  2893. }
  2894. return(all_ok);
  2895. }
  2896. boolean AudioEffectFlange::modify(int delay_offset,int d_depth,float delay_rate)
  2897. {
  2898. boolean all_ok = true;
  2899. delay_depth = d_depth;
  2900. delay_rate_incr = delay_rate/44100.*2147483648.;
  2901. delay_offset_idx = delay_offset;
  2902. // Allow the passthru code to go through
  2903. if(delay_offset_idx < -1) {
  2904. delay_offset_idx = 0;
  2905. all_ok = false;
  2906. }
  2907. if(delay_offset_idx >= delay_length) {
  2908. delay_offset_idx = delay_length - 1;
  2909. all_ok = false;
  2910. }
  2911. l_delay_rate_index = 0;
  2912. r_delay_rate_index = 0;
  2913. l_circ_idx = 0;
  2914. r_circ_idx = 0;
  2915. return(all_ok);
  2916. }
  2917. void AudioEffectFlange::update(void)
  2918. {
  2919. audio_block_t *block;
  2920. int idx;
  2921. short *bp;
  2922. short frac;
  2923. int idx1;
  2924. if(l_delayline == NULL)return;
  2925. if(r_delayline == NULL)return;
  2926. // do passthru
  2927. if(delay_offset_idx == DELAY_PASSTHRU) {
  2928. // Just passthrough
  2929. block = receiveWritable(0);
  2930. if(block) {
  2931. bp = block->data;
  2932. for(int i = 0;i < AUDIO_BLOCK_SAMPLES;i++) {
  2933. l_circ_idx++;
  2934. if(l_circ_idx >= delay_length) {
  2935. l_circ_idx = 0;
  2936. }
  2937. l_delayline[l_circ_idx] = *bp++;
  2938. }
  2939. transmit(block,0);
  2940. release(block);
  2941. }
  2942. block = receiveWritable(1);
  2943. if(block) {
  2944. bp = block->data;
  2945. for(int i = 0;i < AUDIO_BLOCK_SAMPLES;i++) {
  2946. r_circ_idx++;
  2947. if(r_circ_idx >= delay_length) {
  2948. r_circ_idx = 0;
  2949. }
  2950. r_delayline[r_circ_idx] = *bp++;
  2951. }
  2952. transmit(block,1);
  2953. release(block);
  2954. }
  2955. return;
  2956. }
  2957. // L E F T C H A N N E L
  2958. block = receiveWritable(0);
  2959. if(block) {
  2960. bp = block->data;
  2961. for(int i = 0;i < AUDIO_BLOCK_SAMPLES;i++) {
  2962. l_circ_idx++;
  2963. if(l_circ_idx >= delay_length) {
  2964. l_circ_idx = 0;
  2965. }
  2966. l_delayline[l_circ_idx] = *bp;
  2967. idx = arm_sin_q15( (q15_t)((l_delay_rate_index >> 16) & 0x7fff));
  2968. idx = (idx * delay_depth) >> 15;
  2969. //Serial.println(idx);
  2970. idx = l_circ_idx - (delay_offset_idx + idx);
  2971. if(idx < 0) {
  2972. idx += delay_length;
  2973. }
  2974. if(idx >= delay_length) {
  2975. idx -= delay_length;
  2976. }
  2977. if(frac < 0)
  2978. idx1 = idx - 1;
  2979. else
  2980. idx1 = idx + 1;
  2981. if(idx1 < 0) {
  2982. idx1 += delay_length;
  2983. }
  2984. if(idx1 >= delay_length) {
  2985. idx1 -= delay_length;
  2986. }
  2987. frac = (l_delay_rate_index >> 1) &0x7fff;
  2988. frac = (( (int)(l_delayline[idx1] - l_delayline[idx])*frac) >> 15);
  2989. *bp++ = (l_delayline[l_circ_idx]
  2990. + l_delayline[idx] + frac
  2991. )/2;
  2992. l_delay_rate_index += delay_rate_incr;
  2993. if(l_delay_rate_index & 0x80000000) {
  2994. l_delay_rate_index &= 0x7fffffff;
  2995. }
  2996. }
  2997. // send the effect output to the left channel
  2998. transmit(block,0);
  2999. release(block);
  3000. }
  3001. // R I G H T C H A N N E L
  3002. block = receiveWritable(1);
  3003. if(block) {
  3004. bp = block->data;
  3005. for(int i = 0;i < AUDIO_BLOCK_SAMPLES;i++) {
  3006. r_circ_idx++;
  3007. if(r_circ_idx >= delay_length) {
  3008. r_circ_idx = 0;
  3009. }
  3010. r_delayline[r_circ_idx] = *bp;
  3011. idx = arm_sin_q15( (q15_t)((r_delay_rate_index >> 16)&0x7fff));
  3012. idx = (idx * delay_depth) >> 15;
  3013. idx = r_circ_idx - (delay_offset_idx + idx);
  3014. if(idx < 0) {
  3015. idx += delay_length;
  3016. }
  3017. if(idx >= delay_length) {
  3018. idx -= delay_length;
  3019. }
  3020. if(frac < 0)
  3021. idx1 = idx - 1;
  3022. else
  3023. idx1 = idx + 1;
  3024. if(idx1 < 0) {
  3025. idx1 += delay_length;
  3026. }
  3027. if(idx1 >= delay_length) {
  3028. idx1 -= delay_length;
  3029. }
  3030. frac = (r_delay_rate_index >> 1) &0x7fff;
  3031. frac = (( (int)(r_delayline[idx1] - r_delayline[idx])*frac) >> 15);
  3032. *bp++ = (r_delayline[r_circ_idx]
  3033. + r_delayline[idx] + frac
  3034. )/2;
  3035. r_delay_rate_index += delay_rate_incr;
  3036. if(r_delay_rate_index & 0x80000000) {
  3037. r_delay_rate_index &= 0x7fffffff;
  3038. }
  3039. }
  3040. // send the effect output to the right channel
  3041. transmit(block,1);
  3042. release(block);
  3043. }
  3044. }
  3045. /******************************************************************/
  3046. // A u d i o E f f e c t C h o r u s
  3047. // Written by Pete (El Supremo) Jan 2014
  3048. // circular addressing indices for left and right channels
  3049. short AudioEffectChorus::l_circ_idx;
  3050. short AudioEffectChorus::r_circ_idx;
  3051. short * AudioEffectChorus::l_delayline = NULL;
  3052. short * AudioEffectChorus::r_delayline = NULL;
  3053. int AudioEffectChorus::delay_length;
  3054. // An initial value of zero indicates passthru
  3055. int AudioEffectChorus::num_chorus = 0;
  3056. // All three must be valid.
  3057. boolean AudioEffectChorus::begin(short *delayline,int d_length,int n_chorus)
  3058. {
  3059. Serial.print("AudioEffectChorus.begin(Chorus delay line length = ");
  3060. Serial.print(d_length);
  3061. Serial.print(", n_chorus = ");
  3062. Serial.print(n_chorus);
  3063. Serial.println(")");
  3064. l_delayline = NULL;
  3065. r_delayline = NULL;
  3066. delay_length = 0;
  3067. l_circ_idx = 0;
  3068. r_circ_idx = 0;
  3069. if(delayline == NULL) {
  3070. return(false);
  3071. }
  3072. if(d_length < 10) {
  3073. return(false);
  3074. }
  3075. if(n_chorus < 1) {
  3076. return(false);
  3077. }
  3078. l_delayline = delayline;
  3079. r_delayline = delayline + d_length/2;
  3080. delay_length = d_length/2;
  3081. num_chorus = n_chorus;
  3082. return(true);
  3083. }
  3084. // This has the same effect as begin(NULL,0);
  3085. void AudioEffectChorus::stop(void)
  3086. {
  3087. }
  3088. void AudioEffectChorus::modify(int n_chorus)
  3089. {
  3090. num_chorus = n_chorus;
  3091. }
  3092. int iabs(int x)
  3093. {
  3094. if(x < 0)return(-x);
  3095. return(x);
  3096. }
  3097. //static int d_count = 0;
  3098. int last_idx = 0;
  3099. void AudioEffectChorus::update(void)
  3100. {
  3101. audio_block_t *block;
  3102. short *bp;
  3103. int sum;
  3104. int c_idx;
  3105. if(l_delayline == NULL)return;
  3106. if(r_delayline == NULL)return;
  3107. // do passthru
  3108. // It stores the unmodified data in the delay line so that
  3109. // it isn't as likely to click
  3110. if(num_chorus < 1) {
  3111. // Just passthrough
  3112. block = receiveWritable(0);
  3113. if(block) {
  3114. bp = block->data;
  3115. for(int i = 0;i < AUDIO_BLOCK_SAMPLES;i++) {
  3116. l_circ_idx++;
  3117. if(l_circ_idx >= delay_length) {
  3118. l_circ_idx = 0;
  3119. }
  3120. l_delayline[l_circ_idx] = *bp++;
  3121. }
  3122. transmit(block,0);
  3123. release(block);
  3124. }
  3125. block = receiveWritable(1);
  3126. if(block) {
  3127. bp = block->data;
  3128. for(int i = 0;i < AUDIO_BLOCK_SAMPLES;i++) {
  3129. r_circ_idx++;
  3130. if(r_circ_idx >= delay_length) {
  3131. r_circ_idx = 0;
  3132. }
  3133. r_delayline[r_circ_idx] = *bp++;
  3134. }
  3135. transmit(block,1);
  3136. release(block);
  3137. }
  3138. return;
  3139. }
  3140. // L E F T C H A N N E L
  3141. block = receiveWritable(0);
  3142. if(block) {
  3143. bp = block->data;
  3144. for(int i = 0;i < AUDIO_BLOCK_SAMPLES;i++) {
  3145. l_circ_idx++;
  3146. if(l_circ_idx >= delay_length) {
  3147. l_circ_idx = 0;
  3148. }
  3149. l_delayline[l_circ_idx] = *bp;
  3150. sum = 0;
  3151. c_idx = l_circ_idx;
  3152. for(int k = 0; k < num_chorus; k++) {
  3153. sum += l_delayline[c_idx];
  3154. if(num_chorus > 1)c_idx -= delay_length/(num_chorus - 1) - 1;
  3155. if(c_idx < 0) {
  3156. c_idx += delay_length;
  3157. }
  3158. }
  3159. *bp++ = sum/num_chorus;
  3160. }
  3161. // send the effect output to the left channel
  3162. transmit(block,0);
  3163. release(block);
  3164. }
  3165. // R I G H T C H A N N E L
  3166. block = receiveWritable(1);
  3167. if(block) {
  3168. bp = block->data;
  3169. for(int i = 0;i < AUDIO_BLOCK_SAMPLES;i++) {
  3170. r_circ_idx++;
  3171. if(r_circ_idx >= delay_length) {
  3172. r_circ_idx = 0;
  3173. }
  3174. r_delayline[r_circ_idx] = *bp;
  3175. sum = 0;
  3176. c_idx = r_circ_idx;
  3177. for(int k = 0; k < num_chorus; k++) {
  3178. sum += r_delayline[c_idx];
  3179. if(num_chorus > 1)c_idx -= delay_length/(num_chorus - 1) - 1;
  3180. if(c_idx < 0) {
  3181. c_idx += delay_length;
  3182. }
  3183. }
  3184. *bp++ = sum/num_chorus;
  3185. }
  3186. // send the effect output to the left channel
  3187. transmit(block,1);
  3188. release(block);
  3189. }
  3190. }
  3191. // DAP_AUDIO_EQ_BASS_BAND0 & DAP_AUDIO_EQ_BAND1 & DAP_AUDIO_EQ_BAND2 etc etc
  3192. unsigned short AudioControlSGTL5000::dap_audio_eq_band(uint8_t bandNum, float n) // by signed percentage -100/+100; dap_audio_eq(3);
  3193. { // 0x00==-12dB, 0x2F==0dB, 0x5F==12dB
  3194. n=((n/100)*48)+0.499;
  3195. if(n<-47) n=-47;
  3196. if(n>48) n=48;
  3197. n+=47;
  3198. return modify(DAP_AUDIO_EQ_BASS_BAND0+(bandNum*2),(unsigned int)n,127);
  3199. }
  3200. void AudioControlSGTL5000::dap_audio_eq_geq(float bass, float mid_bass, float midrange, float mid_treble, float treble)
  3201. {
  3202. dap_audio_eq_band(0,bass);
  3203. dap_audio_eq_band(1,mid_bass);
  3204. dap_audio_eq_band(2,midrange);
  3205. dap_audio_eq_band(3,mid_treble);
  3206. dap_audio_eq_band(4,treble);
  3207. }
  3208. void AudioControlSGTL5000::dap_audio_eq_tone(float bass, float treble) // dap_audio_eq(2);
  3209. {
  3210. dap_audio_eq_band(0,bass);
  3211. dap_audio_eq_band(4,treble);
  3212. }
  3213. // SGTL5000 PEQ Coefficient loader
  3214. void AudioControlSGTL5000::load_peq(uint8_t filterNum, int *filterParameters)
  3215. {
  3216. // 1111 11111111 11111111
  3217. write(DAP_COEF_WR_B0_MSB,(*filterParameters>>4)&65535);
  3218. write(DAP_COEF_WR_B0_LSB,(*filterParameters++)&15);
  3219. write(DAP_COEF_WR_B1_MSB,(*filterParameters>>4)&65535);
  3220. write(DAP_COEF_WR_B1_LSB,(*filterParameters++)&15);
  3221. write(DAP_COEF_WR_B2_MSB,(*filterParameters>>4)&65535);
  3222. write(DAP_COEF_WR_B2_LSB,(*filterParameters++)&15);
  3223. write(DAP_COEF_WR_A1_MSB,(*filterParameters>>4)&65535);
  3224. write(DAP_COEF_WR_A1_LSB,(*filterParameters++)&15);
  3225. write(DAP_COEF_WR_A2_MSB,(*filterParameters>>4)&65535);
  3226. write(DAP_COEF_WR_A2_LSB,(*filterParameters++)&15);
  3227. write(DAP_FILTER_COEF_ACCESS,(uint16_t)0x100|filterNum);
  3228. delay(10); // seems necessary, didn't work for 1ms.
  3229. modify(DAP_FILTER_COEF_ACCESS,(uint16_t)filterNum,15);
  3230. }
  3231. unsigned char AudioControlSGTL5000::calcVol(float n, unsigned char range)
  3232. {
  3233. n=(n*(((float)range)/100))+0.499;
  3234. if ((unsigned char)n>range) n=range;
  3235. return (unsigned char)n;
  3236. }
  3237. // if(SGTL5000_PEQ) quantization_unit=524288; if(AudioFilterBiquad) quantization_unit=2147483648;
  3238. void calcBiquad(uint8_t filtertype, float fC, float dB_Gain, float Q, uint32_t quantization_unit, uint32_t fS, int *coef)
  3239. {
  3240. // I used resources like http://www.musicdsp.org/files/Audio-EQ-Cookbook.txt
  3241. // to make this routine, I tested most of the filter types and they worked. Such filters have limits and
  3242. // before calling this routine with varying values the end user should check that those values are limited
  3243. // to valid results.
  3244. float A;
  3245. if(filtertype<FILTER_PARAEQ) A=pow(10,dB_Gain/20); else A=pow(10,dB_Gain/40);
  3246. float W0 = 2*3.14159265358979323846*fC/fS;
  3247. float cosw=cos(W0);
  3248. float sinw=sin(W0);
  3249. //float alpha = sinw*sinh((log(2)/2)*BW*W0/sinw);
  3250. //float beta = sqrt(2*A);
  3251. float alpha = sinw / (2 * Q);
  3252. float beta = sqrt(A)/Q;
  3253. float b0,b1,b2,a0,a1,a2;
  3254. switch(filtertype) {
  3255. case FILTER_LOPASS:
  3256. b0 = (1.0F - cosw) * 0.5F; // =(1-COS($H$2))/2
  3257. b1 = 1.0F - cosw;
  3258. b2 = (1.0F - cosw) * 0.5F;
  3259. a0 = 1.0F + alpha;
  3260. a1 = 2.0F * cosw;
  3261. a2 = alpha - 1.0F;
  3262. break;
  3263. case FILTER_HIPASS:
  3264. b0 = (1.0F + cosw) * 0.5F;
  3265. b1 = -(cosw + 1.0F);
  3266. b2 = (1.0F + cosw) * 0.5F;
  3267. a0 = 1.0F + alpha;
  3268. a1 = 2.0F * cosw;
  3269. a2 = alpha - 1.0F;
  3270. break;
  3271. case FILTER_BANDPASS:
  3272. b0 = alpha;
  3273. b1 = 0.0F;
  3274. b2 = -alpha;
  3275. a0 = 1.0F + alpha;
  3276. a1 = 2.0F * cosw;
  3277. a2 = alpha - 1.0F;
  3278. break;
  3279. case FILTER_NOTCH:
  3280. b0=1;
  3281. b1=-2*cosw;
  3282. b2=1;
  3283. a0=1+alpha;
  3284. a1=2*cosw;
  3285. a2=-(1-alpha);
  3286. break;
  3287. case FILTER_PARAEQ:
  3288. b0 = 1 + (alpha*A);
  3289. b1 =-2 * cosw;
  3290. b2 = 1 - (alpha*A);
  3291. a0 = 1 + (alpha/A);
  3292. a1 = 2 * cosw;
  3293. a2 =-(1-(alpha/A));
  3294. break;
  3295. case FILTER_LOSHELF:
  3296. b0 = A * ((A+1.0F) - ((A-1.0F)*cosw) + (beta*sinw));
  3297. b1 = 2.0F * A * ((A-1.0F) - ((A+1.0F)*cosw));
  3298. b2 = A * ((A+1.0F) - ((A-1.0F)*cosw) - (beta*sinw));
  3299. a0 = (A+1.0F) + ((A-1.0F)*cosw) + (beta*sinw);
  3300. a1 = 2.0F * ((A-1.0F) + ((A+1.0F)*cosw));
  3301. a2 = -((A+1.0F) + ((A-1.0F)*cosw) - (beta*sinw));
  3302. break;
  3303. case FILTER_HISHELF:
  3304. b0 = A * ((A+1.0F) + ((A-1.0F)*cosw) + (beta*sinw));
  3305. b1 = -2.0F * A * ((A-1.0F) + ((A+1.0F)*cosw));
  3306. b2 = A * ((A+1.0F) + ((A-1.0F)*cosw) - (beta*sinw));
  3307. a0 = (A+1.0F) - ((A-1.0F)*cosw) + (beta*sinw);
  3308. a1 = -2.0F * ((A-1.0F) - ((A+1.0F)*cosw));
  3309. a2 = -((A+1.0F) - ((A-1.0F)*cosw) - (beta*sinw));
  3310. }
  3311. a0=(a0*2)/(float)quantization_unit; // once here instead of five times there...
  3312. b0/=a0;
  3313. *coef++=(int)(b0+0.499);
  3314. b1/=a0;
  3315. *coef++=(int)(b1+0.499);
  3316. b2/=a0;
  3317. *coef++=(int)(b2+0.499);
  3318. a1/=a0;
  3319. *coef++=(int)(a1+0.499);
  3320. a2/=a0;
  3321. *coef++=(int)(a2+0.499);
  3322. }
  3323. /******************************************************************/
  3324. // A u d i o T o n e S w e e p
  3325. // Written by Pete (El Supremo) Feb 2014
  3326. boolean AudioToneSweep::begin(short t_amp,int t_lo,int t_hi,float t_time)
  3327. {
  3328. double tone_tmp;
  3329. if(0) {
  3330. Serial.print("AudioToneSweep.begin(tone_amp = ");
  3331. Serial.print(t_amp);
  3332. Serial.print(", tone_lo = ");
  3333. Serial.print(t_lo);
  3334. Serial.print(", tone_hi = ");
  3335. Serial.print(t_hi);
  3336. Serial.print(", tone_time = ");
  3337. Serial.print(t_time,1);
  3338. Serial.println(")");
  3339. }
  3340. tone_amp = 0;
  3341. if(t_amp < 0)return false;
  3342. if(t_lo < 1)return false;
  3343. if(t_hi < 1)return false;
  3344. if(t_hi >= 44100/2)return false;
  3345. if(t_lo >= 44100/2)return false;
  3346. if(t_time < 0)return false;
  3347. tone_lo = t_lo;
  3348. tone_hi = t_hi;
  3349. tone_phase = 0;
  3350. tone_amp = t_amp;
  3351. // Limit the output amplitude to prevent aliasing
  3352. // until I can figure out why this "overtops"
  3353. // above 29000.
  3354. if(tone_amp > 29000)tone_amp = 29000;
  3355. tone_tmp = tone_hi - tone_lo;
  3356. tone_sign = 1;
  3357. tone_freq = tone_lo*0x100000000LL;
  3358. if(tone_tmp < 0) {
  3359. tone_sign = -1;
  3360. tone_tmp = -tone_tmp;
  3361. }
  3362. tone_tmp = tone_tmp/t_time/44100.;
  3363. tone_incr = (tone_tmp * 0x100000000LL);
  3364. sweep_busy = 1;
  3365. return(true);
  3366. }
  3367. unsigned char AudioToneSweep::busy(void)
  3368. {
  3369. return(sweep_busy);
  3370. }
  3371. int b_count = 0;
  3372. void AudioToneSweep::update(void)
  3373. {
  3374. audio_block_t *block;
  3375. short *bp;
  3376. int i;
  3377. if(!sweep_busy)return;
  3378. // L E F T C H A N N E L O N L Y
  3379. block = allocate();
  3380. if(block) {
  3381. bp = block->data;
  3382. // Generate the sweep
  3383. for(i = 0;i < AUDIO_BLOCK_SAMPLES;i++) {
  3384. *bp++ = (short)(( (short)(arm_sin_q31((uint32_t)((tone_phase >> 15)&0x7fffffff))>>16) *tone_amp) >> 16);
  3385. uint64_t tone_tmp = (0x400000000000LL * (int)((tone_freq >> 32)&0x7fffffff))/44100;
  3386. tone_phase += tone_tmp;
  3387. if(tone_phase & 0x800000000000LL)tone_phase &= 0x7fffffffffffLL;
  3388. if(tone_sign > 0) {
  3389. if((tone_freq >> 32) > tone_hi) {
  3390. sweep_busy = 0;
  3391. break;
  3392. }
  3393. tone_freq += tone_incr;
  3394. } else {
  3395. if((tone_freq >> 32) < tone_hi) {
  3396. sweep_busy = 0;
  3397. break;
  3398. }
  3399. tone_freq -= tone_incr;
  3400. }
  3401. }
  3402. while(i < AUDIO_BLOCK_SAMPLES) {
  3403. *bp++ = 0;
  3404. i++;
  3405. }
  3406. b_count++;
  3407. // send the samples to the left channel
  3408. transmit(block,0);
  3409. release(block);
  3410. }
  3411. }