No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587
  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. void AudioSynthWaveform::update(void)
  122. {
  123. audio_block_t *block;
  124. uint32_t i, ph, inc, index, scale;
  125. int32_t val1, val2, val3;
  126. //Serial.println("AudioSynthWaveform::update");
  127. if (magnitude > 0 && (block = allocate()) != NULL) {
  128. ph = phase;
  129. inc = phase_increment;
  130. for (i=0; i < AUDIO_BLOCK_SAMPLES; i++) {
  131. index = ph >> 24;
  132. val1 = wavetable[index];
  133. val2 = wavetable[index+1];
  134. scale = (ph >> 8) & 0xFFFF;
  135. val2 *= scale;
  136. val1 *= 0xFFFF - scale;
  137. val3 = (val1 + val2) >> 16;
  138. block->data[i] = (val3 * magnitude) >> 15;
  139. //Serial.print(block->data[i]);
  140. //Serial.print(", ");
  141. //if ((i % 12) == 11) Serial.println();
  142. ph += inc;
  143. }
  144. //Serial.println();
  145. phase = ph;
  146. transmit(block);
  147. release(block);
  148. } else {
  149. // is this numerical overflow ok?
  150. phase += phase_increment * AUDIO_BLOCK_SAMPLES;
  151. }
  152. }
  153. #if 0
  154. void AudioSineWaveMod::frequency(float f)
  155. {
  156. if (f > AUDIO_SAMPLE_RATE_EXACT / 2 || f < 0.0) return;
  157. phase_increment = (f / AUDIO_SAMPLE_RATE_EXACT) * 4294967296.0f;
  158. }
  159. void AudioSineWaveMod::update(void)
  160. {
  161. audio_block_t *block, *modinput;
  162. uint32_t i, ph, inc, index, scale;
  163. int32_t val1, val2;
  164. //Serial.println("AudioSineWave::update");
  165. modinput = receiveReadOnly();
  166. ph = phase;
  167. inc = phase_increment;
  168. block = allocate();
  169. if (!block) {
  170. // unable to allocate memory, so we'll send nothing
  171. if (modinput) {
  172. // but if we got modulation data, update the phase
  173. for (i=0; i < AUDIO_BLOCK_SAMPLES; i++) {
  174. ph += inc + modinput->data[i] * modulation_factor;
  175. }
  176. release(modinput);
  177. } else {
  178. ph += phase_increment * AUDIO_BLOCK_SAMPLES;
  179. }
  180. phase = ph;
  181. return;
  182. }
  183. if (modinput) {
  184. for (i=0; i < AUDIO_BLOCK_SAMPLES; i++) {
  185. index = ph >> 24;
  186. val1 = sine_table[index];
  187. val2 = sine_table[index+1];
  188. scale = (ph >> 8) & 0xFFFF;
  189. val2 *= scale;
  190. val1 *= 0xFFFF - scale;
  191. block->data[i] = (val1 + val2) >> 16;
  192. //Serial.print(block->data[i]);
  193. //Serial.print(", ");
  194. //if ((i % 12) == 11) Serial.println();
  195. ph += inc + modinput->data[i] * modulation_factor;
  196. }
  197. release(modinput);
  198. } else {
  199. ph = phase;
  200. inc = phase_increment;
  201. for (i=0; i < AUDIO_BLOCK_SAMPLES; i++) {
  202. index = ph >> 24;
  203. val1 = sine_table[index];
  204. val2 = sine_table[index+1];
  205. scale = (ph >> 8) & 0xFFFF;
  206. val2 *= scale;
  207. val1 *= 0xFFFF - scale;
  208. block->data[i] = (val1 + val2) >> 16;
  209. //Serial.print(block->data[i]);
  210. //Serial.print(", ");
  211. //if ((i % 12) == 11) Serial.println();
  212. ph += inc;
  213. }
  214. }
  215. phase = ph;
  216. transmit(block);
  217. release(block);
  218. }
  219. #endif
  220. /******************************************************************/
  221. void AudioPrint::update(void)
  222. {
  223. audio_block_t *block;
  224. uint32_t i;
  225. Serial.println("AudioPrint::update");
  226. Serial.println(name);
  227. block = receiveReadOnly();
  228. if (block) {
  229. for (i=0; i < AUDIO_BLOCK_SAMPLES; i++) {
  230. Serial.print(block->data[i]);
  231. Serial.print(", ");
  232. if ((i % 12) == 11) Serial.println();
  233. }
  234. Serial.println();
  235. release(block);
  236. }
  237. }
  238. /******************************************************************/
  239. audio_block_t * AudioOutputPWM::block_1st = NULL;
  240. audio_block_t * AudioOutputPWM::block_2nd = NULL;
  241. uint32_t AudioOutputPWM::block_offset = 0;
  242. bool AudioOutputPWM::update_responsibility = false;
  243. uint8_t AudioOutputPWM::interrupt_count = 0;
  244. DMAMEM uint32_t pwm_dma_buffer[AUDIO_BLOCK_SAMPLES*2];
  245. void AudioOutputPWM::begin(void)
  246. {
  247. //Serial.println("AudioPwmOutput constructor");
  248. block_1st = NULL;
  249. FTM1_SC = 0;
  250. FTM1_CNT = 0;
  251. FTM1_MOD = 543;
  252. FTM1_C0SC = 0x69; // send DMA request on match
  253. FTM1_C1SC = 0x28;
  254. FTM1_SC = FTM_SC_CLKS(1) | FTM_SC_PS(0);
  255. CORE_PIN3_CONFIG = PORT_PCR_MUX(3) | PORT_PCR_DSE | PORT_PCR_SRE;
  256. CORE_PIN4_CONFIG = PORT_PCR_MUX(3) | PORT_PCR_DSE | PORT_PCR_SRE;
  257. FTM1_C0V = 120; // range 120 to 375
  258. FTM1_C1V = 0; // range 0 to 255
  259. for (int i=0; i<256; i+=2) {
  260. pwm_dma_buffer[i] = 120; // zero must not be used
  261. pwm_dma_buffer[i+1] = 0;
  262. }
  263. SIM_SCGC7 |= SIM_SCGC7_DMA;
  264. SIM_SCGC6 |= SIM_SCGC6_DMAMUX;
  265. DMA_CR = 0;
  266. DMA_TCD3_SADDR = pwm_dma_buffer;
  267. DMA_TCD3_SOFF = 4;
  268. DMA_TCD3_ATTR = DMA_TCD_ATTR_SSIZE(2) | DMA_TCD_ATTR_DSIZE(2) | DMA_TCD_ATTR_DMOD(4);
  269. DMA_TCD3_NBYTES_MLNO = 8;
  270. DMA_TCD3_SLAST = -sizeof(pwm_dma_buffer);
  271. DMA_TCD3_DADDR = &FTM1_C0V;
  272. DMA_TCD3_DOFF = 8;
  273. DMA_TCD3_CITER_ELINKNO = sizeof(pwm_dma_buffer) / 8;
  274. DMA_TCD3_DLASTSGA = 0;
  275. DMA_TCD3_BITER_ELINKNO = sizeof(pwm_dma_buffer) / 8;
  276. DMA_TCD3_CSR = DMA_TCD_CSR_INTHALF | DMA_TCD_CSR_INTMAJOR;
  277. DMAMUX0_CHCFG3 = DMAMUX_DISABLE;
  278. DMAMUX0_CHCFG3 = DMAMUX_SOURCE_FTM1_CH0 | DMAMUX_ENABLE;
  279. DMA_SERQ = 3;
  280. update_responsibility = update_setup();
  281. NVIC_ENABLE_IRQ(IRQ_DMA_CH3);
  282. }
  283. void AudioOutputPWM::update(void)
  284. {
  285. audio_block_t *block;
  286. block = receiveReadOnly();
  287. if (!block) return;
  288. __disable_irq();
  289. if (block_1st == NULL) {
  290. block_1st = block;
  291. block_offset = 0;
  292. __enable_irq();
  293. } else if (block_2nd == NULL) {
  294. block_2nd = block;
  295. __enable_irq();
  296. } else {
  297. audio_block_t *tmp = block_1st;
  298. block_1st = block_2nd;
  299. block_2nd = block;
  300. block_offset = 0;
  301. __enable_irq();
  302. release(tmp);
  303. }
  304. }
  305. void dma_ch3_isr(void)
  306. {
  307. int16_t *src;
  308. uint32_t *dest;
  309. audio_block_t *block;
  310. uint32_t saddr, offset;
  311. saddr = (uint32_t)DMA_TCD3_SADDR;
  312. DMA_CINT = 3;
  313. if (saddr < (uint32_t)pwm_dma_buffer + sizeof(pwm_dma_buffer) / 2) {
  314. // DMA is transmitting the first half of the buffer
  315. // so we must fill the second half
  316. dest = &pwm_dma_buffer[AUDIO_BLOCK_SAMPLES];
  317. } else {
  318. // DMA is transmitting the second half of the buffer
  319. // so we must fill the first half
  320. dest = pwm_dma_buffer;
  321. }
  322. block = AudioOutputPWM::block_1st;
  323. offset = AudioOutputPWM::block_offset;
  324. if (block) {
  325. src = &block->data[offset];
  326. for (int i=0; i < AUDIO_BLOCK_SAMPLES/4; i++) {
  327. uint16_t sample = *src++ + 0x8000;
  328. uint32_t msb = ((sample >> 8) & 255) + 120;
  329. uint32_t lsb = sample & 255;
  330. *dest++ = msb;
  331. *dest++ = lsb;
  332. *dest++ = msb;
  333. *dest++ = lsb;
  334. }
  335. offset += AUDIO_BLOCK_SAMPLES/4;
  336. if (offset < AUDIO_BLOCK_SAMPLES) {
  337. AudioOutputPWM::block_offset = offset;
  338. } else {
  339. AudioOutputPWM::block_offset = 0;
  340. AudioStream::release(block);
  341. AudioOutputPWM::block_1st = AudioOutputPWM::block_2nd;
  342. AudioOutputPWM::block_2nd = NULL;
  343. }
  344. } else {
  345. // fill with silence when no data available
  346. for (int i=0; i < AUDIO_BLOCK_SAMPLES/4; i++) {
  347. *dest++ = 248;
  348. *dest++ = 0;
  349. *dest++ = 248;
  350. *dest++ = 0;
  351. }
  352. }
  353. if (AudioOutputPWM::update_responsibility) {
  354. if (++AudioOutputPWM::interrupt_count >= 4) {
  355. AudioOutputPWM::interrupt_count = 0;
  356. AudioStream::update_all();
  357. }
  358. }
  359. }
  360. // DMA target is: (registers require 32 bit writes)
  361. // 40039010 Channel 0 Value (FTM1_C0V)
  362. // 40039018 Channel 1 Value (FTM1_C1V)
  363. // TCD:
  364. // source address = buffer address
  365. // source offset = 4 bytes
  366. // attr = no src mod, ssize = 32 bit, dest mod = 16 bytes (4), dsize = 32 bit
  367. // minor loop byte count = 8
  368. // source last adjust = -sizeof(buffer)
  369. // dest address = FTM1_C0V
  370. // dest address offset = 8
  371. // citer = sizeof(buffer) / 8 (no minor loop linking)
  372. // dest last adjust = 0 (dest modulo keeps it ready for more)
  373. // control:
  374. // throttling = 0
  375. // major link to same channel
  376. // done = 0
  377. // active = 0
  378. // majorlink = 1
  379. // scatter/gather = 0
  380. // disable request = 0
  381. // inthalf = 1
  382. // intmajor = 1
  383. // start = 0
  384. // biter = sizeof(buffer) / 8 (no minor loop linking)
  385. /******************************************************************/
  386. // MCLK needs to be 48e6 / 1088 * 256 = 11.29411765 MHz -> 44.117647 kHz sample rate
  387. // Possible to create using fractional divider for all USB-compatible Kinetis:
  388. // MCLK = 16e6 * 12 / 17
  389. // MCLK = 24e6 * 8 / 17
  390. // MCLK = 48e6 * 4 / 17
  391. // MCLK = 72e6 * 8 / 51
  392. // MCLK = 96e6 * 2 / 17
  393. // MCLK = 120e6 * 8 / 85
  394. // TODO: instigate using I2S0_MCR to select the crystal directly instead of the system
  395. // clock, which has audio band jitter from the PLL
  396. audio_block_t * AudioOutputI2S::block_left_1st = NULL;
  397. audio_block_t * AudioOutputI2S::block_right_1st = NULL;
  398. audio_block_t * AudioOutputI2S::block_left_2nd = NULL;
  399. audio_block_t * AudioOutputI2S::block_right_2nd = NULL;
  400. uint16_t AudioOutputI2S::block_left_offset = 0;
  401. uint16_t AudioOutputI2S::block_right_offset = 0;
  402. bool AudioOutputI2S::update_responsibility = false;
  403. DMAMEM static uint32_t i2s_tx_buffer[AUDIO_BLOCK_SAMPLES];
  404. void AudioOutputI2S::begin(void)
  405. {
  406. //pinMode(2, OUTPUT);
  407. block_left_1st = NULL;
  408. block_right_1st = NULL;
  409. config_i2s();
  410. CORE_PIN22_CONFIG = PORT_PCR_MUX(6); // pin 22, PTC1, I2S0_TXD0
  411. DMA_CR = 0;
  412. DMA_TCD0_SADDR = i2s_tx_buffer;
  413. DMA_TCD0_SOFF = 2;
  414. DMA_TCD0_ATTR = DMA_TCD_ATTR_SSIZE(1) | DMA_TCD_ATTR_DSIZE(1);
  415. DMA_TCD0_NBYTES_MLNO = 2;
  416. DMA_TCD0_SLAST = -sizeof(i2s_tx_buffer);
  417. DMA_TCD0_DADDR = &I2S0_TDR0;
  418. DMA_TCD0_DOFF = 0;
  419. DMA_TCD0_CITER_ELINKNO = sizeof(i2s_tx_buffer) / 2;
  420. DMA_TCD0_DLASTSGA = 0;
  421. DMA_TCD0_BITER_ELINKNO = sizeof(i2s_tx_buffer) / 2;
  422. DMA_TCD0_CSR = DMA_TCD_CSR_INTHALF | DMA_TCD_CSR_INTMAJOR;
  423. DMAMUX0_CHCFG0 = DMAMUX_DISABLE;
  424. DMAMUX0_CHCFG0 = DMAMUX_SOURCE_I2S0_TX | DMAMUX_ENABLE;
  425. update_responsibility = update_setup();
  426. DMA_SERQ = 0;
  427. I2S0_TCSR |= I2S_TCSR_TE | I2S_TCSR_BCE | I2S_TCSR_FRDE | I2S_TCSR_FR;
  428. NVIC_ENABLE_IRQ(IRQ_DMA_CH0);
  429. }
  430. void dma_ch0_isr(void)
  431. {
  432. const int16_t *src, *end;
  433. int16_t *dest;
  434. audio_block_t *block;
  435. uint32_t saddr, offset;
  436. saddr = (uint32_t)DMA_TCD0_SADDR;
  437. DMA_CINT = 0;
  438. if (saddr < (uint32_t)i2s_tx_buffer + sizeof(i2s_tx_buffer) / 2) {
  439. // DMA is transmitting the first half of the buffer
  440. // so we must fill the second half
  441. dest = (int16_t *)&i2s_tx_buffer[AUDIO_BLOCK_SAMPLES/2];
  442. end = (int16_t *)&i2s_tx_buffer[AUDIO_BLOCK_SAMPLES];
  443. if (AudioOutputI2S::update_responsibility) AudioStream::update_all();
  444. } else {
  445. // DMA is transmitting the second half of the buffer
  446. // so we must fill the first half
  447. dest = (int16_t *)i2s_tx_buffer;
  448. end = (int16_t *)&i2s_tx_buffer[AUDIO_BLOCK_SAMPLES/2];
  449. }
  450. // TODO: these copy routines could be merged and optimized, maybe in assembly?
  451. block = AudioOutputI2S::block_left_1st;
  452. if (block) {
  453. offset = AudioOutputI2S::block_left_offset;
  454. src = &block->data[offset];
  455. do {
  456. *dest = *src++;
  457. dest += 2;
  458. } while (dest < end);
  459. offset += AUDIO_BLOCK_SAMPLES/2;
  460. if (offset < AUDIO_BLOCK_SAMPLES) {
  461. AudioOutputI2S::block_left_offset = offset;
  462. } else {
  463. AudioOutputI2S::block_left_offset = 0;
  464. AudioStream::release(block);
  465. AudioOutputI2S::block_left_1st = AudioOutputI2S::block_left_2nd;
  466. AudioOutputI2S::block_left_2nd = NULL;
  467. }
  468. } else {
  469. do {
  470. *dest = 0;
  471. dest += 2;
  472. } while (dest < end);
  473. }
  474. dest -= AUDIO_BLOCK_SAMPLES - 1;
  475. block = AudioOutputI2S::block_right_1st;
  476. if (block) {
  477. offset = AudioOutputI2S::block_right_offset;
  478. src = &block->data[offset];
  479. do {
  480. *dest = *src++;
  481. dest += 2;
  482. } while (dest < end);
  483. offset += AUDIO_BLOCK_SAMPLES/2;
  484. if (offset < AUDIO_BLOCK_SAMPLES) {
  485. AudioOutputI2S::block_right_offset = offset;
  486. } else {
  487. AudioOutputI2S::block_right_offset = 0;
  488. AudioStream::release(block);
  489. AudioOutputI2S::block_right_1st = AudioOutputI2S::block_right_2nd;
  490. AudioOutputI2S::block_right_2nd = NULL;
  491. }
  492. } else {
  493. do {
  494. *dest = 0;
  495. dest += 2;
  496. } while (dest < end);
  497. }
  498. }
  499. void AudioOutputI2S::update(void)
  500. {
  501. // null audio device: discard all incoming data
  502. //if (!active) return;
  503. //audio_block_t *block = receiveReadOnly();
  504. //if (block) release(block);
  505. audio_block_t *block;
  506. block = receiveReadOnly(0); // input 0 = left channel
  507. if (block) {
  508. __disable_irq();
  509. if (block_left_1st == NULL) {
  510. block_left_1st = block;
  511. block_left_offset = 0;
  512. __enable_irq();
  513. } else if (block_left_2nd == NULL) {
  514. block_left_2nd = block;
  515. __enable_irq();
  516. } else {
  517. audio_block_t *tmp = block_left_1st;
  518. block_left_1st = block_left_2nd;
  519. block_left_2nd = block;
  520. block_left_offset = 0;
  521. __enable_irq();
  522. release(tmp);
  523. }
  524. }
  525. block = receiveReadOnly(1); // input 1 = right channel
  526. if (block) {
  527. __disable_irq();
  528. if (block_right_1st == NULL) {
  529. block_right_1st = block;
  530. block_right_offset = 0;
  531. __enable_irq();
  532. } else if (block_right_2nd == NULL) {
  533. block_right_2nd = block;
  534. __enable_irq();
  535. } else {
  536. audio_block_t *tmp = block_right_1st;
  537. block_right_1st = block_right_2nd;
  538. block_right_2nd = block;
  539. block_right_offset = 0;
  540. __enable_irq();
  541. release(tmp);
  542. }
  543. }
  544. }
  545. void AudioOutputI2S::config_i2s(void)
  546. {
  547. SIM_SCGC6 |= SIM_SCGC6_I2S;
  548. SIM_SCGC7 |= SIM_SCGC7_DMA;
  549. SIM_SCGC6 |= SIM_SCGC6_DMAMUX;
  550. // if either transmitter or receiver is enabled, do nothing
  551. if (I2S0_TCSR & I2S_TCSR_TE) return;
  552. if (I2S0_RCSR & I2S_RCSR_RE) return;
  553. // enable MCLK output
  554. I2S0_MCR = I2S_MCR_MICS(3) | I2S_MCR_MOE;
  555. I2S0_MDR = I2S_MDR_FRACT(1) | I2S_MDR_DIVIDE(16);
  556. // configure transmitter
  557. I2S0_TMR = 0;
  558. I2S0_TCR1 = I2S_TCR1_TFW(1); // watermark at half fifo size
  559. I2S0_TCR2 = I2S_TCR2_SYNC(0) | I2S_TCR2_BCP | I2S_TCR2_MSEL(1)
  560. | I2S_TCR2_BCD | I2S_TCR2_DIV(3);
  561. I2S0_TCR3 = I2S_TCR3_TCE;
  562. I2S0_TCR4 = I2S_TCR4_FRSZ(1) | I2S_TCR4_SYWD(15) | I2S_TCR4_MF
  563. | I2S_TCR4_FSE | I2S_TCR4_FSP | I2S_TCR4_FSD;
  564. I2S0_TCR5 = I2S_TCR5_WNW(15) | I2S_TCR5_W0W(15) | I2S_TCR5_FBT(15);
  565. // configure receiver (sync'd to transmitter clocks)
  566. I2S0_RMR = 0;
  567. I2S0_RCR1 = I2S_RCR1_RFW(1);
  568. I2S0_RCR2 = I2S_RCR2_SYNC(1) | I2S_TCR2_BCP | I2S_RCR2_MSEL(1)
  569. | I2S_RCR2_BCD | I2S_RCR2_DIV(3);
  570. I2S0_RCR3 = I2S_RCR3_RCE;
  571. I2S0_RCR4 = I2S_RCR4_FRSZ(1) | I2S_RCR4_SYWD(15) | I2S_RCR4_MF
  572. | I2S_RCR4_FSE | I2S_RCR4_FSP | I2S_RCR4_FSD;
  573. I2S0_RCR5 = I2S_RCR5_WNW(15) | I2S_RCR5_W0W(15) | I2S_RCR5_FBT(15);
  574. // configure pin mux for 3 clock signals
  575. CORE_PIN23_CONFIG = PORT_PCR_MUX(6); // pin 23, PTC2, I2S0_TX_FS (LRCLK)
  576. CORE_PIN9_CONFIG = PORT_PCR_MUX(6); // pin 9, PTC3, I2S0_TX_BCLK
  577. CORE_PIN11_CONFIG = PORT_PCR_MUX(6); // pin 11, PTC6, I2S0_MCLK
  578. }
  579. /******************************************************************/
  580. DMAMEM static uint32_t i2s_rx_buffer[AUDIO_BLOCK_SAMPLES];
  581. audio_block_t * AudioInputI2S::block_left = NULL;
  582. audio_block_t * AudioInputI2S::block_right = NULL;
  583. uint16_t AudioInputI2S::block_offset = 0;
  584. bool AudioInputI2S::update_responsibility = false;
  585. void AudioInputI2S::begin(void)
  586. {
  587. //block_left_1st = NULL;
  588. //block_right_1st = NULL;
  589. //pinMode(3, OUTPUT);
  590. //digitalWriteFast(3, HIGH);
  591. //delayMicroseconds(500);
  592. //digitalWriteFast(3, LOW);
  593. AudioOutputI2S::config_i2s();
  594. CORE_PIN13_CONFIG = PORT_PCR_MUX(4); // pin 13, PTC5, I2S0_RXD0
  595. DMA_CR = 0;
  596. DMA_TCD1_SADDR = &I2S0_RDR0;
  597. DMA_TCD1_SOFF = 0;
  598. DMA_TCD1_ATTR = DMA_TCD_ATTR_SSIZE(1) | DMA_TCD_ATTR_DSIZE(1);
  599. DMA_TCD1_NBYTES_MLNO = 2;
  600. DMA_TCD1_SLAST = 0;
  601. DMA_TCD1_DADDR = i2s_rx_buffer;
  602. DMA_TCD1_DOFF = 2;
  603. DMA_TCD1_CITER_ELINKNO = sizeof(i2s_rx_buffer) / 2;
  604. DMA_TCD1_DLASTSGA = -sizeof(i2s_rx_buffer);
  605. DMA_TCD1_BITER_ELINKNO = sizeof(i2s_rx_buffer) / 2;
  606. DMA_TCD1_CSR = DMA_TCD_CSR_INTHALF | DMA_TCD_CSR_INTMAJOR;
  607. DMAMUX0_CHCFG1 = DMAMUX_DISABLE;
  608. DMAMUX0_CHCFG1 = DMAMUX_SOURCE_I2S0_RX | DMAMUX_ENABLE;
  609. update_responsibility = update_setup();
  610. DMA_SERQ = 1;
  611. // TODO: is I2S_RCSR_BCE appropriate if sync'd to transmitter clock?
  612. //I2S0_RCSR |= I2S_RCSR_RE | I2S_RCSR_BCE | I2S_RCSR_FRDE | I2S_RCSR_FR;
  613. I2S0_RCSR |= I2S_RCSR_RE | I2S_RCSR_FRDE | I2S_RCSR_FR;
  614. NVIC_ENABLE_IRQ(IRQ_DMA_CH1);
  615. }
  616. void dma_ch1_isr(void)
  617. {
  618. uint32_t daddr, offset;
  619. const int16_t *src, *end;
  620. int16_t *dest_left, *dest_right;
  621. audio_block_t *left, *right;
  622. //digitalWriteFast(3, HIGH);
  623. daddr = (uint32_t)DMA_TCD1_DADDR;
  624. DMA_CINT = 1;
  625. if (daddr < (uint32_t)i2s_rx_buffer + sizeof(i2s_rx_buffer) / 2) {
  626. // DMA is receiving to the first half of the buffer
  627. // need to remove data from the second half
  628. src = (int16_t *)&i2s_rx_buffer[AUDIO_BLOCK_SAMPLES/2];
  629. end = (int16_t *)&i2s_rx_buffer[AUDIO_BLOCK_SAMPLES];
  630. if (AudioInputI2S::update_responsibility) AudioStream::update_all();
  631. } else {
  632. // DMA is receiving to the second half of the buffer
  633. // need to remove data from the first half
  634. src = (int16_t *)&i2s_rx_buffer[0];
  635. end = (int16_t *)&i2s_rx_buffer[AUDIO_BLOCK_SAMPLES/2];
  636. }
  637. left = AudioInputI2S::block_left;
  638. right = AudioInputI2S::block_right;
  639. if (left != NULL && right != NULL) {
  640. offset = AudioInputI2S::block_offset;
  641. if (offset <= AUDIO_BLOCK_SAMPLES/2) {
  642. dest_left = &(left->data[offset]);
  643. dest_right = &(right->data[offset]);
  644. AudioInputI2S::block_offset = offset + AUDIO_BLOCK_SAMPLES/2;
  645. do {
  646. //n = *src++;
  647. //*dest_left++ = (int16_t)n;
  648. //*dest_right++ = (int16_t)(n >> 16);
  649. *dest_left++ = *src++;
  650. *dest_right++ = *src++;
  651. } while (src < end);
  652. }
  653. }
  654. //digitalWriteFast(3, LOW);
  655. }
  656. void AudioInputI2S::update(void)
  657. {
  658. audio_block_t *new_left=NULL, *new_right=NULL, *out_left=NULL, *out_right=NULL;
  659. // allocate 2 new blocks, but if one fails, allocate neither
  660. new_left = allocate();
  661. if (new_left != NULL) {
  662. new_right = allocate();
  663. if (new_right == NULL) {
  664. release(new_left);
  665. new_left = NULL;
  666. }
  667. }
  668. __disable_irq();
  669. if (block_offset >= AUDIO_BLOCK_SAMPLES) {
  670. // the DMA filled 2 blocks, so grab them and get the
  671. // 2 new blocks to the DMA, as quickly as possible
  672. out_left = block_left;
  673. block_left = new_left;
  674. out_right = block_right;
  675. block_right = new_right;
  676. block_offset = 0;
  677. __enable_irq();
  678. // then transmit the DMA's former blocks
  679. transmit(out_left, 0);
  680. release(out_left);
  681. transmit(out_right, 1);
  682. release(out_right);
  683. //Serial.print(".");
  684. } else if (new_left != NULL) {
  685. // the DMA didn't fill blocks, but we allocated blocks
  686. if (block_left == NULL) {
  687. // the DMA doesn't have any blocks to fill, so
  688. // give it the ones we just allocated
  689. block_left = new_left;
  690. block_right = new_right;
  691. block_offset = 0;
  692. __enable_irq();
  693. } else {
  694. // the DMA already has blocks, doesn't need these
  695. __enable_irq();
  696. release(new_left);
  697. release(new_right);
  698. }
  699. } else {
  700. // The DMA didn't fill blocks, and we could not allocate
  701. // memory... the system is likely starving for memory!
  702. // Sadly, there's nothing we can do.
  703. __enable_irq();
  704. }
  705. }
  706. /******************************************************************/
  707. DMAMEM static uint16_t analog_rx_buffer[AUDIO_BLOCK_SAMPLES];
  708. audio_block_t * AudioInputAnalog::block_left = NULL;
  709. uint16_t AudioInputAnalog::block_offset = 0;
  710. #define PDB_CONFIG (PDB_SC_TRGSEL(15) | PDB_SC_PDBEN | PDB_SC_CONT)
  711. #define PDB_PERIOD 1087 // 48e6 / 44100
  712. void AudioInputAnalog::begin(unsigned int pin)
  713. {
  714. uint32_t i, sum=0;
  715. // pin must be 0 to 13 (for A0 to A13)
  716. // or 14 to 23 for digital pin numbers A0-A9
  717. // or 34 to 37 corresponding to A10-A13
  718. if (pin > 23 && !(pin >= 34 && pin <= 37)) return;
  719. //pinMode(2, OUTPUT);
  720. //pinMode(3, OUTPUT);
  721. //digitalWriteFast(3, HIGH);
  722. //delayMicroseconds(500);
  723. //digitalWriteFast(3, LOW);
  724. // Configure the ADC and run at least one software-triggered
  725. // conversion. This completes the self calibration stuff and
  726. // leaves the ADC in a state that's mostly ready to use
  727. analogReadRes(16);
  728. analogReference(INTERNAL); // range 0 to 1.2 volts
  729. //analogReference(DEFAULT); // range 0 to 3.3 volts
  730. analogReadAveraging(8);
  731. // Actually, do many normal reads, to start with a nice DC level
  732. for (i=0; i < 1024; i++) {
  733. sum += analogRead(pin);
  734. }
  735. dc_average = sum >> 10;
  736. // testing only, enable adc interrupt
  737. //ADC0_SC1A |= ADC_SC1_AIEN;
  738. //while ((ADC0_SC1A & ADC_SC1_COCO) == 0) ; // wait
  739. //NVIC_ENABLE_IRQ(IRQ_ADC0);
  740. // set the programmable delay block to trigger the ADC at 44.1 kHz
  741. SIM_SCGC6 |= SIM_SCGC6_PDB;
  742. PDB0_MOD = PDB_PERIOD;
  743. PDB0_SC = PDB_CONFIG | PDB_SC_LDOK;
  744. PDB0_SC = PDB_CONFIG | PDB_SC_SWTRIG;
  745. PDB0_CH0C1 = 0x0101;
  746. // enable the ADC for hardware trigger and DMA
  747. ADC0_SC2 |= ADC_SC2_ADTRG | ADC_SC2_DMAEN;
  748. // set up a DMA channel to store the ADC data
  749. SIM_SCGC7 |= SIM_SCGC7_DMA;
  750. SIM_SCGC6 |= SIM_SCGC6_DMAMUX;
  751. DMA_CR = 0;
  752. DMA_TCD2_SADDR = &ADC0_RA;
  753. DMA_TCD2_SOFF = 0;
  754. DMA_TCD2_ATTR = DMA_TCD_ATTR_SSIZE(1) | DMA_TCD_ATTR_DSIZE(1);
  755. DMA_TCD2_NBYTES_MLNO = 2;
  756. DMA_TCD2_SLAST = 0;
  757. DMA_TCD2_DADDR = analog_rx_buffer;
  758. DMA_TCD2_DOFF = 2;
  759. DMA_TCD2_CITER_ELINKNO = sizeof(analog_rx_buffer) / 2;
  760. DMA_TCD2_DLASTSGA = -sizeof(analog_rx_buffer);
  761. DMA_TCD2_BITER_ELINKNO = sizeof(analog_rx_buffer) / 2;
  762. DMA_TCD2_CSR = DMA_TCD_CSR_INTHALF | DMA_TCD_CSR_INTMAJOR;
  763. DMAMUX0_CHCFG2 = DMAMUX_DISABLE;
  764. DMAMUX0_CHCFG2 = DMAMUX_SOURCE_ADC0 | DMAMUX_ENABLE;
  765. //update_responsibility = update_setup();
  766. DMA_SERQ = 2;
  767. NVIC_ENABLE_IRQ(IRQ_DMA_CH2);
  768. }
  769. void dma_ch2_isr(void)
  770. {
  771. uint32_t daddr, offset;
  772. const uint16_t *src, *end;
  773. uint16_t *dest_left;
  774. audio_block_t *left;
  775. //digitalWriteFast(3, HIGH);
  776. daddr = (uint32_t)DMA_TCD2_DADDR;
  777. DMA_CINT = 2;
  778. if (daddr < (uint32_t)analog_rx_buffer + sizeof(analog_rx_buffer) / 2) {
  779. // DMA is receiving to the first half of the buffer
  780. // need to remove data from the second half
  781. src = (uint16_t *)&analog_rx_buffer[AUDIO_BLOCK_SAMPLES/2];
  782. end = (uint16_t *)&analog_rx_buffer[AUDIO_BLOCK_SAMPLES];
  783. //if (AudioInputI2S::update_responsibility) AudioStream::update_all();
  784. } else {
  785. // DMA is receiving to the second half of the buffer
  786. // need to remove data from the first half
  787. src = (uint16_t *)&analog_rx_buffer[0];
  788. end = (uint16_t *)&analog_rx_buffer[AUDIO_BLOCK_SAMPLES/2];
  789. }
  790. left = AudioInputAnalog::block_left;
  791. if (left != NULL) {
  792. offset = AudioInputAnalog::block_offset;
  793. if (offset > AUDIO_BLOCK_SAMPLES/2) offset = AUDIO_BLOCK_SAMPLES/2;
  794. //if (offset <= AUDIO_BLOCK_SAMPLES/2) {
  795. dest_left = (uint16_t *)&(left->data[offset]);
  796. AudioInputAnalog::block_offset = offset + AUDIO_BLOCK_SAMPLES/2;
  797. do {
  798. *dest_left++ = *src++;
  799. } while (src < end);
  800. //}
  801. }
  802. //digitalWriteFast(3, LOW);
  803. }
  804. #if 0
  805. void adc0_isr(void)
  806. {
  807. uint32_t tmp = ADC0_RA; // read ADC result to clear interrupt
  808. digitalWriteFast(3, HIGH);
  809. delayMicroseconds(1);
  810. digitalWriteFast(3, LOW);
  811. }
  812. #endif
  813. void AudioInputAnalog::update(void)
  814. {
  815. audio_block_t *new_left=NULL, *out_left=NULL;
  816. unsigned int dc, offset;
  817. int16_t s, *p, *end;
  818. // allocate new block (ok if NULL)
  819. new_left = allocate();
  820. __disable_irq();
  821. offset = block_offset;
  822. if (offset < AUDIO_BLOCK_SAMPLES) {
  823. // the DMA didn't fill a block
  824. if (new_left != NULL) {
  825. // but we allocated a block
  826. if (block_left == NULL) {
  827. // the DMA doesn't have any blocks to fill, so
  828. // give it the one we just allocated
  829. block_left = new_left;
  830. block_offset = 0;
  831. __enable_irq();
  832. //Serial.println("fail1");
  833. } else {
  834. // the DMA already has blocks, doesn't need this
  835. __enable_irq();
  836. release(new_left);
  837. //Serial.print("fail2, offset=");
  838. //Serial.println(offset);
  839. }
  840. } else {
  841. // The DMA didn't fill a block, and we could not allocate
  842. // memory... the system is likely starving for memory!
  843. // Sadly, there's nothing we can do.
  844. __enable_irq();
  845. //Serial.println("fail3");
  846. }
  847. return;
  848. }
  849. // the DMA filled a block, so grab it and get the
  850. // new block to the DMA, as quickly as possible
  851. out_left = block_left;
  852. block_left = new_left;
  853. block_offset = 0;
  854. __enable_irq();
  855. // find and subtract DC offset....
  856. // TODO: this may not be correct, needs testing with more types of signals
  857. dc = dc_average;
  858. p = out_left->data;
  859. end = p + AUDIO_BLOCK_SAMPLES;
  860. do {
  861. s = (uint16_t)(*p) - dc; // TODO: should be saturating subtract
  862. *p++ = s;
  863. dc += s >> 13; // approx 5.38 Hz high pass filter
  864. } while (p < end);
  865. dc_average = dc;
  866. // then transmit the AC data
  867. transmit(out_left);
  868. release(out_left);
  869. }
  870. /******************************************************************/
  871. // #define PDB_CONFIG (PDB_SC_TRGSEL(15) | PDB_SC_PDBEN | PDB_SC_CONT)
  872. // #define PDB_PERIOD 1087 // 48e6 / 44100
  873. #if defined(__MK20DX256__) && defined(DMA_TCD4_SADDR)
  874. DMAMEM static uint16_t dac_buffer[AUDIO_BLOCK_SAMPLES*2];
  875. audio_block_t * AudioOutputAnalog::block_left_1st = NULL;
  876. audio_block_t * AudioOutputAnalog::block_left_2nd = NULL;
  877. bool AudioOutputAnalog::update_responsibility = false;
  878. void AudioOutputAnalog::begin(void)
  879. {
  880. SIM_SCGC2 |= SIM_SCGC2_DAC0;
  881. DAC0_C0 = DAC_C0_DACEN | DAC_C0_DACRFS; // 3.3V VDDA is DACREF_2
  882. // slowly ramp up to DC voltage, approx 1/4 second
  883. for (int16_t i=0; i<2047; i++) {
  884. *(int16_t *)&(DAC0_DAT0L) = i;
  885. delayMicroseconds(262);
  886. }
  887. // set the programmable delay block to trigger DMA requests
  888. SIM_SCGC6 |= SIM_SCGC6_PDB;
  889. PDB0_IDLY = 50; // TODO: is this ok?
  890. PDB0_MOD = PDB_PERIOD;
  891. PDB0_SC = PDB_CONFIG | PDB_SC_LDOK;
  892. PDB0_SC = PDB_CONFIG | PDB_SC_SWTRIG | PDB_SC_PDBIE | PDB_SC_DMAEN;
  893. //PDB0_SC = PDB_CONFIG | PDB_SC_SWTRIG | PDB_SC_PDBIE;
  894. //NVIC_ENABLE_IRQ(IRQ_PDB);
  895. #if 1
  896. SIM_SCGC7 |= SIM_SCGC7_DMA;
  897. SIM_SCGC6 |= SIM_SCGC6_DMAMUX;
  898. DMA_CR = 0;
  899. DMA_TCD4_SADDR = dac_buffer;
  900. DMA_TCD4_SOFF = 2;
  901. DMA_TCD4_ATTR = DMA_TCD_ATTR_SSIZE(1) | DMA_TCD_ATTR_DSIZE(1);
  902. DMA_TCD4_NBYTES_MLNO = 2;
  903. DMA_TCD4_SLAST = -sizeof(dac_buffer);
  904. DMA_TCD4_DADDR = &DAC0_DAT0L;
  905. DMA_TCD4_DOFF = 0;
  906. DMA_TCD4_CITER_ELINKNO = sizeof(dac_buffer) / 2;
  907. DMA_TCD4_DLASTSGA = 0;
  908. DMA_TCD4_BITER_ELINKNO = sizeof(dac_buffer) / 2;
  909. DMA_TCD4_CSR = DMA_TCD_CSR_INTHALF | DMA_TCD_CSR_INTMAJOR;
  910. DMAMUX0_CHCFG4 = DMAMUX_DISABLE;
  911. DMAMUX0_CHCFG4 = DMAMUX_SOURCE_PDB | DMAMUX_ENABLE;
  912. update_responsibility = update_setup();
  913. DMA_SERQ = 4;
  914. NVIC_ENABLE_IRQ(IRQ_DMA_CH4);
  915. #endif
  916. }
  917. //void pdb_isr(void)
  918. //{
  919. // static uint16_t val=0;
  920. //
  921. // PDB0_SC = PDB_CONFIG | PDB_SC_PDBIE;
  922. // if (val == 0) val = 4095; // testing only, full scale 22.05 kHz output
  923. // else val = 0;
  924. // DAC0_DAT0L = val & 255;
  925. // DAC0_DATH = val >> 8;
  926. //}
  927. void AudioOutputAnalog::update(void)
  928. {
  929. audio_block_t *block;
  930. block = receiveReadOnly(0); // input 0
  931. if (block) {
  932. __disable_irq();
  933. if (block_left_1st == NULL) {
  934. block_left_1st = block;
  935. __enable_irq();
  936. } else if (block_left_2nd == NULL) {
  937. block_left_2nd = block;
  938. __enable_irq();
  939. } else {
  940. audio_block_t *tmp = block_left_1st;
  941. block_left_1st = block_left_2nd;
  942. block_left_2nd = block;
  943. __enable_irq();
  944. release(tmp);
  945. }
  946. }
  947. }
  948. // TODO: the DAC has much higher bandwidth than the datasheet says
  949. // can we output a 2X oversampled output, for easier filtering?
  950. void dma_ch4_isr(void)
  951. {
  952. const int16_t *src, *end;
  953. int16_t *dest;
  954. audio_block_t *block;
  955. uint32_t saddr, offset;
  956. saddr = (uint32_t)DMA_TCD4_SADDR;
  957. DMA_CINT = 4;
  958. if (saddr < (uint32_t)dac_buffer + sizeof(dac_buffer) / 2) {
  959. // DMA is transmitting the first half of the buffer
  960. // so we must fill the second half
  961. dest = (int16_t *)&dac_buffer[AUDIO_BLOCK_SAMPLES];
  962. end = (int16_t *)&dac_buffer[AUDIO_BLOCK_SAMPLES*2];
  963. if (AudioOutputAnalog::update_responsibility) AudioStream::update_all();
  964. } else {
  965. // DMA is transmitting the second half of the buffer
  966. // so we must fill the first half
  967. dest = (int16_t *)dac_buffer;
  968. end = (int16_t *)&dac_buffer[AUDIO_BLOCK_SAMPLES];
  969. }
  970. block = AudioOutputAnalog::block_left_1st;
  971. if (block) {
  972. src = &block->data[offset];
  973. do {
  974. // TODO: this should probably dither
  975. *dest++ = ((*src++) + 32767) >> 4; // TODO: optimize
  976. } while (dest < end);
  977. AudioStream::release(block);
  978. AudioOutputAnalog::block_left_1st = AudioOutputAnalog::block_left_2nd;
  979. AudioOutputAnalog::block_left_2nd = NULL;
  980. } else {
  981. do {
  982. *dest++ = 2047;
  983. } while (dest < end);
  984. }
  985. Serial.print(".");
  986. }
  987. #else
  988. void AudioOutputAnalog::begin(void)
  989. {
  990. }
  991. void AudioOutputAnalog::update(void)
  992. {
  993. audio_block_t *block;
  994. block = receiveReadOnly(0); // input 0
  995. if (block) release(block);
  996. }
  997. #endif // defined(__MK20DX256__) && defined(DMA_TCD4_SADDR)
  998. /******************************************************************/
  999. #define STATE_DIRECT_8BIT_MONO 0 // playing mono at native sample rate
  1000. #define STATE_DIRECT_8BIT_STEREO 1 // playing stereo at native sample rate
  1001. #define STATE_DIRECT_16BIT_MONO 2 // playing mono at native sample rate
  1002. #define STATE_DIRECT_16BIT_STEREO 3 // playing stereo at native sample rate
  1003. #define STATE_CONVERT_8BIT_MONO 4 // playing mono, converting sample rate
  1004. #define STATE_CONVERT_8BIT_STEREO 5 // playing stereo, converting sample rate
  1005. #define STATE_CONVERT_16BIT_MONO 6 // playing mono, converting sample rate
  1006. #define STATE_CONVERT_16BIT_STEREO 7 // playing stereo, converting sample rate
  1007. #define STATE_PARSE1 8 // looking for 20 byte ID header
  1008. #define STATE_PARSE2 9 // looking for 16 byte format header
  1009. #define STATE_PARSE3 10 // looking for 8 byte data header
  1010. #define STATE_PARSE4 11 // ignoring unknown chunk
  1011. #define STATE_STOP 12
  1012. void AudioPlaySDcardWAV::begin(void)
  1013. {
  1014. state = STATE_STOP;
  1015. state_play = STATE_STOP;
  1016. data_length = 0;
  1017. if (block_left) {
  1018. release(block_left);
  1019. block_left = NULL;
  1020. }
  1021. if (block_right) {
  1022. release(block_right);
  1023. block_right = NULL;
  1024. }
  1025. }
  1026. bool AudioPlaySDcardWAV::play(const char *filename)
  1027. {
  1028. stop();
  1029. wavfile = SD.open(filename);
  1030. if (!wavfile) return false;
  1031. buffer_remaining = 0;
  1032. state_play = STATE_STOP;
  1033. data_length = 0;
  1034. state = STATE_PARSE1;
  1035. return true;
  1036. }
  1037. void AudioPlaySDcardWAV::stop(void)
  1038. {
  1039. __disable_irq();
  1040. if (state != STATE_STOP) {
  1041. state = STATE_STOP;
  1042. __enable_irq();
  1043. wavfile.close();
  1044. } else {
  1045. __enable_irq();
  1046. }
  1047. }
  1048. bool AudioPlaySDcardWAV::start(void)
  1049. {
  1050. __disable_irq();
  1051. if (state == STATE_STOP) {
  1052. if (state_play == STATE_STOP) {
  1053. __enable_irq();
  1054. return false;
  1055. }
  1056. state = state_play;
  1057. }
  1058. __enable_irq();
  1059. return true;
  1060. }
  1061. void AudioPlaySDcardWAV::update(void)
  1062. {
  1063. // only update if we're playing
  1064. if (state == STATE_STOP) return;
  1065. // allocate the audio blocks to transmit
  1066. block_left = allocate();
  1067. if (block_left == NULL) return;
  1068. if (state < 8 && (state & 1) == 1) {
  1069. // if we're playing stereo, allocate another
  1070. // block for the right channel output
  1071. block_right = allocate();
  1072. if (block_right == NULL) {
  1073. release(block_left);
  1074. return;
  1075. }
  1076. } else {
  1077. // if we're playing mono or just parsing
  1078. // the WAV file header, no right-side block
  1079. block_right = NULL;
  1080. }
  1081. block_offset = 0;
  1082. //Serial.println("update");
  1083. // is there buffered data?
  1084. if (buffer_remaining > 0) {
  1085. // we have buffered data
  1086. if (consume()) return; // it was enough to transmit audio
  1087. }
  1088. // we only get to this point when buffer[512] is empty
  1089. if (state != STATE_STOP && wavfile.available()) {
  1090. // we can read more data from the file...
  1091. buffer_remaining = wavfile.read(buffer, 512);
  1092. if (consume()) {
  1093. // good, it resulted in audio transmit
  1094. return;
  1095. } else {
  1096. // not good, no audio was transmitted
  1097. buffer_remaining = 0;
  1098. if (block_left) release(block_left);
  1099. if (block_right) release(block_right);
  1100. // if we're still playing, well, there's going to
  1101. // be a gap in output, but we can't keep burning
  1102. // time trying to read more data. Hopefully things
  1103. // will go better next time?
  1104. if (state != STATE_STOP) return;
  1105. }
  1106. }
  1107. // end of file reached or other reason to stop
  1108. wavfile.close();
  1109. state_play = STATE_STOP;
  1110. state = STATE_STOP;
  1111. }
  1112. // https://ccrma.stanford.edu/courses/422/projects/WaveFormat/
  1113. // Consume already buffered data. Returns true if audio transmitted.
  1114. bool AudioPlaySDcardWAV::consume(void)
  1115. {
  1116. uint32_t len, size;
  1117. uint8_t lsb, msb;
  1118. const uint8_t *p;
  1119. size = buffer_remaining;
  1120. p = buffer + 512 - size;
  1121. start:
  1122. if (size == 0) return false;
  1123. //Serial.print("AudioPlaySDcardWAV write, size = ");
  1124. //Serial.print(size);
  1125. //Serial.print(", data_length = ");
  1126. //Serial.print(data_length);
  1127. //Serial.print(", state = ");
  1128. //Serial.println(state);
  1129. switch (state) {
  1130. // parse wav file header, is this really a .wav file?
  1131. case STATE_PARSE1:
  1132. len = 20 - data_length;
  1133. if (size < len) len = size;
  1134. memcpy((uint8_t *)header + data_length, p, len);
  1135. data_length += len;
  1136. if (data_length < 20) return false;
  1137. // parse the header...
  1138. if (header[0] == 0x46464952 && header[2] == 0x45564157
  1139. && header[3] == 0x20746D66 && header[4] == 16) {
  1140. //Serial.println("header ok");
  1141. state = STATE_PARSE2;
  1142. p += len;
  1143. size -= len;
  1144. data_length = 0;
  1145. goto start;
  1146. }
  1147. //Serial.println("unknown WAV header");
  1148. break;
  1149. // check & extract key audio parameters
  1150. case STATE_PARSE2:
  1151. len = 16 - data_length;
  1152. if (size < len) len = size;
  1153. memcpy((uint8_t *)header + data_length, p, len);
  1154. data_length += len;
  1155. if (data_length < 16) return false;
  1156. if (parse_format()) {
  1157. //Serial.println("audio format ok");
  1158. p += len;
  1159. size -= len;
  1160. data_length = 0;
  1161. state = STATE_PARSE3;
  1162. goto start;
  1163. }
  1164. //Serial.println("unknown audio format");
  1165. break;
  1166. // find the data chunk
  1167. case STATE_PARSE3:
  1168. len = 8 - data_length;
  1169. if (size < len) len = size;
  1170. memcpy((uint8_t *)header + data_length, p, len);
  1171. data_length += len;
  1172. if (data_length < 8) return false;
  1173. //Serial.print("chunk id = ");
  1174. //Serial.print(header[0], HEX);
  1175. //Serial.print(", length = ");
  1176. //Serial.println(header[1]);
  1177. p += len;
  1178. size -= len;
  1179. data_length = header[1];
  1180. if (header[0] == 0x61746164) {
  1181. //Serial.println("found data chunk");
  1182. // TODO: verify offset in file is an even number
  1183. // as required by WAV format. abort if odd. Code
  1184. // below will depend upon this and fail if not even.
  1185. leftover_bytes = 0;
  1186. state = state_play;
  1187. if (state & 1) {
  1188. // if we're going to start stereo
  1189. // better allocate another output block
  1190. block_right = allocate();
  1191. if (!block_right) return false;
  1192. }
  1193. } else {
  1194. state = STATE_PARSE4;
  1195. }
  1196. goto start;
  1197. // ignore any extra unknown chunks (title & artist info)
  1198. case STATE_PARSE4:
  1199. if (size < data_length) {
  1200. data_length -= size;
  1201. return false;
  1202. }
  1203. p += data_length;
  1204. size -= data_length;
  1205. data_length = 0;
  1206. state = STATE_PARSE3;
  1207. goto start;
  1208. // playing mono at native sample rate
  1209. case STATE_DIRECT_8BIT_MONO:
  1210. return false;
  1211. // playing stereo at native sample rate
  1212. case STATE_DIRECT_8BIT_STEREO:
  1213. return false;
  1214. // playing mono at native sample rate
  1215. case STATE_DIRECT_16BIT_MONO:
  1216. if (size > data_length) size = data_length;
  1217. data_length -= size;
  1218. while (1) {
  1219. lsb = *p++;
  1220. msb = *p++;
  1221. size -= 2;
  1222. block_left->data[block_offset++] = (msb << 8) | lsb;
  1223. if (block_offset >= AUDIO_BLOCK_SAMPLES) {
  1224. transmit(block_left, 0);
  1225. transmit(block_left, 1);
  1226. //Serial1.print('%');
  1227. //delayMicroseconds(90);
  1228. release(block_left);
  1229. block_left = NULL;
  1230. data_length += size;
  1231. buffer_remaining = size;
  1232. if (block_right) release(block_right);
  1233. return true;
  1234. }
  1235. if (size == 0) {
  1236. if (data_length == 0) break;
  1237. return false;
  1238. }
  1239. }
  1240. // end of file reached
  1241. if (block_offset > 0) {
  1242. // TODO: fill remainder of last block with zero and transmit
  1243. }
  1244. state = STATE_STOP;
  1245. return false;
  1246. // playing stereo at native sample rate
  1247. case STATE_DIRECT_16BIT_STEREO:
  1248. if (size > data_length) size = data_length;
  1249. data_length -= size;
  1250. if (leftover_bytes) {
  1251. block_left->data[block_offset] = header[0];
  1252. goto right16;
  1253. }
  1254. while (1) {
  1255. lsb = *p++;
  1256. msb = *p++;
  1257. size -= 2;
  1258. if (size == 0) {
  1259. if (data_length == 0) break;
  1260. header[0] = (msb << 8) | lsb;
  1261. leftover_bytes = 2;
  1262. return false;
  1263. }
  1264. block_left->data[block_offset] = (msb << 8) | lsb;
  1265. right16:
  1266. lsb = *p++;
  1267. msb = *p++;
  1268. size -= 2;
  1269. block_right->data[block_offset++] = (msb << 8) | lsb;
  1270. if (block_offset >= AUDIO_BLOCK_SAMPLES) {
  1271. transmit(block_left, 0);
  1272. release(block_left);
  1273. block_left = NULL;
  1274. transmit(block_right, 1);
  1275. release(block_right);
  1276. block_right = NULL;
  1277. data_length += size;
  1278. buffer_remaining = size;
  1279. return true;
  1280. }
  1281. if (size == 0) {
  1282. if (data_length == 0) break;
  1283. leftover_bytes = 0;
  1284. return false;
  1285. }
  1286. }
  1287. // end of file reached
  1288. if (block_offset > 0) {
  1289. // TODO: fill remainder of last block with zero and transmit
  1290. }
  1291. state = STATE_STOP;
  1292. return false;
  1293. // playing mono, converting sample rate
  1294. case STATE_CONVERT_8BIT_MONO :
  1295. return false;
  1296. // playing stereo, converting sample rate
  1297. case STATE_CONVERT_8BIT_STEREO:
  1298. return false;
  1299. // playing mono, converting sample rate
  1300. case STATE_CONVERT_16BIT_MONO:
  1301. return false;
  1302. // playing stereo, converting sample rate
  1303. case STATE_CONVERT_16BIT_STEREO:
  1304. return false;
  1305. // ignore any extra data after playing
  1306. // or anything following any error
  1307. case STATE_STOP:
  1308. return false;
  1309. // this is not supposed to happen!
  1310. //default:
  1311. //Serial.println("AudioPlaySDcardWAV, unknown state");
  1312. }
  1313. state_play = STATE_STOP;
  1314. state = STATE_STOP;
  1315. return false;
  1316. }
  1317. /*
  1318. 00000000 52494646 66EA6903 57415645 666D7420 RIFFf.i.WAVEfmt
  1319. 00000010 10000000 01000200 44AC0000 10B10200 ........D.......
  1320. 00000020 04001000 4C495354 3A000000 494E464F ....LIST:...INFO
  1321. 00000030 494E414D 14000000 49205761 6E742054 INAM....I Want T
  1322. 00000040 6F20436F 6D65204F 76657200 49415254 o Come Over.IART
  1323. 00000050 12000000 4D656C69 73736120 45746865 ....Melissa Ethe
  1324. 00000060 72696467 65006461 746100EA 69030100 ridge.data..i...
  1325. 00000070 FEFF0300 FCFF0400 FDFF0200 0000FEFF ................
  1326. 00000080 0300FDFF 0200FFFF 00000100 FEFF0300 ................
  1327. 00000090 FDFF0300 FDFF0200 FFFF0100 0000FFFF ................
  1328. */
  1329. // SD library on Teensy3 at 96 MHz
  1330. // 256 byte chunks, speed is 443272 bytes/sec
  1331. // 512 byte chunks, speed is 468023 bytes/sec
  1332. bool AudioPlaySDcardWAV::parse_format(void)
  1333. {
  1334. uint8_t num = 0;
  1335. uint16_t format;
  1336. uint16_t channels;
  1337. uint32_t rate;
  1338. uint16_t bits;
  1339. format = header[0];
  1340. //Serial.print(" format = ");
  1341. //Serial.println(format);
  1342. if (format != 1) return false;
  1343. channels = header[0] >> 16;
  1344. //Serial.print(" channels = ");
  1345. //Serial.println(channels);
  1346. if (channels == 1) {
  1347. } else if (channels == 2) {
  1348. num = 1;
  1349. } else {
  1350. return false;
  1351. }
  1352. bits = header[3] >> 16;
  1353. //Serial.print(" bits = ");
  1354. //Serial.println(bits);
  1355. if (bits == 8) {
  1356. } else if (bits == 16) {
  1357. num |= 2;
  1358. } else {
  1359. return false;
  1360. }
  1361. rate = header[1];
  1362. //Serial.print(" rate = ");
  1363. //Serial.println(rate);
  1364. if (rate == AUDIO_SAMPLE_RATE) {
  1365. } else if (rate >= 8000 && rate <= 48000) {
  1366. num |= 4;
  1367. } else {
  1368. return false;
  1369. }
  1370. // we're not checking the byte rate and block align fields
  1371. // if they're not the expected values, all we could do is
  1372. // return false. Do any real wav files have unexpected
  1373. // values in these other fields?
  1374. state_play = num;
  1375. return true;
  1376. }
  1377. /******************************************************************/
  1378. void AudioPlaySDcardRAW::begin(void)
  1379. {
  1380. playing = false;
  1381. if (block) {
  1382. release(block);
  1383. block = NULL;
  1384. }
  1385. }
  1386. bool AudioPlaySDcardRAW::play(const char *filename)
  1387. {
  1388. stop();
  1389. rawfile = SD.open(filename);
  1390. if (!rawfile) {
  1391. Serial.println("unable to open file");
  1392. return false;
  1393. }
  1394. Serial.println("able to open file");
  1395. playing = true;
  1396. return true;
  1397. }
  1398. void AudioPlaySDcardRAW::stop(void)
  1399. {
  1400. __disable_irq();
  1401. if (playing) {
  1402. playing = false;
  1403. __enable_irq();
  1404. rawfile.close();
  1405. } else {
  1406. __enable_irq();
  1407. }
  1408. }
  1409. void AudioPlaySDcardRAW::update(void)
  1410. {
  1411. unsigned int i, n;
  1412. // only update if we're playing
  1413. if (!playing) return;
  1414. // allocate the audio blocks to transmit
  1415. block = allocate();
  1416. if (block == NULL) return;
  1417. if (rawfile.available()) {
  1418. // we can read more data from the file...
  1419. n = rawfile.read(block->data, AUDIO_BLOCK_SAMPLES*2);
  1420. for (i=n/2; i < AUDIO_BLOCK_SAMPLES; i++) {
  1421. block->data[i] = 0;
  1422. }
  1423. transmit(block);
  1424. release(block);
  1425. } else {
  1426. rawfile.close();
  1427. playing = false;
  1428. }
  1429. }
  1430. /******************************************************************/
  1431. void AudioPlayMemory::play(const unsigned int *data)
  1432. {
  1433. uint32_t format;
  1434. playing = 0;
  1435. prior = 0;
  1436. format = *data++;
  1437. next = data;
  1438. length = format & 0xFFFFFF;
  1439. playing = format >> 24;
  1440. }
  1441. void AudioPlayMemory::stop(void)
  1442. {
  1443. playing = 0;
  1444. }
  1445. extern "C" {
  1446. extern const int16_t ulaw_decode_table[256];
  1447. };
  1448. void AudioPlayMemory::update(void)
  1449. {
  1450. audio_block_t *block;
  1451. const unsigned int *in;
  1452. int16_t *out;
  1453. uint32_t tmp32, consumed;
  1454. int16_t s0, s1, s2, s3, s4;
  1455. int i;
  1456. if (!playing) return;
  1457. block = allocate();
  1458. if (block == NULL) return;
  1459. //Serial.write('.');
  1460. out = block->data;
  1461. in = next;
  1462. s0 = prior;
  1463. switch (playing) {
  1464. case 0x01: // u-law encoded, 44100 Hz
  1465. for (i=0; i < AUDIO_BLOCK_SAMPLES; i += 4) {
  1466. tmp32 = *in++;
  1467. *out++ = ulaw_decode_table[(tmp32 >> 0) & 255];
  1468. *out++ = ulaw_decode_table[(tmp32 >> 8) & 255];
  1469. *out++ = ulaw_decode_table[(tmp32 >> 16) & 255];
  1470. *out++ = ulaw_decode_table[(tmp32 >> 24) & 255];
  1471. }
  1472. consumed = 128;
  1473. break;
  1474. case 0x81: // 16 bit PCM, 44100 Hz
  1475. for (i=0; i < AUDIO_BLOCK_SAMPLES; i += 2) {
  1476. tmp32 = *in++;
  1477. *out++ = (int16_t)(tmp32 & 65535);
  1478. *out++ = (int16_t)(tmp32 >> 16);
  1479. }
  1480. consumed = 128;
  1481. break;
  1482. case 0x02: // u-law encoded, 22050 Hz
  1483. for (i=0; i < AUDIO_BLOCK_SAMPLES; i += 8) {
  1484. tmp32 = *in++;
  1485. s1 = ulaw_decode_table[(tmp32 >> 0) & 255];
  1486. s2 = ulaw_decode_table[(tmp32 >> 8) & 255];
  1487. s3 = ulaw_decode_table[(tmp32 >> 16) & 255];
  1488. s4 = ulaw_decode_table[(tmp32 >> 24) & 255];
  1489. *out++ = (s0 + s1) >> 1;
  1490. *out++ = s1;
  1491. *out++ = (s1 + s2) >> 1;
  1492. *out++ = s2;
  1493. *out++ = (s2 + s3) >> 1;
  1494. *out++ = s3;
  1495. *out++ = (s3 + s4) >> 1;
  1496. *out++ = s4;
  1497. s0 = s4;
  1498. }
  1499. consumed = 64;
  1500. break;
  1501. case 0x82: // 16 bits PCM, 22050 Hz
  1502. for (i=0; i < AUDIO_BLOCK_SAMPLES; i += 4) {
  1503. tmp32 = *in++;
  1504. s1 = (int16_t)(tmp32 & 65535);
  1505. s2 = (int16_t)(tmp32 >> 16);
  1506. *out++ = (s0 + s1) >> 1;
  1507. *out++ = s1;
  1508. *out++ = (s1 + s2) >> 1;
  1509. *out++ = s2;
  1510. s0 = s2;
  1511. }
  1512. consumed = 64;
  1513. break;
  1514. case 0x03: // u-law encoded, 11025 Hz
  1515. for (i=0; i < AUDIO_BLOCK_SAMPLES; i += 16) {
  1516. tmp32 = *in++;
  1517. s1 = ulaw_decode_table[(tmp32 >> 0) & 255];
  1518. s2 = ulaw_decode_table[(tmp32 >> 8) & 255];
  1519. s3 = ulaw_decode_table[(tmp32 >> 16) & 255];
  1520. s4 = ulaw_decode_table[(tmp32 >> 24) & 255];
  1521. *out++ = (s0 * 3 + s1) >> 2;
  1522. *out++ = (s0 + s1) >> 1;
  1523. *out++ = (s0 + s1 * 3) >> 2;
  1524. *out++ = s1;
  1525. *out++ = (s1 * 3 + s2) >> 2;
  1526. *out++ = (s1 + s2) >> 1;
  1527. *out++ = (s1 + s2 * 3) >> 2;
  1528. *out++ = s2;
  1529. *out++ = (s2 * 3 + s3) >> 2;
  1530. *out++ = (s2 + s3) >> 1;
  1531. *out++ = (s2 + s3 * 3) >> 2;
  1532. *out++ = s3;
  1533. *out++ = (s3 * 3 + s4) >> 2;
  1534. *out++ = (s3 + s4) >> 1;
  1535. *out++ = (s3 + s4 * 3) >> 2;
  1536. *out++ = s4;
  1537. s0 = s4;
  1538. }
  1539. consumed = 32;
  1540. break;
  1541. case 0x83: // 16 bit PCM, 11025 Hz
  1542. for (i=0; i < AUDIO_BLOCK_SAMPLES; i += 8) {
  1543. tmp32 = *in++;
  1544. s1 = (int16_t)(tmp32 & 65535);
  1545. s2 = (int16_t)(tmp32 >> 16);
  1546. *out++ = (s0 * 3 + s1) >> 2;
  1547. *out++ = (s0 + s1) >> 1;
  1548. *out++ = (s0 + s1 * 3) >> 2;
  1549. *out++ = s1;
  1550. *out++ = (s1 * 3 + s2) >> 2;
  1551. *out++ = (s1 + s2) >> 1;
  1552. *out++ = (s1 + s2 * 3) >> 2;
  1553. *out++ = s2;
  1554. s0 = s2;
  1555. }
  1556. consumed = 32;
  1557. break;
  1558. default:
  1559. release(block);
  1560. playing = 0;
  1561. return;
  1562. }
  1563. prior = s0;
  1564. next = in;
  1565. if (length > consumed) {
  1566. length -= consumed;
  1567. } else {
  1568. playing = 0;
  1569. }
  1570. transmit(block);
  1571. release(block);
  1572. }
  1573. /******************************************************************/
  1574. // computes ((a[31:0] * b[15:0]) >> 16)
  1575. static inline int32_t signed_multiply_32x16b(int32_t a, uint32_t b) __attribute__((always_inline));
  1576. static inline int32_t signed_multiply_32x16b(int32_t a, uint32_t b)
  1577. {
  1578. int32_t out;
  1579. asm volatile("smulwb %0, %1, %2" : "=r" (out) : "r" (a), "r" (b));
  1580. return out;
  1581. }
  1582. // computes ((a[31:0] * b[31:16]) >> 16)
  1583. static inline int32_t signed_multiply_32x16t(int32_t a, uint32_t b) __attribute__((always_inline));
  1584. static inline int32_t signed_multiply_32x16t(int32_t a, uint32_t b)
  1585. {
  1586. int32_t out;
  1587. asm volatile("smulwt %0, %1, %2" : "=r" (out) : "r" (a), "r" (b));
  1588. return out;
  1589. }
  1590. // computes ((a[15:0) << 16) | b[15:0])
  1591. static inline uint32_t pack_16x16(int32_t a, int32_t b) __attribute__((always_inline));
  1592. static inline uint32_t pack_16x16(int32_t a, int32_t b)
  1593. {
  1594. int32_t out;
  1595. asm volatile("pkhbt %0, %1, %2, lsl #16" : "=r" (out) : "r" (b), "r" (a));
  1596. return out;
  1597. }
  1598. // computes (((a[31:16] + b[31:16]) << 16) | (a[15:0 + b[15:0]))
  1599. static inline uint32_t signed_add_16_and_16(uint32_t a, uint32_t b) __attribute__((always_inline));
  1600. static inline uint32_t signed_add_16_and_16(uint32_t a, uint32_t b)
  1601. {
  1602. int32_t out;
  1603. asm volatile("qadd16 %0, %1, %2" : "=r" (out) : "r" (a), "r" (b));
  1604. return out;
  1605. }
  1606. void applyGain(int16_t *data, int32_t mult)
  1607. {
  1608. uint32_t *p = (uint32_t *)data;
  1609. const uint32_t *end = (uint32_t *)(data + AUDIO_BLOCK_SAMPLES);
  1610. do {
  1611. uint32_t tmp32 = *p; // read 2 samples from *data
  1612. int32_t val1 = signed_multiply_32x16b(mult, tmp32);
  1613. int32_t val2 = signed_multiply_32x16t(mult, tmp32);
  1614. val1 = signed_saturate_rshift(val1, 16, 0);
  1615. val2 = signed_saturate_rshift(val2, 16, 0);
  1616. *p++ = pack_16x16(val2, val1);
  1617. } while (p < end);
  1618. }
  1619. // page 133
  1620. void applyGainThenAdd(int16_t *data, const int16_t *in, int32_t mult)
  1621. {
  1622. uint32_t *dst = (uint32_t *)data;
  1623. const uint32_t *src = (uint32_t *)in;
  1624. const uint32_t *end = (uint32_t *)(data + AUDIO_BLOCK_SAMPLES);
  1625. if (mult == 65536) {
  1626. do {
  1627. uint32_t tmp32 = *dst;
  1628. *dst++ = signed_add_16_and_16(tmp32, *src++);
  1629. tmp32 = *dst;
  1630. *dst++ = signed_add_16_and_16(tmp32, *src++);
  1631. } while (dst < end);
  1632. } else {
  1633. do {
  1634. uint32_t tmp32 = *src++; // read 2 samples from *data
  1635. int32_t val1 = signed_multiply_32x16b(mult, tmp32);
  1636. int32_t val2 = signed_multiply_32x16t(mult, tmp32);
  1637. val1 = signed_saturate_rshift(val1, 16, 0);
  1638. val2 = signed_saturate_rshift(val2, 16, 0);
  1639. tmp32 = pack_16x16(val2, val1);
  1640. uint32_t tmp32b = *dst;
  1641. *dst++ = signed_add_16_and_16(tmp32, tmp32b);
  1642. } while (dst < end);
  1643. }
  1644. }
  1645. void AudioMixer4::update(void)
  1646. {
  1647. audio_block_t *in, *out=NULL;
  1648. unsigned int channel;
  1649. for (channel=0; channel < 4; channel++) {
  1650. if (!out) {
  1651. out = receiveWritable(channel);
  1652. if (out) {
  1653. int32_t mult = multiplier[channel];
  1654. if (mult != 65536) applyGain(out->data, mult);
  1655. }
  1656. } else {
  1657. in = receiveReadOnly(channel);
  1658. if (in) {
  1659. applyGainThenAdd(out->data, in->data, multiplier[channel]);
  1660. release(in);
  1661. }
  1662. }
  1663. }
  1664. if (out) {
  1665. transmit(out);
  1666. release(out);
  1667. }
  1668. }
  1669. /******************************************************************/
  1670. #include "Wire.h"
  1671. #define WM8731_I2C_ADDR 0x1A
  1672. //#define WM8731_I2C_ADDR 0x1B
  1673. #define WM8731_REG_LLINEIN 0
  1674. #define WM8731_REG_RLINEIN 1
  1675. #define WM8731_REG_LHEADOUT 2
  1676. #define WM8731_REG_RHEADOUT 3
  1677. #define WM8731_REG_ANALOG 4
  1678. #define WM8731_REG_DIGITAL 5
  1679. #define WM8731_REG_POWERDOWN 6
  1680. #define WM8731_REG_INTERFACE 7
  1681. #define WM8731_REG_SAMPLING 8
  1682. #define WM8731_REG_ACTIVE 9
  1683. #define WM8731_REG_RESET 15
  1684. bool AudioControlWM8731::enable(void)
  1685. {
  1686. Wire.begin();
  1687. delay(5);
  1688. //write(WM8731_REG_RESET, 0);
  1689. write(WM8731_REG_INTERFACE, 0x02); // I2S, 16 bit, MCLK slave
  1690. write(WM8731_REG_SAMPLING, 0x20); // 256*Fs, 44.1 kHz, MCLK/1
  1691. // In order to prevent pops, the DAC should first be soft-muted (DACMU),
  1692. // the output should then be de-selected from the line and headphone output
  1693. // (DACSEL), then the DAC powered down (DACPD).
  1694. write(WM8731_REG_DIGITAL, 0x08); // DAC soft mute
  1695. write(WM8731_REG_ANALOG, 0x00); // disable all
  1696. write(WM8731_REG_POWERDOWN, 0x60); // linein, mic, adc, dac, lineout
  1697. write(WM8731_REG_LHEADOUT, 0x80); // volume off
  1698. write(WM8731_REG_RHEADOUT, 0x80);
  1699. delay(100); // how long to power up?
  1700. write(WM8731_REG_ACTIVE, 1);
  1701. delay(5);
  1702. write(WM8731_REG_DIGITAL, 0x00); // DAC unmuted
  1703. write(WM8731_REG_ANALOG, 0x10); // DAC selected
  1704. return true;
  1705. }
  1706. bool AudioControlWM8731::write(unsigned int reg, unsigned int val)
  1707. {
  1708. Wire.beginTransmission(WM8731_I2C_ADDR);
  1709. Wire.write((reg << 1) | ((val >> 8) & 1));
  1710. Wire.write(val & 0xFF);
  1711. Wire.endTransmission();
  1712. return true;
  1713. }
  1714. bool AudioControlWM8731::volumeInteger(unsigned int n)
  1715. {
  1716. if (n > 127) n = 127;
  1717. //Serial.print("volumeInteger, n = ");
  1718. //Serial.println(n);
  1719. write(WM8731_REG_LHEADOUT, n | 0x180);
  1720. write(WM8731_REG_RHEADOUT, n | 0x80);
  1721. return true;
  1722. }
  1723. /******************************************************************/
  1724. #define CHIP_ID 0x0000
  1725. // 15:8 PARTID 0xA0 - 8 bit identifier for SGTL5000
  1726. // 7:0 REVID 0x00 - revision number for SGTL5000.
  1727. #define CHIP_DIG_POWER 0x0002
  1728. // 6 ADC_POWERUP 1=Enable, 0=disable the ADC block, both digital & analog,
  1729. // 5 DAC_POWERUP 1=Enable, 0=disable the DAC block, both analog and digital
  1730. // 4 DAP_POWERUP 1=Enable, 0=disable the DAP block
  1731. // 1 I2S_OUT_POWERUP 1=Enable, 0=disable the I2S data output
  1732. // 0 I2S_IN_POWERUP 1=Enable, 0=disable the I2S data input
  1733. #define CHIP_CLK_CTRL 0x0004
  1734. // 5:4 RATE_MODE Sets the sample rate mode. MCLK_FREQ is still specified
  1735. // relative to the rate in SYS_FS
  1736. // 0x0 = SYS_FS specifies the rate
  1737. // 0x1 = Rate is 1/2 of the SYS_FS rate
  1738. // 0x2 = Rate is 1/4 of the SYS_FS rate
  1739. // 0x3 = Rate is 1/6 of the SYS_FS rate
  1740. // 3:2 SYS_FS Sets the internal system sample rate (default=2)
  1741. // 0x0 = 32 kHz
  1742. // 0x1 = 44.1 kHz
  1743. // 0x2 = 48 kHz
  1744. // 0x3 = 96 kHz
  1745. // 1:0 MCLK_FREQ Identifies incoming SYS_MCLK frequency and if the PLL should be used
  1746. // 0x0 = 256*Fs
  1747. // 0x1 = 384*Fs
  1748. // 0x2 = 512*Fs
  1749. // 0x3 = Use PLL
  1750. // The 0x3 (Use PLL) setting must be used if the SYS_MCLK is not
  1751. // a standard multiple of Fs (256, 384, or 512). This setting can
  1752. // also be used if SYS_MCLK is a standard multiple of Fs.
  1753. // Before this field is set to 0x3 (Use PLL), the PLL must be
  1754. // powered up by setting CHIP_ANA_POWER->PLL_POWERUP and
  1755. // CHIP_ANA_POWER->VCOAMP_POWERUP. Also, the PLL dividers must
  1756. // be calculated based on the external MCLK rate and
  1757. // CHIP_PLL_CTRL register must be set (see CHIP_PLL_CTRL register
  1758. // description details on how to calculate the divisors).
  1759. #define CHIP_I2S_CTRL 0x0006
  1760. // 8 SCLKFREQ Sets frequency of I2S_SCLK when in master mode (MS=1). When in slave
  1761. // mode (MS=0), this field must be set appropriately to match SCLK input
  1762. // rate.
  1763. // 0x0 = 64Fs
  1764. // 0x1 = 32Fs - Not supported for RJ mode (I2S_MODE = 1)
  1765. // 7 MS Configures master or slave of I2S_LRCLK and I2S_SCLK.
  1766. // 0x0 = Slave: I2S_LRCLK an I2S_SCLK are inputs
  1767. // 0x1 = Master: I2S_LRCLK and I2S_SCLK are outputs
  1768. // NOTE: If the PLL is used (CHIP_CLK_CTRL->MCLK_FREQ==0x3),
  1769. // the SGTL5000 must be a master of the I2S port (MS==1)
  1770. // 6 SCLK_INV Sets the edge that data (input and output) is clocked in on for I2S_SCLK
  1771. // 0x0 = data is valid on rising edge of I2S_SCLK
  1772. // 0x1 = data is valid on falling edge of I2S_SCLK
  1773. // 5:4 DLEN I2S data length (default=1)
  1774. // 0x0 = 32 bits (only valid when SCLKFREQ=0),
  1775. // not valid for Right Justified Mode
  1776. // 0x1 = 24 bits (only valid when SCLKFREQ=0)
  1777. // 0x2 = 20 bits
  1778. // 0x3 = 16 bits
  1779. // 3:2 I2S_MODE Sets the mode for the I2S port
  1780. // 0x0 = I2S mode or Left Justified (Use LRALIGN to select)
  1781. // 0x1 = Right Justified Mode
  1782. // 0x2 = PCM Format A/B
  1783. // 0x3 = RESERVED
  1784. // 1 LRALIGN I2S_LRCLK Alignment to data word. Not used for Right Justified mode
  1785. // 0x0 = Data word starts 1 I2S_SCLK delay after I2S_LRCLK
  1786. // transition (I2S format, PCM format A)
  1787. // 0x1 = Data word starts after I2S_LRCLK transition (left
  1788. // justified format, PCM format B)
  1789. // 0 LRPOL I2S_LRCLK Polarity when data is presented.
  1790. // 0x0 = I2S_LRCLK = 0 - Left, 1 - Right
  1791. // 1x0 = I2S_LRCLK = 0 - Right, 1 - Left
  1792. // The left subframe should be presented first regardless of
  1793. // the setting of LRPOL.
  1794. #define CHIP_SSS_CTRL 0x000A
  1795. // 14 DAP_MIX_LRSWAP DAP Mixer Input Swap
  1796. // 0x0 = Normal Operation
  1797. // 0x1 = Left and Right channels for the DAP MIXER Input are swapped.
  1798. // 13 DAP_LRSWAP DAP Mixer Input Swap
  1799. // 0x0 = Normal Operation
  1800. // 0x1 = Left and Right channels for the DAP Input are swapped
  1801. // 12 DAC_LRSWAP DAC Input Swap
  1802. // 0x0 = Normal Operation
  1803. // 0x1 = Left and Right channels for the DAC are swapped
  1804. // 10 I2S_LRSWAP I2S_DOUT Swap
  1805. // 0x0 = Normal Operation
  1806. // 0x1 = Left and Right channels for the I2S_DOUT are swapped
  1807. // 9:8 DAP_MIX_SELECT Select data source for DAP mixer
  1808. // 0x0 = ADC
  1809. // 0x1 = I2S_IN
  1810. // 0x2 = Reserved
  1811. // 0x3 = Reserved
  1812. // 7:6 DAP_SELECT Select data source for DAP
  1813. // 0x0 = ADC
  1814. // 0x1 = I2S_IN
  1815. // 0x2 = Reserved
  1816. // 0x3 = Reserved
  1817. // 5:4 DAC_SELECT Select data source for DAC (default=1)
  1818. // 0x0 = ADC
  1819. // 0x1 = I2S_IN
  1820. // 0x2 = Reserved
  1821. // 0x3 = DAP
  1822. // 1:0 I2S_SELECT Select data source for I2S_DOUT
  1823. // 0x0 = ADC
  1824. // 0x1 = I2S_IN
  1825. // 0x2 = Reserved
  1826. // 0x3 = DAP
  1827. #define CHIP_ADCDAC_CTRL 0x000E
  1828. // 13 VOL_BUSY_DAC_RIGHT Volume Busy DAC Right
  1829. // 0x0 = Ready
  1830. // 0x1 = Busy - This indicates the channel has not reached its
  1831. // programmed volume/mute level
  1832. // 12 VOL_BUSY_DAC_LEFT Volume Busy DAC Left
  1833. // 0x0 = Ready
  1834. // 0x1 = Busy - This indicates the channel has not reached its
  1835. // programmed volume/mute level
  1836. // 9 VOL_RAMP_EN Volume Ramp Enable (default=1)
  1837. // 0x0 = Disables volume ramp. New volume settings take immediate
  1838. // effect without a ramp
  1839. // 0x1 = Enables volume ramp
  1840. // This field affects DAC_VOL. The volume ramp effects both
  1841. // volume settings and mute When set to 1 a soft mute is enabled.
  1842. // 8 VOL_EXPO_RAMP Exponential Volume Ramp Enable
  1843. // 0x0 = Linear ramp over top 4 volume octaves
  1844. // 0x1 = Exponential ramp over full volume range
  1845. // This bit only takes effect if VOL_RAMP_EN is 1.
  1846. // 3 DAC_MUTE_RIGHT DAC Right Mute (default=1)
  1847. // 0x0 = Unmute
  1848. // 0x1 = Muted
  1849. // If VOL_RAMP_EN = 1, this is a soft mute.
  1850. // 2 DAC_MUTE_LEFT DAC Left Mute (default=1)
  1851. // 0x0 = Unmute
  1852. // 0x1 = Muted
  1853. // If VOL_RAMP_EN = 1, this is a soft mute.
  1854. // 1 ADC_HPF_FREEZE ADC High Pass Filter Freeze
  1855. // 0x0 = Normal operation
  1856. // 0x1 = Freeze the ADC high-pass filter offset register. The
  1857. // offset continues to be subtracted from the ADC data stream.
  1858. // 0 ADC_HPF_BYPASS ADC High Pass Filter Bypass
  1859. // 0x0 = Normal operation
  1860. // 0x1 = Bypassed and offset not updated
  1861. #define CHIP_DAC_VOL 0x0010
  1862. // 15:8 DAC_VOL_RIGHT DAC Right Channel Volume. Set the Right channel DAC volume
  1863. // with 0.5017 dB steps from 0 to -90 dB
  1864. // 0x3B and less = Reserved
  1865. // 0x3C = 0 dB
  1866. // 0x3D = -0.5 dB
  1867. // 0xF0 = -90 dB
  1868. // 0xFC and greater = Muted
  1869. // If VOL_RAMP_EN = 1, there is an automatic ramp to the
  1870. // new volume setting.
  1871. // 7:0 DAC_VOL_LEFT DAC Left Channel Volume. Set the Left channel DAC volume
  1872. // with 0.5017 dB steps from 0 to -90 dB
  1873. // 0x3B and less = Reserved
  1874. // 0x3C = 0 dB
  1875. // 0x3D = -0.5 dB
  1876. // 0xF0 = -90 dB
  1877. // 0xFC and greater = Muted
  1878. // If VOL_RAMP_EN = 1, there is an automatic ramp to the
  1879. // new volume setting.
  1880. #define CHIP_PAD_STRENGTH 0x0014
  1881. // 9:8 I2S_LRCLK I2S LRCLK Pad Drive Strength (default=1)
  1882. // Sets drive strength for output pads per the table below.
  1883. // VDDIO 1.8 V 2.5 V 3.3 V
  1884. // 0x0 = Disable
  1885. // 0x1 = 1.66 mA 2.87 mA 4.02 mA
  1886. // 0x2 = 3.33 mA 5.74 mA 8.03 mA
  1887. // 0x3 = 4.99 mA 8.61 mA 12.05 mA
  1888. // 7:6 I2S_SCLK I2S SCLK Pad Drive Strength (default=1)
  1889. // 5:4 I2S_DOUT I2S DOUT Pad Drive Strength (default=1)
  1890. // 3:2 CTRL_DATA I2C DATA Pad Drive Strength (default=3)
  1891. // 1:0 CTRL_CLK I2C CLK Pad Drive Strength (default=3)
  1892. // (all use same table as I2S_LRCLK)
  1893. #define CHIP_ANA_ADC_CTRL 0x0020
  1894. // 8 ADC_VOL_M6DB ADC Volume Range Reduction
  1895. // This bit shifts both right and left analog ADC volume
  1896. // range down by 6.0 dB.
  1897. // 0x0 = No change in ADC range
  1898. // 0x1 = ADC range reduced by 6.0 dB
  1899. // 7:4 ADC_VOL_RIGHT ADC Right Channel Volume
  1900. // Right channel analog ADC volume control in 1.5 dB steps.
  1901. // 0x0 = 0 dB
  1902. // 0x1 = +1.5 dB
  1903. // ...
  1904. // 0xF = +22.5 dB
  1905. // This range is -6.0 dB to +16.5 dB if ADC_VOL_M6DB is set to 1.
  1906. // 3:0 ADC_VOL_LEFT ADC Left Channel Volume
  1907. // (same scale as ADC_VOL_RIGHT)
  1908. #define CHIP_ANA_HP_CTRL 0x0022
  1909. // 14:8 HP_VOL_RIGHT Headphone Right Channel Volume (default 0x18)
  1910. // Right channel headphone volume control with 0.5 dB steps.
  1911. // 0x00 = +12 dB
  1912. // 0x01 = +11.5 dB
  1913. // 0x18 = 0 dB
  1914. // ...
  1915. // 0x7F = -51.5 dB
  1916. // 6:0 HP_VOL_LEFT Headphone Left Channel Volume (default 0x18)
  1917. // (same scale as HP_VOL_RIGHT)
  1918. #define CHIP_ANA_CTRL 0x0024
  1919. // 8 MUTE_LO LINEOUT Mute, 0 = Unmute, 1 = Mute (default 1)
  1920. // 6 SELECT_HP Select the headphone input, 0 = DAC, 1 = LINEIN
  1921. // 5 EN_ZCD_HP Enable the headphone zero cross detector (ZCD)
  1922. // 0x0 = HP ZCD disabled
  1923. // 0x1 = HP ZCD enabled
  1924. // 4 MUTE_HP Mute the headphone outputs, 0 = Unmute, 1 = Mute (default)
  1925. // 2 SELECT_ADC Select the ADC input, 0 = Microphone, 1 = LINEIN
  1926. // 1 EN_ZCD_ADC Enable the ADC analog zero cross detector (ZCD)
  1927. // 0x0 = ADC ZCD disabled
  1928. // 0x1 = ADC ZCD enabled
  1929. // 0 MUTE_ADC Mute the ADC analog volume, 0 = Unmute, 1 = Mute (default)
  1930. #define CHIP_LINREG_CTRL 0x0026
  1931. // 6 VDDC_MAN_ASSN Determines chargepump source when VDDC_ASSN_OVRD is set.
  1932. // 0x0 = VDDA
  1933. // 0x1 = VDDIO
  1934. // 5 VDDC_ASSN_OVRD Charge pump Source Assignment Override
  1935. // 0x0 = Charge pump source is automatically assigned based
  1936. // on higher of VDDA and VDDIO
  1937. // 0x1 = the source of charge pump is manually assigned by
  1938. // VDDC_MAN_ASSN If VDDIO and VDDA are both the same
  1939. // and greater than 3.1 V, VDDC_ASSN_OVRD and
  1940. // VDDC_MAN_ASSN should be used to manually assign
  1941. // VDDIO as the source for charge pump.
  1942. // 3:0 D_PROGRAMMING Sets the VDDD linear regulator output voltage in 50 mV steps.
  1943. // Must clear the LINREG_SIMPLE_POWERUP and STARTUP_POWERUP bits
  1944. // in the 0x0030 (CHIP_ANA_POWER) register after power-up, for
  1945. // this setting to produce the proper VDDD voltage.
  1946. // 0x0 = 1.60
  1947. // 0xF = 0.85
  1948. #define CHIP_REF_CTRL 0x0028 // bandgap reference bias voltage and currents
  1949. // 8:4 VAG_VAL Analog Ground Voltage Control
  1950. // These bits control the analog ground voltage in 25 mV steps.
  1951. // This should usually be set to VDDA/2 or lower for best
  1952. // performance (maximum output swing at minimum THD). This VAG
  1953. // reference is also used for the DAC and ADC voltage reference.
  1954. // So changing this voltage scales the output swing of the DAC
  1955. // and the output signal of the ADC.
  1956. // 0x00 = 0.800 V
  1957. // 0x1F = 1.575 V
  1958. // 3:1 BIAS_CTRL Bias control
  1959. // These bits adjust the bias currents for all of the analog
  1960. // blocks. By lowering the bias current a lower quiescent power
  1961. // is achieved. It should be noted that this mode can affect
  1962. // performance by 3-4 dB.
  1963. // 0x0 = Nominal
  1964. // 0x1-0x3=+12.5%
  1965. // 0x4=-12.5%
  1966. // 0x5=-25%
  1967. // 0x6=-37.5%
  1968. // 0x7=-50%
  1969. // 0 SMALL_POP VAG Ramp Control
  1970. // Setting this bit slows down the VAG ramp from ~200 to ~400 ms
  1971. // to reduce the startup pop, but increases the turn on/off time.
  1972. // 0x0 = Normal VAG ramp
  1973. // 0x1 = Slow down VAG ramp
  1974. #define CHIP_MIC_CTRL 0x002A // microphone gain & internal microphone bias
  1975. // 9:8 BIAS_RESISTOR MIC Bias Output Impedance Adjustment
  1976. // Controls an adjustable output impedance for the microphone bias.
  1977. // If this is set to zero the micbias block is powered off and
  1978. // the output is highZ.
  1979. // 0x0 = Powered off
  1980. // 0x1 = 2.0 kohm
  1981. // 0x2 = 4.0 kohm
  1982. // 0x3 = 8.0 kohm
  1983. // 6:4 BIAS_VOLT MIC Bias Voltage Adjustment
  1984. // Controls an adjustable bias voltage for the microphone bias
  1985. // amp in 250 mV steps. This bias voltage setting should be no
  1986. // more than VDDA-200 mV for adequate power supply rejection.
  1987. // 0x0 = 1.25 V
  1988. // ...
  1989. // 0x7 = 3.00 V
  1990. // 1:0 GAIN MIC Amplifier Gain
  1991. // Sets the microphone amplifier gain. At 0 dB setting the THD
  1992. // can be slightly higher than other paths- typically around
  1993. // ~65 dB. At other gain settings the THD are better.
  1994. // 0x0 = 0 dB
  1995. // 0x1 = +20 dB
  1996. // 0x2 = +30 dB
  1997. // 0x3 = +40 dB
  1998. #define CHIP_LINE_OUT_CTRL 0x002C
  1999. // 11:8 OUT_CURRENT Controls the output bias current for the LINEOUT amplifiers. The
  2000. // nominal recommended setting for a 10 kohm load with 1.0 nF load cap
  2001. // is 0x3. There are only 5 valid settings.
  2002. // 0x0=0.18 mA
  2003. // 0x1=0.27 mA
  2004. // 0x3=0.36 mA
  2005. // 0x7=0.45 mA
  2006. // 0xF=0.54 mA
  2007. // 5:0 LO_VAGCNTRL LINEOUT Amplifier Analog Ground Voltage
  2008. // Controls the analog ground voltage for the LINEOUT amplifiers
  2009. // in 25 mV steps. This should usually be set to VDDIO/2.
  2010. // 0x00 = 0.800 V
  2011. // ...
  2012. // 0x1F = 1.575 V
  2013. // ...
  2014. // 0x23 = 1.675 V
  2015. // 0x24-0x3F are invalid
  2016. #define CHIP_LINE_OUT_VOL 0x002E
  2017. // 12:8 LO_VOL_RIGHT LINEOUT Right Channel Volume (default=4)
  2018. // Controls the right channel LINEOUT volume in 0.5 dB steps.
  2019. // Higher codes have more attenuation.
  2020. // 4:0 LO_VOL_LEFT LINEOUT Left Channel Output Level (default=4)
  2021. // Used to normalize the output level of the left line output
  2022. // to full scale based on the values used to set
  2023. // LINE_OUT_CTRL->LO_VAGCNTRL and CHIP_REF_CTRL->VAG_VAL.
  2024. // In general this field should be set to:
  2025. // 40*log((VAG_VAL)/(LO_VAGCNTRL)) + 15
  2026. // Suggested values based on typical VDDIO and VDDA voltages.
  2027. // VDDA VAG_VAL VDDIO LO_VAGCNTRL LO_VOL_*
  2028. // 1.8 V 0.9 3.3 V 1.55 0x06
  2029. // 1.8 V 0.9 1.8 V 0.9 0x0F
  2030. // 3.3 V 1.55 1.8 V 0.9 0x19
  2031. // 3.3 V 1.55 3.3 V 1.55 0x0F
  2032. // After setting to the nominal voltage, this field can be used
  2033. // to adjust the output level in +/-0.5 dB increments by using
  2034. // values higher or lower than the nominal setting.
  2035. #define CHIP_ANA_POWER 0x0030 // power down controls for the analog blocks.
  2036. // The only other power-down controls are BIAS_RESISTOR in the MIC_CTRL register
  2037. // and the EN_ZCD control bits in ANA_CTRL.
  2038. // 14 DAC_MONO While DAC_POWERUP is set, this allows the DAC to be put into left only
  2039. // mono operation for power savings. 0=mono, 1=stereo (default)
  2040. // 13 LINREG_SIMPLE_POWERUP Power up the simple (low power) digital supply regulator.
  2041. // After reset, this bit can be cleared IF VDDD is driven
  2042. // externally OR the primary digital linreg is enabled with
  2043. // LINREG_D_POWERUP
  2044. // 12 STARTUP_POWERUP Power up the circuitry needed during the power up ramp and reset.
  2045. // After reset this bit can be cleared if VDDD is coming from
  2046. // an external source.
  2047. // 11 VDDC_CHRGPMP_POWERUP Power up the VDDC charge pump block. If neither VDDA or VDDIO
  2048. // is 3.0 V or larger this bit should be cleared before analog
  2049. // blocks are powered up.
  2050. // 10 PLL_POWERUP PLL Power Up, 0 = Power down, 1 = Power up
  2051. // When cleared, the PLL is turned off. This must be set before
  2052. // CHIP_CLK_CTRL->MCLK_FREQ is programmed to 0x3. The
  2053. // CHIP_PLL_CTRL register must be configured correctly before
  2054. // setting this bit.
  2055. // 9 LINREG_D_POWERUP Power up the primary VDDD linear regulator, 0 = Power down, 1 = Power up
  2056. // 8 VCOAMP_POWERUP Power up the PLL VCO amplifier, 0 = Power down, 1 = Power up
  2057. // 7 VAG_POWERUP Power up the VAG reference buffer.
  2058. // Setting this bit starts the power up ramp for the headphone
  2059. // and LINEOUT. The headphone (and/or LINEOUT) powerup should
  2060. // be set BEFORE clearing this bit. When this bit is cleared
  2061. // the power-down ramp is started. The headphone (and/or LINEOUT)
  2062. // powerup should stay set until the VAG is fully ramped down
  2063. // (200 to 400 ms after clearing this bit).
  2064. // 0x0 = Power down, 0x1 = Power up
  2065. // 6 ADC_MONO While ADC_POWERUP is set, this allows the ADC to be put into left only
  2066. // mono operation for power savings. This mode is useful when
  2067. // only using the microphone input.
  2068. // 0x0 = Mono (left only), 0x1 = Stereo
  2069. // 5 REFTOP_POWERUP Power up the reference bias currents
  2070. // 0x0 = Power down, 0x1 = Power up
  2071. // This bit can be cleared when the part is a sleep state
  2072. // to minimize analog power.
  2073. // 4 HEADPHONE_POWERUP Power up the headphone amplifiers
  2074. // 0x0 = Power down, 0x1 = Power up
  2075. // 3 DAC_POWERUP Power up the DACs
  2076. // 0x0 = Power down, 0x1 = Power up
  2077. // 2 CAPLESS_HEADPHONE_POWERUP Power up the capless headphone mode
  2078. // 0x0 = Power down, 0x1 = Power up
  2079. // 1 ADC_POWERUP Power up the ADCs
  2080. // 0x0 = Power down, 0x1 = Power up
  2081. // 0 LINEOUT_POWERUP Power up the LINEOUT amplifiers
  2082. // 0x0 = Power down, 0x1 = Power up
  2083. #define CHIP_PLL_CTRL 0x0032
  2084. // 15:11 INT_DIVISOR
  2085. // 10:0 FRAC_DIVISOR
  2086. #define CHIP_CLK_TOP_CTRL 0x0034
  2087. // 11 ENABLE_INT_OSC Setting this bit enables an internal oscillator to be used for the
  2088. // zero cross detectors, the short detect recovery, and the
  2089. // charge pump. This allows the I2S clock to be shut off while
  2090. // still operating an analog signal path. This bit can be kept
  2091. // on when the I2S clock is enabled, but the I2S clock is more
  2092. // accurate so it is preferred to clear this bit when I2S is present.
  2093. // 3 INPUT_FREQ_DIV2 SYS_MCLK divider before PLL input
  2094. // 0x0 = pass through
  2095. // 0x1 = SYS_MCLK is divided by 2 before entering PLL
  2096. // This must be set when the input clock is above 17 Mhz. This
  2097. // has no effect when the PLL is powered down.
  2098. #define CHIP_ANA_STATUS 0x0036
  2099. // 9 LRSHORT_STS This bit is high whenever a short is detected on the left or right
  2100. // channel headphone drivers.
  2101. // 8 CSHORT_STS This bit is high whenever a short is detected on the capless headphone
  2102. // common/center channel driver.
  2103. // 4 PLL_IS_LOCKED This bit goes high after the PLL is locked.
  2104. #define CHIP_ANA_TEST1 0x0038 // intended only for debug.
  2105. #define CHIP_ANA_TEST2 0x003A // intended only for debug.
  2106. #define CHIP_SHORT_CTRL 0x003C
  2107. // 14:12 LVLADJR Right channel headphone short detector in 25 mA steps.
  2108. // 0x3=25 mA
  2109. // 0x2=50 mA
  2110. // 0x1=75 mA
  2111. // 0x0=100 mA
  2112. // 0x4=125 mA
  2113. // 0x5=150 mA
  2114. // 0x6=175 mA
  2115. // 0x7=200 mA
  2116. // This trip point can vary by ~30% over process so leave plenty
  2117. // of guard band to avoid false trips. This short detect trip
  2118. // point is also effected by the bias current adjustments made
  2119. // by CHIP_REF_CTRL->BIAS_CTRL and by CHIP_ANA_TEST1->HP_IALL_ADJ.
  2120. // 10:8 LVLADJL Left channel headphone short detector in 25 mA steps.
  2121. // (same scale as LVLADJR)
  2122. // 6:4 LVLADJC Capless headphone center channel short detector in 50 mA steps.
  2123. // 0x3=50 mA
  2124. // 0x2=100 mA
  2125. // 0x1=150 mA
  2126. // 0x0=200 mA
  2127. // 0x4=250 mA
  2128. // 0x5=300 mA
  2129. // 0x6=350 mA
  2130. // 0x7=400 mA
  2131. // 3:2 MODE_LR Behavior of left/right short detection
  2132. // 0x0 = Disable short detector, reset short detect latch,
  2133. // software view non-latched short signal
  2134. // 0x1 = Enable short detector and reset the latch at timeout
  2135. // (every ~50 ms)
  2136. // 0x2 = This mode is not used/invalid
  2137. // 0x3 = Enable short detector with only manual reset (have
  2138. // to return to 0x0 to reset the latch)
  2139. // 1:0 MODE_CM Behavior of capless headphone central short detection
  2140. // (same settings as MODE_LR)
  2141. #define DAP_CONTROL 0x0100
  2142. #define DAP_PEQ 0x0102
  2143. #define DAP_BASS_ENHANCE 0x0104
  2144. #define DAP_BASS_ENHANCE_CTRL 0x0106
  2145. #define DAP_AUDIO_EQ 0x0108
  2146. #define DAP_SGTL_SURROUND 0x010A
  2147. #define DAP_FILTER_COEF_ACCES 0x010C
  2148. #define DAP_COEF_WR_B0_MSB 0x010E
  2149. #define DAP_COEF_WR_B0_LSB 0x0110
  2150. #define DAP_AUDIO_EQ_BASS_BAND0 0x0116 // 115 Hz
  2151. #define DAP_AUDIO_EQ_BAND1 0x0118 // 330 Hz
  2152. #define DAP_AUDIO_EQ_BAND2 0x011A // 990 Hz
  2153. #define DAP_AUDIO_EQ_BAND3 0x011C // 3000 Hz
  2154. #define DAP_AUDIO_EQ_TREBLE_BAND4 0x011E // 9900 Hz
  2155. #define DAP_MAIN_CHAN 0x0120
  2156. #define DAP_MIX_CHAN 0x0122
  2157. #define DAP_AVC_CTRL 0x0124
  2158. #define DAP_AVC_THRESHOLD 0x0126
  2159. #define DAP_AVC_ATTACK 0x0128
  2160. #define DAP_AVC_DECAY 0x012A
  2161. #define DAP_COEF_WR_B1_MSB 0x012C
  2162. #define DAP_COEF_WR_B1_LSB 0x012E
  2163. #define DAP_COEF_WR_B2_MSB 0x0130
  2164. #define DAP_COEF_WR_B2_LSB 0x0132
  2165. #define DAP_COEF_WR_A1_MSB 0x0134
  2166. #define DAP_COEF_WR_A1_LSB 0x0136
  2167. #define DAP_COEF_WR_A2_MSB 0x0138
  2168. #define DAP_COEF_WR_A2_LSB 0x013A
  2169. #define SGTL5000_I2C_ADDR 0x0A // CTRL_ADR0_CS pin low (normal configuration)
  2170. //#define SGTL5000_I2C_ADDR 0x2A // CTRL_ADR0_CS pin high
  2171. bool AudioControlSGTL5000::enable(void)
  2172. {
  2173. unsigned int n;
  2174. muted = true;
  2175. Wire.begin();
  2176. delay(5);
  2177. Serial.print("chip ID = ");
  2178. delay(5);
  2179. n = read(CHIP_ID);
  2180. Serial.println(n, HEX);
  2181. write(CHIP_ANA_POWER, 0x4060); // VDDD is externally driven with 1.8V
  2182. write(CHIP_LINREG_CTRL, 0x006C); // VDDA & VDDIO both over 3.1V
  2183. write(CHIP_REF_CTRL, 0x01F1); // VAG=1.575 slow ramp, normal bias current
  2184. write(CHIP_LINE_OUT_CTRL, 0x0322);
  2185. write(CHIP_SHORT_CTRL, 0x4446); // allow up to 125mA
  2186. write(CHIP_ANA_CTRL, 0x0137); // enable zero cross detectors
  2187. write(CHIP_ANA_POWER, 0x40FF); // power up: lineout, hp, adc, dac
  2188. write(CHIP_DIG_POWER, 0x0073); // power up all digital stuff
  2189. delay(400);
  2190. write(CHIP_LINE_OUT_VOL, 0x0505); // TODO: correct value for 3.3V
  2191. write(CHIP_CLK_CTRL, 0x0004); // 44.1 kHz, 256*Fs
  2192. write(CHIP_I2S_CTRL, 0x0130); // SCLK=32*Fs, 16bit, I2S format
  2193. // default signal routing is ok?
  2194. write(CHIP_SSS_CTRL, 0x0010); // ADC->I2S, I2S->DAC
  2195. write(CHIP_ADCDAC_CTRL, 0x0000); // disable dac mute
  2196. write(CHIP_DAC_VOL, 0x3C3C); // digital gain, 0dB
  2197. write(CHIP_ANA_HP_CTRL, 0x7F7F); // set volume (lowest level)
  2198. write(CHIP_ANA_CTRL, 0x0136); // enable zero cross detectors
  2199. //mute = false;
  2200. return true;
  2201. }
  2202. unsigned int AudioControlSGTL5000::read(unsigned int reg)
  2203. {
  2204. unsigned int val;
  2205. Wire.beginTransmission(SGTL5000_I2C_ADDR);
  2206. Wire.write(reg >> 8);
  2207. Wire.write(reg);
  2208. if (Wire.endTransmission(false) != 0) return 0;
  2209. if (Wire.requestFrom(SGTL5000_I2C_ADDR, 2) < 2) return 0;
  2210. val = Wire.read() << 8;
  2211. val |= Wire.read();
  2212. return val;
  2213. }
  2214. bool AudioControlSGTL5000::write(unsigned int reg, unsigned int val)
  2215. {
  2216. if (reg == CHIP_ANA_CTRL) ana_ctrl = val;
  2217. Wire.beginTransmission(SGTL5000_I2C_ADDR);
  2218. Wire.write(reg >> 8);
  2219. Wire.write(reg);
  2220. Wire.write(val >> 8);
  2221. Wire.write(val);
  2222. if (Wire.endTransmission() == 0) return true;
  2223. return false;
  2224. }
  2225. bool AudioControlSGTL5000::volumeInteger(unsigned int n)
  2226. {
  2227. if (n == 0) {
  2228. muted = true;
  2229. write(CHIP_ANA_HP_CTRL, 0x7F7F);
  2230. return muteHeadphone();
  2231. } else if (n > 0x80) {
  2232. n = 0;
  2233. } else {
  2234. n = 0x80 - n;
  2235. }
  2236. if (muted) {
  2237. muted = false;
  2238. unmuteHeadphone();
  2239. }
  2240. n = n | (n << 8);
  2241. return write(CHIP_ANA_HP_CTRL, n); // set volume
  2242. }