Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

3605 lines
98KB

  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. /******************************************************************/
  1918. extern "C" {
  1919. extern const int16_t fader_table[256];
  1920. };
  1921. void AudioEffectFade::update(void)
  1922. {
  1923. audio_block_t *block;
  1924. uint32_t i, pos, inc, index, scale;
  1925. int32_t val1, val2, val, sample;
  1926. uint8_t dir;
  1927. pos = position;
  1928. if (pos == 0) {
  1929. // output is silent
  1930. block = receiveReadOnly();
  1931. if (block) release(block);
  1932. return;
  1933. } else if (pos == 0xFFFFFFFF) {
  1934. // output is 100%
  1935. block = receiveReadOnly();
  1936. if (!block) return;
  1937. transmit(block);
  1938. release(block);
  1939. return;
  1940. }
  1941. block = receiveWritable();
  1942. if (!block) return;
  1943. inc = rate;
  1944. dir = direction;
  1945. for (i=0; i < AUDIO_BLOCK_SAMPLES; i++) {
  1946. index = pos >> 24;
  1947. val1 = fader_table[index];
  1948. val2 = fader_table[index+1];
  1949. scale = (pos >> 8) & 0xFFFF;
  1950. val2 *= scale;
  1951. val1 *= 0x10000 - scale;
  1952. val = (val1 + val2) >> 16;
  1953. sample = block->data[i];
  1954. sample = (sample * val) >> 15;
  1955. block->data[i] = sample;
  1956. if (dir > 0) {
  1957. // output is increasing
  1958. if (inc < 0xFFFFFFFF - pos) pos += inc;
  1959. else pos = 0xFFFFFFFF;
  1960. } else {
  1961. // output is decreasing
  1962. if (inc < pos) pos -= inc;
  1963. else pos = 0;
  1964. }
  1965. }
  1966. position = pos;
  1967. transmit(block);
  1968. release(block);
  1969. }
  1970. void AudioEffectFade::fadeBegin(uint32_t newrate, uint8_t dir)
  1971. {
  1972. __disable_irq();
  1973. uint32_t pos = position;
  1974. if (pos == 0) position = 1;
  1975. else if (pos == 0xFFFFFFFF) position = 0xFFFFFFFE;
  1976. rate = newrate;
  1977. direction = dir;
  1978. __enable_irq();
  1979. }
  1980. /******************************************************************/
  1981. static inline int32_t multiply_32x32_rshift30(int32_t a, int32_t b) __attribute__((always_inline));
  1982. static inline int32_t multiply_32x32_rshift30(int32_t a, int32_t b)
  1983. {
  1984. return ((int64_t)a * (int64_t)b) >> 30;
  1985. }
  1986. //#define TONE_DETECT_FAST
  1987. void AudioAnalyzeToneDetect::update(void)
  1988. {
  1989. audio_block_t *block;
  1990. int32_t q0, q1, q2, coef;
  1991. const int16_t *p, *end;
  1992. uint16_t n;
  1993. block = receiveReadOnly();
  1994. if (!block) return;
  1995. if (!enabled) {
  1996. release(block);
  1997. return;
  1998. }
  1999. p = block->data;
  2000. end = p + AUDIO_BLOCK_SAMPLES;
  2001. n = count;
  2002. coef = coefficient;
  2003. q1 = s1;
  2004. q2 = s2;
  2005. do {
  2006. // the Goertzel algorithm is kinda magical ;-)
  2007. #ifdef TONE_DETECT_FAST
  2008. q0 = (*p++) + (multiply_32x32_rshift32_rounded(coef, q1) << 2) - q2;
  2009. #else
  2010. q0 = (*p++) + multiply_32x32_rshift30(coef, q1) - q2;
  2011. // TODO: is this only 1 cycle slower? if so, always use it
  2012. #endif
  2013. q2 = q1;
  2014. q1 = q0;
  2015. if (--n == 0) {
  2016. out1 = q1;
  2017. out2 = q2;
  2018. q1 = 0; // TODO: does clearing these help or hinder?
  2019. q2 = 0;
  2020. new_output = true;
  2021. n = length;
  2022. }
  2023. } while (p < end);
  2024. count = n;
  2025. s1 = q1;
  2026. s2 = q2;
  2027. release(block);
  2028. }
  2029. void AudioAnalyzeToneDetect::set_params(int32_t coef, uint16_t cycles, uint16_t len)
  2030. {
  2031. __disable_irq();
  2032. coefficient = coef;
  2033. ncycles = cycles;
  2034. length = len;
  2035. count = len;
  2036. s1 = 0;
  2037. s2 = 0;
  2038. enabled = true;
  2039. __enable_irq();
  2040. //Serial.printf("Tone: coef=%d, ncycles=%d, length=%d\n", coefficient, ncycles, length);
  2041. }
  2042. float AudioAnalyzeToneDetect::read(void)
  2043. {
  2044. int32_t coef, q1, q2, power;
  2045. uint16_t len;
  2046. __disable_irq();
  2047. coef = coefficient;
  2048. q1 = out1;
  2049. q2 = out2;
  2050. len = length;
  2051. __enable_irq();
  2052. #ifdef TONE_DETECT_FAST
  2053. power = multiply_32x32_rshift32_rounded(q2, q2);
  2054. power = multiply_accumulate_32x32_rshift32_rounded(power, q1, q1);
  2055. power = multiply_subtract_32x32_rshift32_rounded(power,
  2056. multiply_32x32_rshift30(q1, q2), coef);
  2057. power <<= 4;
  2058. #else
  2059. int64_t power64;
  2060. power64 = (int64_t)q2 * (int64_t)q2;
  2061. power64 += (int64_t)q1 * (int64_t)q1;
  2062. power64 -= (((int64_t)q1 * (int64_t)q2) >> 30) * (int64_t)coef;
  2063. power = power64 >> 28;
  2064. #endif
  2065. return sqrtf((float)power) / (float)len;
  2066. }
  2067. AudioAnalyzeToneDetect::operator bool()
  2068. {
  2069. int32_t coef, q1, q2, power, trigger;
  2070. uint16_t len;
  2071. __disable_irq();
  2072. coef = coefficient;
  2073. q1 = out1;
  2074. q2 = out2;
  2075. len = length;
  2076. __enable_irq();
  2077. #ifdef TONE_DETECT_FAST
  2078. power = multiply_32x32_rshift32_rounded(q2, q2);
  2079. power = multiply_accumulate_32x32_rshift32_rounded(power, q1, q1);
  2080. power = multiply_subtract_32x32_rshift32_rounded(power,
  2081. multiply_32x32_rshift30(q1, q2), coef);
  2082. power <<= 4;
  2083. #else
  2084. int64_t power64;
  2085. power64 = (int64_t)q2 * (int64_t)q2;
  2086. power64 += (int64_t)q1 * (int64_t)q1;
  2087. power64 -= (((int64_t)q1 * (int64_t)q2) >> 30) * (int64_t)coef;
  2088. power = power64 >> 28;
  2089. #endif
  2090. trigger = (uint32_t)len * thresh;
  2091. trigger = multiply_32x32_rshift32(trigger, trigger);
  2092. Serial.printf("bool: power=%d, trig=%d\n", power, trigger);
  2093. return (power >= trigger);
  2094. }
  2095. /******************************************************************/
  2096. #include "Wire.h"
  2097. #define WM8731_I2C_ADDR 0x1A
  2098. //#define WM8731_I2C_ADDR 0x1B
  2099. #define WM8731_REG_LLINEIN 0
  2100. #define WM8731_REG_RLINEIN 1
  2101. #define WM8731_REG_LHEADOUT 2
  2102. #define WM8731_REG_RHEADOUT 3
  2103. #define WM8731_REG_ANALOG 4
  2104. #define WM8731_REG_DIGITAL 5
  2105. #define WM8731_REG_POWERDOWN 6
  2106. #define WM8731_REG_INTERFACE 7
  2107. #define WM8731_REG_SAMPLING 8
  2108. #define WM8731_REG_ACTIVE 9
  2109. #define WM8731_REG_RESET 15
  2110. bool AudioControlWM8731::enable(void)
  2111. {
  2112. Wire.begin();
  2113. delay(5);
  2114. //write(WM8731_REG_RESET, 0);
  2115. write(WM8731_REG_INTERFACE, 0x02); // I2S, 16 bit, MCLK slave
  2116. write(WM8731_REG_SAMPLING, 0x20); // 256*Fs, 44.1 kHz, MCLK/1
  2117. // In order to prevent pops, the DAC should first be soft-muted (DACMU),
  2118. // the output should then be de-selected from the line and headphone output
  2119. // (DACSEL), then the DAC powered down (DACPD).
  2120. write(WM8731_REG_DIGITAL, 0x08); // DAC soft mute
  2121. write(WM8731_REG_ANALOG, 0x00); // disable all
  2122. write(WM8731_REG_POWERDOWN, 0x00); // codec powerdown
  2123. write(WM8731_REG_LHEADOUT, 0x80); // volume off
  2124. write(WM8731_REG_RHEADOUT, 0x80);
  2125. delay(100); // how long to power up?
  2126. write(WM8731_REG_ACTIVE, 1);
  2127. delay(5);
  2128. write(WM8731_REG_DIGITAL, 0x00); // DAC unmuted
  2129. write(WM8731_REG_ANALOG, 0x10); // DAC selected
  2130. return true;
  2131. }
  2132. bool AudioControlWM8731::write(unsigned int reg, unsigned int val)
  2133. {
  2134. Wire.beginTransmission(WM8731_I2C_ADDR);
  2135. Wire.write((reg << 1) | ((val >> 8) & 1));
  2136. Wire.write(val & 0xFF);
  2137. Wire.endTransmission();
  2138. return true;
  2139. }
  2140. bool AudioControlWM8731::volumeInteger(unsigned int n)
  2141. {
  2142. if (n > 127) n = 127;
  2143. //Serial.print("volumeInteger, n = ");
  2144. //Serial.println(n);
  2145. write(WM8731_REG_LHEADOUT, n | 0x180);
  2146. write(WM8731_REG_RHEADOUT, n | 0x80);
  2147. return true;
  2148. }
  2149. /******************************************************************/
  2150. bool AudioControlWM8731master::enable(void)
  2151. {
  2152. Wire.begin();
  2153. delay(5);
  2154. //write(WM8731_REG_RESET, 0);
  2155. write(WM8731_REG_INTERFACE, 0x42); // I2S, 16 bit, MCLK master
  2156. write(WM8731_REG_SAMPLING, 0x20); // 256*Fs, 44.1 kHz, MCLK/1
  2157. // In order to prevent pops, the DAC should first be soft-muted (DACMU),
  2158. // the output should then be de-selected from the line and headphone output
  2159. // (DACSEL), then the DAC powered down (DACPD).
  2160. write(WM8731_REG_DIGITAL, 0x08); // DAC soft mute
  2161. write(WM8731_REG_ANALOG, 0x00); // disable all
  2162. write(WM8731_REG_POWERDOWN, 0x00); // codec powerdown
  2163. write(WM8731_REG_LHEADOUT, 0x80); // volume off
  2164. write(WM8731_REG_RHEADOUT, 0x80);
  2165. delay(100); // how long to power up?
  2166. write(WM8731_REG_ACTIVE, 1);
  2167. delay(5);
  2168. write(WM8731_REG_DIGITAL, 0x00); // DAC unmuted
  2169. write(WM8731_REG_ANALOG, 0x10); // DAC selected
  2170. return true;
  2171. }
  2172. /******************************************************************/
  2173. #define CHIP_ID 0x0000
  2174. // 15:8 PARTID 0xA0 - 8 bit identifier for SGTL5000
  2175. // 7:0 REVID 0x00 - revision number for SGTL5000.
  2176. #define CHIP_DIG_POWER 0x0002
  2177. // 6 ADC_POWERUP 1=Enable, 0=disable the ADC block, both digital & analog,
  2178. // 5 DAC_POWERUP 1=Enable, 0=disable the DAC block, both analog and digital
  2179. // 4 DAP_POWERUP 1=Enable, 0=disable the DAP block
  2180. // 1 I2S_OUT_POWERUP 1=Enable, 0=disable the I2S data output
  2181. // 0 I2S_IN_POWERUP 1=Enable, 0=disable the I2S data input
  2182. #define CHIP_CLK_CTRL 0x0004
  2183. // 5:4 RATE_MODE Sets the sample rate mode. MCLK_FREQ is still specified
  2184. // relative to the rate in SYS_FS
  2185. // 0x0 = SYS_FS specifies the rate
  2186. // 0x1 = Rate is 1/2 of the SYS_FS rate
  2187. // 0x2 = Rate is 1/4 of the SYS_FS rate
  2188. // 0x3 = Rate is 1/6 of the SYS_FS rate
  2189. // 3:2 SYS_FS Sets the internal system sample rate (default=2)
  2190. // 0x0 = 32 kHz
  2191. // 0x1 = 44.1 kHz
  2192. // 0x2 = 48 kHz
  2193. // 0x3 = 96 kHz
  2194. // 1:0 MCLK_FREQ Identifies incoming SYS_MCLK frequency and if the PLL should be used
  2195. // 0x0 = 256*Fs
  2196. // 0x1 = 384*Fs
  2197. // 0x2 = 512*Fs
  2198. // 0x3 = Use PLL
  2199. // The 0x3 (Use PLL) setting must be used if the SYS_MCLK is not
  2200. // a standard multiple of Fs (256, 384, or 512). This setting can
  2201. // also be used if SYS_MCLK is a standard multiple of Fs.
  2202. // Before this field is set to 0x3 (Use PLL), the PLL must be
  2203. // powered up by setting CHIP_ANA_POWER->PLL_POWERUP and
  2204. // CHIP_ANA_POWER->VCOAMP_POWERUP. Also, the PLL dividers must
  2205. // be calculated based on the external MCLK rate and
  2206. // CHIP_PLL_CTRL register must be set (see CHIP_PLL_CTRL register
  2207. // description details on how to calculate the divisors).
  2208. #define CHIP_I2S_CTRL 0x0006
  2209. // 8 SCLKFREQ Sets frequency of I2S_SCLK when in master mode (MS=1). When in slave
  2210. // mode (MS=0), this field must be set appropriately to match SCLK input
  2211. // rate.
  2212. // 0x0 = 64Fs
  2213. // 0x1 = 32Fs - Not supported for RJ mode (I2S_MODE = 1)
  2214. // 7 MS Configures master or slave of I2S_LRCLK and I2S_SCLK.
  2215. // 0x0 = Slave: I2S_LRCLK an I2S_SCLK are inputs
  2216. // 0x1 = Master: I2S_LRCLK and I2S_SCLK are outputs
  2217. // NOTE: If the PLL is used (CHIP_CLK_CTRL->MCLK_FREQ==0x3),
  2218. // the SGTL5000 must be a master of the I2S port (MS==1)
  2219. // 6 SCLK_INV Sets the edge that data (input and output) is clocked in on for I2S_SCLK
  2220. // 0x0 = data is valid on rising edge of I2S_SCLK
  2221. // 0x1 = data is valid on falling edge of I2S_SCLK
  2222. // 5:4 DLEN I2S data length (default=1)
  2223. // 0x0 = 32 bits (only valid when SCLKFREQ=0),
  2224. // not valid for Right Justified Mode
  2225. // 0x1 = 24 bits (only valid when SCLKFREQ=0)
  2226. // 0x2 = 20 bits
  2227. // 0x3 = 16 bits
  2228. // 3:2 I2S_MODE Sets the mode for the I2S port
  2229. // 0x0 = I2S mode or Left Justified (Use LRALIGN to select)
  2230. // 0x1 = Right Justified Mode
  2231. // 0x2 = PCM Format A/B
  2232. // 0x3 = RESERVED
  2233. // 1 LRALIGN I2S_LRCLK Alignment to data word. Not used for Right Justified mode
  2234. // 0x0 = Data word starts 1 I2S_SCLK delay after I2S_LRCLK
  2235. // transition (I2S format, PCM format A)
  2236. // 0x1 = Data word starts after I2S_LRCLK transition (left
  2237. // justified format, PCM format B)
  2238. // 0 LRPOL I2S_LRCLK Polarity when data is presented.
  2239. // 0x0 = I2S_LRCLK = 0 - Left, 1 - Right
  2240. // 1x0 = I2S_LRCLK = 0 - Right, 1 - Left
  2241. // The left subframe should be presented first regardless of
  2242. // the setting of LRPOL.
  2243. #define CHIP_SSS_CTRL 0x000A
  2244. // 14 DAP_MIX_LRSWAP DAP Mixer Input Swap
  2245. // 0x0 = Normal Operation
  2246. // 0x1 = Left and Right channels for the DAP MIXER Input are swapped.
  2247. // 13 DAP_LRSWAP DAP Mixer Input Swap
  2248. // 0x0 = Normal Operation
  2249. // 0x1 = Left and Right channels for the DAP Input are swapped
  2250. // 12 DAC_LRSWAP DAC Input Swap
  2251. // 0x0 = Normal Operation
  2252. // 0x1 = Left and Right channels for the DAC are swapped
  2253. // 10 I2S_LRSWAP I2S_DOUT Swap
  2254. // 0x0 = Normal Operation
  2255. // 0x1 = Left and Right channels for the I2S_DOUT are swapped
  2256. // 9:8 DAP_MIX_SELECT Select data source for DAP mixer
  2257. // 0x0 = ADC
  2258. // 0x1 = I2S_IN
  2259. // 0x2 = Reserved
  2260. // 0x3 = Reserved
  2261. // 7:6 DAP_SELECT Select data source for DAP
  2262. // 0x0 = ADC
  2263. // 0x1 = I2S_IN
  2264. // 0x2 = Reserved
  2265. // 0x3 = Reserved
  2266. // 5:4 DAC_SELECT Select data source for DAC (default=1)
  2267. // 0x0 = ADC
  2268. // 0x1 = I2S_IN
  2269. // 0x2 = Reserved
  2270. // 0x3 = DAP
  2271. // 1:0 I2S_SELECT Select data source for I2S_DOUT
  2272. // 0x0 = ADC
  2273. // 0x1 = I2S_IN
  2274. // 0x2 = Reserved
  2275. // 0x3 = DAP
  2276. #define CHIP_ADCDAC_CTRL 0x000E
  2277. // 13 VOL_BUSY_DAC_RIGHT Volume Busy DAC Right
  2278. // 0x0 = Ready
  2279. // 0x1 = Busy - This indicates the channel has not reached its
  2280. // programmed volume/mute level
  2281. // 12 VOL_BUSY_DAC_LEFT Volume Busy DAC Left
  2282. // 0x0 = Ready
  2283. // 0x1 = Busy - This indicates the channel has not reached its
  2284. // programmed volume/mute level
  2285. // 9 VOL_RAMP_EN Volume Ramp Enable (default=1)
  2286. // 0x0 = Disables volume ramp. New volume settings take immediate
  2287. // effect without a ramp
  2288. // 0x1 = Enables volume ramp
  2289. // This field affects DAC_VOL. The volume ramp effects both
  2290. // volume settings and mute When set to 1 a soft mute is enabled.
  2291. // 8 VOL_EXPO_RAMP Exponential Volume Ramp Enable
  2292. // 0x0 = Linear ramp over top 4 volume octaves
  2293. // 0x1 = Exponential ramp over full volume range
  2294. // This bit only takes effect if VOL_RAMP_EN is 1.
  2295. // 3 DAC_MUTE_RIGHT DAC Right Mute (default=1)
  2296. // 0x0 = Unmute
  2297. // 0x1 = Muted
  2298. // If VOL_RAMP_EN = 1, this is a soft mute.
  2299. // 2 DAC_MUTE_LEFT DAC Left Mute (default=1)
  2300. // 0x0 = Unmute
  2301. // 0x1 = Muted
  2302. // If VOL_RAMP_EN = 1, this is a soft mute.
  2303. // 1 ADC_HPF_FREEZE ADC High Pass Filter Freeze
  2304. // 0x0 = Normal operation
  2305. // 0x1 = Freeze the ADC high-pass filter offset register. The
  2306. // offset continues to be subtracted from the ADC data stream.
  2307. // 0 ADC_HPF_BYPASS ADC High Pass Filter Bypass
  2308. // 0x0 = Normal operation
  2309. // 0x1 = Bypassed and offset not updated
  2310. #define CHIP_DAC_VOL 0x0010
  2311. // 15:8 DAC_VOL_RIGHT DAC Right Channel Volume. Set the Right channel DAC volume
  2312. // with 0.5017 dB steps from 0 to -90 dB
  2313. // 0x3B and less = Reserved
  2314. // 0x3C = 0 dB
  2315. // 0x3D = -0.5 dB
  2316. // 0xF0 = -90 dB
  2317. // 0xFC and greater = Muted
  2318. // If VOL_RAMP_EN = 1, there is an automatic ramp to the
  2319. // new volume setting.
  2320. // 7:0 DAC_VOL_LEFT DAC Left Channel Volume. Set the Left channel DAC volume
  2321. // with 0.5017 dB steps from 0 to -90 dB
  2322. // 0x3B and less = Reserved
  2323. // 0x3C = 0 dB
  2324. // 0x3D = -0.5 dB
  2325. // 0xF0 = -90 dB
  2326. // 0xFC and greater = Muted
  2327. // If VOL_RAMP_EN = 1, there is an automatic ramp to the
  2328. // new volume setting.
  2329. #define CHIP_PAD_STRENGTH 0x0014
  2330. // 9:8 I2S_LRCLK I2S LRCLK Pad Drive Strength (default=1)
  2331. // Sets drive strength for output pads per the table below.
  2332. // VDDIO 1.8 V 2.5 V 3.3 V
  2333. // 0x0 = Disable
  2334. // 0x1 = 1.66 mA 2.87 mA 4.02 mA
  2335. // 0x2 = 3.33 mA 5.74 mA 8.03 mA
  2336. // 0x3 = 4.99 mA 8.61 mA 12.05 mA
  2337. // 7:6 I2S_SCLK I2S SCLK Pad Drive Strength (default=1)
  2338. // 5:4 I2S_DOUT I2S DOUT Pad Drive Strength (default=1)
  2339. // 3:2 CTRL_DATA I2C DATA Pad Drive Strength (default=3)
  2340. // 1:0 CTRL_CLK I2C CLK Pad Drive Strength (default=3)
  2341. // (all use same table as I2S_LRCLK)
  2342. #define CHIP_ANA_ADC_CTRL 0x0020
  2343. // 8 ADC_VOL_M6DB ADC Volume Range Reduction
  2344. // This bit shifts both right and left analog ADC volume
  2345. // range down by 6.0 dB.
  2346. // 0x0 = No change in ADC range
  2347. // 0x1 = ADC range reduced by 6.0 dB
  2348. // 7:4 ADC_VOL_RIGHT ADC Right Channel Volume
  2349. // Right channel analog ADC volume control in 1.5 dB steps.
  2350. // 0x0 = 0 dB
  2351. // 0x1 = +1.5 dB
  2352. // ...
  2353. // 0xF = +22.5 dB
  2354. // This range is -6.0 dB to +16.5 dB if ADC_VOL_M6DB is set to 1.
  2355. // 3:0 ADC_VOL_LEFT ADC Left Channel Volume
  2356. // (same scale as ADC_VOL_RIGHT)
  2357. #define CHIP_ANA_HP_CTRL 0x0022
  2358. // 14:8 HP_VOL_RIGHT Headphone Right Channel Volume (default 0x18)
  2359. // Right channel headphone volume control with 0.5 dB steps.
  2360. // 0x00 = +12 dB
  2361. // 0x01 = +11.5 dB
  2362. // 0x18 = 0 dB
  2363. // ...
  2364. // 0x7F = -51.5 dB
  2365. // 6:0 HP_VOL_LEFT Headphone Left Channel Volume (default 0x18)
  2366. // (same scale as HP_VOL_RIGHT)
  2367. #define CHIP_ANA_CTRL 0x0024
  2368. // 8 MUTE_LO LINEOUT Mute, 0 = Unmute, 1 = Mute (default 1)
  2369. // 6 SELECT_HP Select the headphone input, 0 = DAC, 1 = LINEIN
  2370. // 5 EN_ZCD_HP Enable the headphone zero cross detector (ZCD)
  2371. // 0x0 = HP ZCD disabled
  2372. // 0x1 = HP ZCD enabled
  2373. // 4 MUTE_HP Mute the headphone outputs, 0 = Unmute, 1 = Mute (default)
  2374. // 2 SELECT_ADC Select the ADC input, 0 = Microphone, 1 = LINEIN
  2375. // 1 EN_ZCD_ADC Enable the ADC analog zero cross detector (ZCD)
  2376. // 0x0 = ADC ZCD disabled
  2377. // 0x1 = ADC ZCD enabled
  2378. // 0 MUTE_ADC Mute the ADC analog volume, 0 = Unmute, 1 = Mute (default)
  2379. #define CHIP_LINREG_CTRL 0x0026
  2380. // 6 VDDC_MAN_ASSN Determines chargepump source when VDDC_ASSN_OVRD is set.
  2381. // 0x0 = VDDA
  2382. // 0x1 = VDDIO
  2383. // 5 VDDC_ASSN_OVRD Charge pump Source Assignment Override
  2384. // 0x0 = Charge pump source is automatically assigned based
  2385. // on higher of VDDA and VDDIO
  2386. // 0x1 = the source of charge pump is manually assigned by
  2387. // VDDC_MAN_ASSN If VDDIO and VDDA are both the same
  2388. // and greater than 3.1 V, VDDC_ASSN_OVRD and
  2389. // VDDC_MAN_ASSN should be used to manually assign
  2390. // VDDIO as the source for charge pump.
  2391. // 3:0 D_PROGRAMMING Sets the VDDD linear regulator output voltage in 50 mV steps.
  2392. // Must clear the LINREG_SIMPLE_POWERUP and STARTUP_POWERUP bits
  2393. // in the 0x0030 (CHIP_ANA_POWER) register after power-up, for
  2394. // this setting to produce the proper VDDD voltage.
  2395. // 0x0 = 1.60
  2396. // 0xF = 0.85
  2397. #define CHIP_REF_CTRL 0x0028 // bandgap reference bias voltage and currents
  2398. // 8:4 VAG_VAL Analog Ground Voltage Control
  2399. // These bits control the analog ground voltage in 25 mV steps.
  2400. // This should usually be set to VDDA/2 or lower for best
  2401. // performance (maximum output swing at minimum THD). This VAG
  2402. // reference is also used for the DAC and ADC voltage reference.
  2403. // So changing this voltage scales the output swing of the DAC
  2404. // and the output signal of the ADC.
  2405. // 0x00 = 0.800 V
  2406. // 0x1F = 1.575 V
  2407. // 3:1 BIAS_CTRL Bias control
  2408. // These bits adjust the bias currents for all of the analog
  2409. // blocks. By lowering the bias current a lower quiescent power
  2410. // is achieved. It should be noted that this mode can affect
  2411. // performance by 3-4 dB.
  2412. // 0x0 = Nominal
  2413. // 0x1-0x3=+12.5%
  2414. // 0x4=-12.5%
  2415. // 0x5=-25%
  2416. // 0x6=-37.5%
  2417. // 0x7=-50%
  2418. // 0 SMALL_POP VAG Ramp Control
  2419. // Setting this bit slows down the VAG ramp from ~200 to ~400 ms
  2420. // to reduce the startup pop, but increases the turn on/off time.
  2421. // 0x0 = Normal VAG ramp
  2422. // 0x1 = Slow down VAG ramp
  2423. #define CHIP_MIC_CTRL 0x002A // microphone gain & internal microphone bias
  2424. // 9:8 BIAS_RESISTOR MIC Bias Output Impedance Adjustment
  2425. // Controls an adjustable output impedance for the microphone bias.
  2426. // If this is set to zero the micbias block is powered off and
  2427. // the output is highZ.
  2428. // 0x0 = Powered off
  2429. // 0x1 = 2.0 kohm
  2430. // 0x2 = 4.0 kohm
  2431. // 0x3 = 8.0 kohm
  2432. // 6:4 BIAS_VOLT MIC Bias Voltage Adjustment
  2433. // Controls an adjustable bias voltage for the microphone bias
  2434. // amp in 250 mV steps. This bias voltage setting should be no
  2435. // more than VDDA-200 mV for adequate power supply rejection.
  2436. // 0x0 = 1.25 V
  2437. // ...
  2438. // 0x7 = 3.00 V
  2439. // 1:0 GAIN MIC Amplifier Gain
  2440. // Sets the microphone amplifier gain. At 0 dB setting the THD
  2441. // can be slightly higher than other paths- typically around
  2442. // ~65 dB. At other gain settings the THD are better.
  2443. // 0x0 = 0 dB
  2444. // 0x1 = +20 dB
  2445. // 0x2 = +30 dB
  2446. // 0x3 = +40 dB
  2447. #define CHIP_LINE_OUT_CTRL 0x002C
  2448. // 11:8 OUT_CURRENT Controls the output bias current for the LINEOUT amplifiers. The
  2449. // nominal recommended setting for a 10 kohm load with 1.0 nF load cap
  2450. // is 0x3. There are only 5 valid settings.
  2451. // 0x0=0.18 mA
  2452. // 0x1=0.27 mA
  2453. // 0x3=0.36 mA
  2454. // 0x7=0.45 mA
  2455. // 0xF=0.54 mA
  2456. // 5:0 LO_VAGCNTRL LINEOUT Amplifier Analog Ground Voltage
  2457. // Controls the analog ground voltage for the LINEOUT amplifiers
  2458. // in 25 mV steps. This should usually be set to VDDIO/2.
  2459. // 0x00 = 0.800 V
  2460. // ...
  2461. // 0x1F = 1.575 V
  2462. // ...
  2463. // 0x23 = 1.675 V
  2464. // 0x24-0x3F are invalid
  2465. #define CHIP_LINE_OUT_VOL 0x002E
  2466. // 12:8 LO_VOL_RIGHT LINEOUT Right Channel Volume (default=4)
  2467. // Controls the right channel LINEOUT volume in 0.5 dB steps.
  2468. // Higher codes have more attenuation.
  2469. // 4:0 LO_VOL_LEFT LINEOUT Left Channel Output Level (default=4)
  2470. // Used to normalize the output level of the left line output
  2471. // to full scale based on the values used to set
  2472. // LINE_OUT_CTRL->LO_VAGCNTRL and CHIP_REF_CTRL->VAG_VAL.
  2473. // In general this field should be set to:
  2474. // 40*log((VAG_VAL)/(LO_VAGCNTRL)) + 15
  2475. // Suggested values based on typical VDDIO and VDDA voltages.
  2476. // VDDA VAG_VAL VDDIO LO_VAGCNTRL LO_VOL_*
  2477. // 1.8 V 0.9 3.3 V 1.55 0x06
  2478. // 1.8 V 0.9 1.8 V 0.9 0x0F
  2479. // 3.3 V 1.55 1.8 V 0.9 0x19
  2480. // 3.3 V 1.55 3.3 V 1.55 0x0F
  2481. // After setting to the nominal voltage, this field can be used
  2482. // to adjust the output level in +/-0.5 dB increments by using
  2483. // values higher or lower than the nominal setting.
  2484. #define CHIP_ANA_POWER 0x0030 // power down controls for the analog blocks.
  2485. // The only other power-down controls are BIAS_RESISTOR in the MIC_CTRL register
  2486. // and the EN_ZCD control bits in ANA_CTRL.
  2487. // 14 DAC_MONO While DAC_POWERUP is set, this allows the DAC to be put into left only
  2488. // mono operation for power savings. 0=mono, 1=stereo (default)
  2489. // 13 LINREG_SIMPLE_POWERUP Power up the simple (low power) digital supply regulator.
  2490. // After reset, this bit can be cleared IF VDDD is driven
  2491. // externally OR the primary digital linreg is enabled with
  2492. // LINREG_D_POWERUP
  2493. // 12 STARTUP_POWERUP Power up the circuitry needed during the power up ramp and reset.
  2494. // After reset this bit can be cleared if VDDD is coming from
  2495. // an external source.
  2496. // 11 VDDC_CHRGPMP_POWERUP Power up the VDDC charge pump block. If neither VDDA or VDDIO
  2497. // is 3.0 V or larger this bit should be cleared before analog
  2498. // blocks are powered up.
  2499. // 10 PLL_POWERUP PLL Power Up, 0 = Power down, 1 = Power up
  2500. // When cleared, the PLL is turned off. This must be set before
  2501. // CHIP_CLK_CTRL->MCLK_FREQ is programmed to 0x3. The
  2502. // CHIP_PLL_CTRL register must be configured correctly before
  2503. // setting this bit.
  2504. // 9 LINREG_D_POWERUP Power up the primary VDDD linear regulator, 0 = Power down, 1 = Power up
  2505. // 8 VCOAMP_POWERUP Power up the PLL VCO amplifier, 0 = Power down, 1 = Power up
  2506. // 7 VAG_POWERUP Power up the VAG reference buffer.
  2507. // Setting this bit starts the power up ramp for the headphone
  2508. // and LINEOUT. The headphone (and/or LINEOUT) powerup should
  2509. // be set BEFORE clearing this bit. When this bit is cleared
  2510. // the power-down ramp is started. The headphone (and/or LINEOUT)
  2511. // powerup should stay set until the VAG is fully ramped down
  2512. // (200 to 400 ms after clearing this bit).
  2513. // 0x0 = Power down, 0x1 = Power up
  2514. // 6 ADC_MONO While ADC_POWERUP is set, this allows the ADC to be put into left only
  2515. // mono operation for power savings. This mode is useful when
  2516. // only using the microphone input.
  2517. // 0x0 = Mono (left only), 0x1 = Stereo
  2518. // 5 REFTOP_POWERUP Power up the reference bias currents
  2519. // 0x0 = Power down, 0x1 = Power up
  2520. // This bit can be cleared when the part is a sleep state
  2521. // to minimize analog power.
  2522. // 4 HEADPHONE_POWERUP Power up the headphone amplifiers
  2523. // 0x0 = Power down, 0x1 = Power up
  2524. // 3 DAC_POWERUP Power up the DACs
  2525. // 0x0 = Power down, 0x1 = Power up
  2526. // 2 CAPLESS_HEADPHONE_POWERUP Power up the capless headphone mode
  2527. // 0x0 = Power down, 0x1 = Power up
  2528. // 1 ADC_POWERUP Power up the ADCs
  2529. // 0x0 = Power down, 0x1 = Power up
  2530. // 0 LINEOUT_POWERUP Power up the LINEOUT amplifiers
  2531. // 0x0 = Power down, 0x1 = Power up
  2532. #define CHIP_PLL_CTRL 0x0032
  2533. // 15:11 INT_DIVISOR
  2534. // 10:0 FRAC_DIVISOR
  2535. #define CHIP_CLK_TOP_CTRL 0x0034
  2536. // 11 ENABLE_INT_OSC Setting this bit enables an internal oscillator to be used for the
  2537. // zero cross detectors, the short detect recovery, and the
  2538. // charge pump. This allows the I2S clock to be shut off while
  2539. // still operating an analog signal path. This bit can be kept
  2540. // on when the I2S clock is enabled, but the I2S clock is more
  2541. // accurate so it is preferred to clear this bit when I2S is present.
  2542. // 3 INPUT_FREQ_DIV2 SYS_MCLK divider before PLL input
  2543. // 0x0 = pass through
  2544. // 0x1 = SYS_MCLK is divided by 2 before entering PLL
  2545. // This must be set when the input clock is above 17 Mhz. This
  2546. // has no effect when the PLL is powered down.
  2547. #define CHIP_ANA_STATUS 0x0036
  2548. // 9 LRSHORT_STS This bit is high whenever a short is detected on the left or right
  2549. // channel headphone drivers.
  2550. // 8 CSHORT_STS This bit is high whenever a short is detected on the capless headphone
  2551. // common/center channel driver.
  2552. // 4 PLL_IS_LOCKED This bit goes high after the PLL is locked.
  2553. #define CHIP_ANA_TEST1 0x0038 // intended only for debug.
  2554. #define CHIP_ANA_TEST2 0x003A // intended only for debug.
  2555. #define CHIP_SHORT_CTRL 0x003C
  2556. // 14:12 LVLADJR Right channel headphone short detector in 25 mA steps.
  2557. // 0x3=25 mA
  2558. // 0x2=50 mA
  2559. // 0x1=75 mA
  2560. // 0x0=100 mA
  2561. // 0x4=125 mA
  2562. // 0x5=150 mA
  2563. // 0x6=175 mA
  2564. // 0x7=200 mA
  2565. // This trip point can vary by ~30% over process so leave plenty
  2566. // of guard band to avoid false trips. This short detect trip
  2567. // point is also effected by the bias current adjustments made
  2568. // by CHIP_REF_CTRL->BIAS_CTRL and by CHIP_ANA_TEST1->HP_IALL_ADJ.
  2569. // 10:8 LVLADJL Left channel headphone short detector in 25 mA steps.
  2570. // (same scale as LVLADJR)
  2571. // 6:4 LVLADJC Capless headphone center channel short detector in 50 mA steps.
  2572. // 0x3=50 mA
  2573. // 0x2=100 mA
  2574. // 0x1=150 mA
  2575. // 0x0=200 mA
  2576. // 0x4=250 mA
  2577. // 0x5=300 mA
  2578. // 0x6=350 mA
  2579. // 0x7=400 mA
  2580. // 3:2 MODE_LR Behavior of left/right short detection
  2581. // 0x0 = Disable short detector, reset short detect latch,
  2582. // software view non-latched short signal
  2583. // 0x1 = Enable short detector and reset the latch at timeout
  2584. // (every ~50 ms)
  2585. // 0x2 = This mode is not used/invalid
  2586. // 0x3 = Enable short detector with only manual reset (have
  2587. // to return to 0x0 to reset the latch)
  2588. // 1:0 MODE_CM Behavior of capless headphone central short detection
  2589. // (same settings as MODE_LR)
  2590. #define DAP_CONTROL 0x0100
  2591. #define DAP_PEQ 0x0102
  2592. #define DAP_BASS_ENHANCE 0x0104
  2593. #define DAP_BASS_ENHANCE_CTRL 0x0106
  2594. #define DAP_AUDIO_EQ 0x0108
  2595. #define DAP_SGTL_SURROUND 0x010A
  2596. #define DAP_FILTER_COEF_ACCES 0x010C
  2597. #define DAP_COEF_WR_B0_MSB 0x010E
  2598. #define DAP_COEF_WR_B0_LSB 0x0110
  2599. #define DAP_AUDIO_EQ_BASS_BAND0 0x0116 // 115 Hz
  2600. #define DAP_AUDIO_EQ_BAND1 0x0118 // 330 Hz
  2601. #define DAP_AUDIO_EQ_BAND2 0x011A // 990 Hz
  2602. #define DAP_AUDIO_EQ_BAND3 0x011C // 3000 Hz
  2603. #define DAP_AUDIO_EQ_TREBLE_BAND4 0x011E // 9900 Hz
  2604. #define DAP_MAIN_CHAN 0x0120
  2605. #define DAP_MIX_CHAN 0x0122
  2606. #define DAP_AVC_CTRL 0x0124
  2607. #define DAP_AVC_THRESHOLD 0x0126
  2608. #define DAP_AVC_ATTACK 0x0128
  2609. #define DAP_AVC_DECAY 0x012A
  2610. #define DAP_COEF_WR_B1_MSB 0x012C
  2611. #define DAP_COEF_WR_B1_LSB 0x012E
  2612. #define DAP_COEF_WR_B2_MSB 0x0130
  2613. #define DAP_COEF_WR_B2_LSB 0x0132
  2614. #define DAP_COEF_WR_A1_MSB 0x0134
  2615. #define DAP_COEF_WR_A1_LSB 0x0136
  2616. #define DAP_COEF_WR_A2_MSB 0x0138
  2617. #define DAP_COEF_WR_A2_LSB 0x013A
  2618. #define SGTL5000_I2C_ADDR 0x0A // CTRL_ADR0_CS pin low (normal configuration)
  2619. //#define SGTL5000_I2C_ADDR 0x2A // CTRL_ADR0_CS pin high
  2620. bool AudioControlSGTL5000::enable(void)
  2621. {
  2622. //unsigned int n;
  2623. muted = true;
  2624. Wire.begin();
  2625. delay(5);
  2626. //Serial.print("chip ID = ");
  2627. //delay(5);
  2628. //n = read(CHIP_ID);
  2629. //Serial.println(n, HEX);
  2630. write(CHIP_ANA_POWER, 0x4060); // VDDD is externally driven with 1.8V
  2631. write(CHIP_LINREG_CTRL, 0x006C); // VDDA & VDDIO both over 3.1V
  2632. write(CHIP_REF_CTRL, 0x01F1); // VAG=1.575 slow ramp, normal bias current
  2633. write(CHIP_LINE_OUT_CTRL, 0x0322);
  2634. write(CHIP_SHORT_CTRL, 0x4446); // allow up to 125mA
  2635. write(CHIP_ANA_CTRL, 0x0137); // enable zero cross detectors
  2636. write(CHIP_ANA_POWER, 0x40FF); // power up: lineout, hp, adc, dac
  2637. write(CHIP_DIG_POWER, 0x0073); // power up all digital stuff
  2638. delay(400);
  2639. write(CHIP_LINE_OUT_VOL, 0x0505); // TODO: correct value for 3.3V
  2640. write(CHIP_CLK_CTRL, 0x0004); // 44.1 kHz, 256*Fs
  2641. write(CHIP_I2S_CTRL, 0x0130); // SCLK=32*Fs, 16bit, I2S format
  2642. // default signal routing is ok?
  2643. write(CHIP_SSS_CTRL, 0x0010); // ADC->I2S, I2S->DAC
  2644. write(CHIP_ADCDAC_CTRL, 0x0000); // disable dac mute
  2645. write(CHIP_DAC_VOL, 0x3C3C); // digital gain, 0dB
  2646. write(CHIP_ANA_HP_CTRL, 0x7F7F); // set volume (lowest level)
  2647. write(CHIP_ANA_CTRL, 0x0136); // enable zero cross detectors
  2648. //mute = false;
  2649. return true;
  2650. }
  2651. unsigned int AudioControlSGTL5000::read(unsigned int reg)
  2652. {
  2653. unsigned int val;
  2654. Wire.beginTransmission(SGTL5000_I2C_ADDR);
  2655. Wire.write(reg >> 8);
  2656. Wire.write(reg);
  2657. if (Wire.endTransmission(false) != 0) return 0;
  2658. if (Wire.requestFrom(SGTL5000_I2C_ADDR, 2) < 2) return 0;
  2659. val = Wire.read() << 8;
  2660. val |= Wire.read();
  2661. return val;
  2662. }
  2663. bool AudioControlSGTL5000::write(unsigned int reg, unsigned int val)
  2664. {
  2665. if (reg == CHIP_ANA_CTRL) ana_ctrl = val;
  2666. Wire.beginTransmission(SGTL5000_I2C_ADDR);
  2667. Wire.write(reg >> 8);
  2668. Wire.write(reg);
  2669. Wire.write(val >> 8);
  2670. Wire.write(val);
  2671. if (Wire.endTransmission() == 0) return true;
  2672. return false;
  2673. }
  2674. bool AudioControlSGTL5000::volumeInteger(unsigned int n)
  2675. {
  2676. if (n == 0) {
  2677. muted = true;
  2678. write(CHIP_ANA_HP_CTRL, 0x7F7F);
  2679. return muteHeadphone();
  2680. } else if (n > 0x80) {
  2681. n = 0;
  2682. } else {
  2683. n = 0x80 - n;
  2684. }
  2685. if (muted) {
  2686. muted = false;
  2687. unmuteHeadphone();
  2688. }
  2689. n = n | (n << 8);
  2690. return write(CHIP_ANA_HP_CTRL, n); // set volume
  2691. }
  2692. /******************************************************************/
  2693. // arm state arrays and FIR instances for left and right channels
  2694. // the state arrays are defined to handle a maximum of MAX_COEFFS
  2695. // coefficients in a filter
  2696. q15_t AudioFilterFIR::l_StateQ15[AUDIO_BLOCK_SAMPLES + MAX_COEFFS];
  2697. q15_t AudioFilterFIR::r_StateQ15[AUDIO_BLOCK_SAMPLES + MAX_COEFFS];
  2698. arm_fir_instance_q15 AudioFilterFIR::l_fir_inst;
  2699. arm_fir_instance_q15 AudioFilterFIR::r_fir_inst;
  2700. // pointer to current coefficients or NULL or FIR_PASSTHRU
  2701. short * AudioFilterFIR::coeff_p = NULL;
  2702. void AudioFilterFIR::begin(short *cp,int n_coeffs)
  2703. {
  2704. // pointer to coefficients
  2705. coeff_p = cp;
  2706. // Initialize FIR instances for the left and right channels
  2707. if(coeff_p && (coeff_p != FIR_PASSTHRU)) {
  2708. arm_fir_init_q15(&l_fir_inst, n_coeffs, coeff_p, &l_StateQ15[0], AUDIO_BLOCK_SAMPLES);
  2709. arm_fir_init_q15(&r_fir_inst, n_coeffs, coeff_p, &r_StateQ15[0], AUDIO_BLOCK_SAMPLES);
  2710. }
  2711. }
  2712. // This has the same effect as begin(NULL,0);
  2713. void AudioFilterFIR::stop(void)
  2714. {
  2715. coeff_p = NULL;
  2716. }
  2717. void AudioFilterFIR::update(void)
  2718. {
  2719. audio_block_t *block,*b_new;
  2720. // If there's no coefficient table, give up.
  2721. if(coeff_p == NULL)return;
  2722. // do passthru
  2723. if(coeff_p == FIR_PASSTHRU) {
  2724. // Just passthrough
  2725. block = receiveWritable(0);
  2726. if(block) {
  2727. transmit(block,0);
  2728. release(block);
  2729. }
  2730. block = receiveWritable(1);
  2731. if(block) {
  2732. transmit(block,1);
  2733. release(block);
  2734. }
  2735. return;
  2736. }
  2737. // Left Channel
  2738. block = receiveWritable(0);
  2739. // get a block for the FIR output
  2740. b_new = allocate();
  2741. if(block && b_new) {
  2742. arm_fir_q15(&l_fir_inst, (q15_t *)block->data, (q15_t *)b_new->data, AUDIO_BLOCK_SAMPLES);
  2743. // send the FIR output to the left channel
  2744. transmit(b_new,0);
  2745. }
  2746. if(block)release(block);
  2747. if(b_new)release(b_new);
  2748. // Right Channel
  2749. block = receiveWritable(1);
  2750. b_new = allocate();
  2751. if(block && b_new) {
  2752. arm_fir_q15(&r_fir_inst, (q15_t *)block->data, (q15_t *)b_new->data, AUDIO_BLOCK_SAMPLES);
  2753. transmit(b_new,1);
  2754. }
  2755. if(block)release(block);
  2756. if(b_new)release(b_new);
  2757. }
  2758. /******************************************************************/
  2759. // A u d i o E f f e c t F l a n g e
  2760. // Written by Pete (El Supremo) Jan 2014
  2761. // circular addressing indices for left and right channels
  2762. short AudioEffectFlange::l_circ_idx;
  2763. short AudioEffectFlange::r_circ_idx;
  2764. short * AudioEffectFlange::l_delayline = NULL;
  2765. short * AudioEffectFlange::r_delayline = NULL;
  2766. // User-supplied offset for the delayed sample
  2767. // but start with passthru
  2768. int AudioEffectFlange::delay_offset_idx = DELAY_PASSTHRU;
  2769. int AudioEffectFlange::delay_length;
  2770. int AudioEffectFlange::delay_depth;
  2771. int AudioEffectFlange::delay_rate_incr;
  2772. unsigned int AudioEffectFlange::l_delay_rate_index;
  2773. unsigned int AudioEffectFlange::r_delay_rate_index;
  2774. // fails if the user provides unreasonable values but will
  2775. // coerce them and go ahead anyway. e.g. if the delay offset
  2776. // is >= CHORUS_DELAY_LENGTH, the code will force it to
  2777. // CHORUS_DELAY_LENGTH-1 and return false.
  2778. // delay_rate is the rate (in Hz) of the sine wave modulation
  2779. // delay_depth is the maximum variation around delay_offset
  2780. // i.e. the total offset is delay_offset + delay_depth * sin(delay_rate)
  2781. boolean AudioEffectFlange::begin(short *delayline,int d_length,int delay_offset,int d_depth,float delay_rate)
  2782. {
  2783. boolean all_ok = true;
  2784. Serial.print("AudioEffectFlange.begin(ofsset = ");
  2785. Serial.print(delay_offset);
  2786. Serial.print(", depth = ");
  2787. Serial.print(d_depth);
  2788. Serial.print(", rate = ");
  2789. Serial.print(delay_rate,3);
  2790. Serial.println(")");
  2791. Serial.print(" CHORUS_DELAY_LENGTH = ");
  2792. Serial.println(d_length);
  2793. delay_length = d_length/2;
  2794. l_delayline = delayline;
  2795. r_delayline = delayline + delay_length;
  2796. delay_depth = d_depth;
  2797. // initial index
  2798. l_delay_rate_index = 0;
  2799. r_delay_rate_index = 0;
  2800. l_circ_idx = 0;
  2801. r_circ_idx = 0;
  2802. delay_rate_incr = 2*PI*delay_rate/44100.*2147483648.;
  2803. //Serial.println(delay_rate_incr,HEX);
  2804. delay_offset_idx = delay_offset;
  2805. // Allow the passthru code to go through
  2806. if(delay_offset_idx < -1) {
  2807. delay_offset_idx = 0;
  2808. all_ok = false;
  2809. }
  2810. if(delay_offset_idx >= delay_length) {
  2811. delay_offset_idx = delay_length - 1;
  2812. all_ok = false;
  2813. }
  2814. return(all_ok);
  2815. }
  2816. boolean AudioEffectFlange::modify(int delay_offset,int d_depth,float delay_rate)
  2817. {
  2818. boolean all_ok = true;
  2819. delay_depth = d_depth;
  2820. delay_rate_incr = 2*PI*delay_rate/44100.*2147483648.;
  2821. delay_offset_idx = delay_offset;
  2822. // Allow the passthru code to go through
  2823. if(delay_offset_idx < -1) {
  2824. delay_offset_idx = 0;
  2825. all_ok = false;
  2826. }
  2827. if(delay_offset_idx >= delay_length) {
  2828. delay_offset_idx = delay_length - 1;
  2829. all_ok = false;
  2830. }
  2831. l_delay_rate_index = 0;
  2832. r_delay_rate_index = 0;
  2833. l_circ_idx = 0;
  2834. r_circ_idx = 0;
  2835. return(all_ok);
  2836. }
  2837. void AudioEffectFlange::update(void)
  2838. {
  2839. audio_block_t *block;
  2840. int idx;
  2841. short *bp;
  2842. short frac;
  2843. int idx1;
  2844. if(l_delayline == NULL)return;
  2845. if(r_delayline == NULL)return;
  2846. // do passthru
  2847. if(delay_offset_idx == DELAY_PASSTHRU) {
  2848. // Just passthrough
  2849. block = receiveWritable(0);
  2850. if(block) {
  2851. bp = block->data;
  2852. for(int i = 0;i < AUDIO_BLOCK_SAMPLES;i++) {
  2853. l_circ_idx++;
  2854. if(l_circ_idx >= delay_length) {
  2855. l_circ_idx = 0;
  2856. }
  2857. l_delayline[l_circ_idx] = *bp++;
  2858. }
  2859. transmit(block,0);
  2860. release(block);
  2861. }
  2862. block = receiveWritable(1);
  2863. if(block) {
  2864. bp = block->data;
  2865. for(int i = 0;i < AUDIO_BLOCK_SAMPLES;i++) {
  2866. r_circ_idx++;
  2867. if(r_circ_idx >= delay_length) {
  2868. r_circ_idx = 0;
  2869. }
  2870. r_delayline[r_circ_idx] = *bp++;
  2871. }
  2872. transmit(block,1);
  2873. release(block);
  2874. }
  2875. return;
  2876. }
  2877. // L E F T C H A N N E L
  2878. block = receiveWritable(0);
  2879. if(block) {
  2880. bp = block->data;
  2881. for(int i = 0;i < AUDIO_BLOCK_SAMPLES;i++) {
  2882. l_circ_idx++;
  2883. if(l_circ_idx >= delay_length) {
  2884. l_circ_idx = 0;
  2885. }
  2886. l_delayline[l_circ_idx] = *bp;
  2887. idx = arm_sin_q15( (q15_t)((l_delay_rate_index >> 16) & 0x7fff));
  2888. idx = (idx * delay_depth) >> 15;
  2889. //Serial.println(idx);
  2890. idx = l_circ_idx - (delay_offset_idx + idx);
  2891. if(idx < 0) {
  2892. idx += delay_length;
  2893. }
  2894. if(idx >= delay_length) {
  2895. idx -= delay_length;
  2896. }
  2897. if(frac < 0)
  2898. idx1 = idx - 1;
  2899. else
  2900. idx1 = idx + 1;
  2901. if(idx1 < 0) {
  2902. idx1 += delay_length;
  2903. }
  2904. if(idx1 >= delay_length) {
  2905. idx1 -= delay_length;
  2906. }
  2907. frac = (l_delay_rate_index >> 1) &0x7fff;
  2908. frac = (( (int)(l_delayline[idx1] - l_delayline[idx])*frac) >> 15);
  2909. //frac = 0;
  2910. *bp++ = (l_delayline[l_circ_idx]
  2911. + l_delayline[idx] + frac
  2912. // + l_delayline[(l_circ_idx + delay_length/2) % delay_length]
  2913. )/2;
  2914. l_delay_rate_index += delay_rate_incr;
  2915. if(l_delay_rate_index & 0x80000000) {
  2916. l_delay_rate_index &= 0x7fffffff;
  2917. }
  2918. }
  2919. // send the effect output to the left channel
  2920. transmit(block,0);
  2921. release(block);
  2922. }
  2923. // R I G H T C H A N N E L
  2924. block = receiveWritable(1);
  2925. if(block) {
  2926. bp = block->data;
  2927. for(int i = 0;i < AUDIO_BLOCK_SAMPLES;i++) {
  2928. r_circ_idx++;
  2929. if(r_circ_idx >= delay_length) {
  2930. r_circ_idx = 0;
  2931. }
  2932. r_delayline[r_circ_idx] = *bp;
  2933. idx = arm_sin_q15( (q15_t)((r_delay_rate_index >> 16)&0x7fff));
  2934. idx = (idx * delay_depth) >> 15;
  2935. idx = r_circ_idx - (delay_offset_idx + idx);
  2936. if(idx < 0) {
  2937. idx += delay_length;
  2938. }
  2939. if(idx >= delay_length) {
  2940. idx -= delay_length;
  2941. }
  2942. if(frac < 0)
  2943. idx1 = idx - 1;
  2944. else
  2945. idx1 = idx + 1;
  2946. if(idx1 < 0) {
  2947. idx1 += delay_length;
  2948. }
  2949. if(idx1 >= delay_length) {
  2950. idx1 -= delay_length;
  2951. }
  2952. frac = (r_delay_rate_index >> 1) &0x7fff;
  2953. frac = (( (int)(r_delayline[idx1] - r_delayline[idx])*frac) >> 15);
  2954. //frac = 0;
  2955. *bp++ = (r_delayline[r_circ_idx]
  2956. + r_delayline[idx] + frac
  2957. )/2;
  2958. r_delay_rate_index += delay_rate_incr;
  2959. if(r_delay_rate_index & 0x80000000) {
  2960. r_delay_rate_index &= 0x7fffffff;
  2961. }
  2962. }
  2963. // send the effect output to the right channel
  2964. transmit(block,1);
  2965. release(block);
  2966. }
  2967. }
  2968. /******************************************************************/
  2969. // A u d i o E f f e c t C h o r u s
  2970. // Written by Pete (El Supremo) Jan 2014
  2971. // circular addressing indices for left and right channels
  2972. short AudioEffectChorus::l_circ_idx;
  2973. short AudioEffectChorus::r_circ_idx;
  2974. short * AudioEffectChorus::l_delayline = NULL;
  2975. short * AudioEffectChorus::r_delayline = NULL;
  2976. int AudioEffectChorus::delay_length;
  2977. // An initial value of zero indicates passthru
  2978. int AudioEffectChorus::num_chorus = 0;
  2979. // All three must be valid.
  2980. boolean AudioEffectChorus::begin(short *delayline,int d_length,int n_chorus)
  2981. {
  2982. Serial.print("AudioEffectChorus.begin(Chorus delay line length = ");
  2983. Serial.print(d_length);
  2984. Serial.print(", n_chorus = ");
  2985. Serial.print(n_chorus);
  2986. Serial.println(")");
  2987. l_delayline = NULL;
  2988. r_delayline = NULL;
  2989. delay_length = 0;
  2990. l_circ_idx = 0;
  2991. r_circ_idx = 0;
  2992. if(delayline == NULL) {
  2993. return(false);
  2994. }
  2995. if(d_length < 10) {
  2996. return(false);
  2997. }
  2998. if(n_chorus < 1) {
  2999. return(false);
  3000. }
  3001. l_delayline = delayline;
  3002. r_delayline = delayline + d_length/2;
  3003. delay_length = d_length/2;
  3004. num_chorus = n_chorus;
  3005. return(true);
  3006. }
  3007. // This has the same effect as begin(NULL,0);
  3008. void AudioEffectChorus::stop(void)
  3009. {
  3010. }
  3011. void AudioEffectChorus::modify(int n_chorus)
  3012. {
  3013. num_chorus = n_chorus;
  3014. }
  3015. int iabs(int x)
  3016. {
  3017. if(x < 0)return(-x);
  3018. return(x);
  3019. }
  3020. //static int d_count = 0;
  3021. int last_idx = 0;
  3022. void AudioEffectChorus::update(void)
  3023. {
  3024. audio_block_t *block;
  3025. short *bp;
  3026. int sum;
  3027. int c_idx;
  3028. if(l_delayline == NULL)return;
  3029. if(r_delayline == NULL)return;
  3030. // do passthru
  3031. // It stores the unmodified data in the delay line so that
  3032. // it isn't as likely to click
  3033. if(num_chorus < 1) {
  3034. // Just passthrough
  3035. block = receiveWritable(0);
  3036. if(block) {
  3037. bp = block->data;
  3038. for(int i = 0;i < AUDIO_BLOCK_SAMPLES;i++) {
  3039. l_circ_idx++;
  3040. if(l_circ_idx >= delay_length) {
  3041. l_circ_idx = 0;
  3042. }
  3043. l_delayline[l_circ_idx] = *bp++;
  3044. }
  3045. transmit(block,0);
  3046. release(block);
  3047. }
  3048. block = receiveWritable(1);
  3049. if(block) {
  3050. bp = block->data;
  3051. for(int i = 0;i < AUDIO_BLOCK_SAMPLES;i++) {
  3052. r_circ_idx++;
  3053. if(r_circ_idx >= delay_length) {
  3054. r_circ_idx = 0;
  3055. }
  3056. r_delayline[r_circ_idx] = *bp++;
  3057. }
  3058. transmit(block,1);
  3059. release(block);
  3060. }
  3061. return;
  3062. }
  3063. // L E F T C H A N N E L
  3064. block = receiveWritable(0);
  3065. if(block) {
  3066. bp = block->data;
  3067. for(int i = 0;i < AUDIO_BLOCK_SAMPLES;i++) {
  3068. l_circ_idx++;
  3069. if(l_circ_idx >= delay_length) {
  3070. l_circ_idx = 0;
  3071. }
  3072. l_delayline[l_circ_idx] = *bp;
  3073. sum = 0;
  3074. c_idx = l_circ_idx;
  3075. for(int k = 0; k < num_chorus; k++) {
  3076. sum += l_delayline[c_idx];
  3077. if(num_chorus > 1)c_idx -= delay_length/(num_chorus - 1) - 1;
  3078. if(c_idx < 0) {
  3079. c_idx += delay_length;
  3080. }
  3081. }
  3082. *bp++ = sum/num_chorus;
  3083. }
  3084. // send the effect output to the left channel
  3085. transmit(block,0);
  3086. release(block);
  3087. }
  3088. // R I G H T C H A N N E L
  3089. block = receiveWritable(1);
  3090. if(block) {
  3091. bp = block->data;
  3092. for(int i = 0;i < AUDIO_BLOCK_SAMPLES;i++) {
  3093. r_circ_idx++;
  3094. if(r_circ_idx >= delay_length) {
  3095. r_circ_idx = 0;
  3096. }
  3097. r_delayline[r_circ_idx] = *bp;
  3098. sum = 0;
  3099. c_idx = r_circ_idx;
  3100. for(int k = 0; k < num_chorus; k++) {
  3101. sum += r_delayline[c_idx];
  3102. if(num_chorus > 1)c_idx -= delay_length/(num_chorus - 1) - 1;
  3103. if(c_idx < 0) {
  3104. c_idx += delay_length;
  3105. }
  3106. }
  3107. *bp++ = sum/num_chorus;
  3108. }
  3109. // send the effect output to the left channel
  3110. transmit(block,1);
  3111. release(block);
  3112. }
  3113. }