You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

пре 11 година
пре 11 година
пре 11 година
пре 11 година
пре 11 година
пре 11 година
пре 11 година
пре 11 година
пре 11 година
пре 11 година
пре 11 година
пре 11 година
пре 11 година
пре 11 година
пре 11 година
пре 11 година
пре 11 година
пре 11 година
пре 10 година
пре 11 година
пре 11 година
пре 11 година
пре 10 година
пре 10 година
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054
  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. void AudioOutputI2Sslave::begin(void)
  581. {
  582. //pinMode(2, OUTPUT);
  583. block_left_1st = NULL;
  584. block_right_1st = NULL;
  585. AudioOutputI2Sslave::config_i2s();
  586. CORE_PIN22_CONFIG = PORT_PCR_MUX(6); // pin 22, PTC1, I2S0_TXD0
  587. DMA_CR = 0;
  588. DMA_TCD0_SADDR = i2s_tx_buffer;
  589. DMA_TCD0_SOFF = 2;
  590. DMA_TCD0_ATTR = DMA_TCD_ATTR_SSIZE(1) | DMA_TCD_ATTR_DSIZE(1);
  591. DMA_TCD0_NBYTES_MLNO = 2;
  592. DMA_TCD0_SLAST = -sizeof(i2s_tx_buffer);
  593. DMA_TCD0_DADDR = &I2S0_TDR0;
  594. DMA_TCD0_DOFF = 0;
  595. DMA_TCD0_CITER_ELINKNO = sizeof(i2s_tx_buffer) / 2;
  596. DMA_TCD0_DLASTSGA = 0;
  597. DMA_TCD0_BITER_ELINKNO = sizeof(i2s_tx_buffer) / 2;
  598. DMA_TCD0_CSR = DMA_TCD_CSR_INTHALF | DMA_TCD_CSR_INTMAJOR;
  599. DMAMUX0_CHCFG0 = DMAMUX_DISABLE;
  600. DMAMUX0_CHCFG0 = DMAMUX_SOURCE_I2S0_TX | DMAMUX_ENABLE;
  601. update_responsibility = update_setup();
  602. DMA_SERQ = 0;
  603. I2S0_TCSR |= I2S_TCSR_TE | I2S_TCSR_BCE | I2S_TCSR_FRDE | I2S_TCSR_FR;
  604. NVIC_ENABLE_IRQ(IRQ_DMA_CH0);
  605. }
  606. void AudioOutputI2Sslave::config_i2s(void)
  607. {
  608. SIM_SCGC6 |= SIM_SCGC6_I2S;
  609. SIM_SCGC7 |= SIM_SCGC7_DMA;
  610. SIM_SCGC6 |= SIM_SCGC6_DMAMUX;
  611. // if either transmitter or receiver is enabled, do nothing
  612. if (I2S0_TCSR & I2S_TCSR_TE) return;
  613. if (I2S0_RCSR & I2S_RCSR_RE) return;
  614. // Select input clock 0
  615. // Configure to input the bit-clock from pin, bypasses the MCLK divider
  616. I2S0_MCR = I2S_MCR_MICS(0);
  617. I2S0_MDR = 0;
  618. // configure transmitter
  619. I2S0_TMR = 0;
  620. I2S0_TCR1 = I2S_TCR1_TFW(1); // watermark at half fifo size
  621. I2S0_TCR2 = I2S_TCR2_SYNC(0) | I2S_TCR2_BCP;
  622. I2S0_TCR3 = I2S_TCR3_TCE;
  623. I2S0_TCR4 = I2S_TCR4_FRSZ(1) | I2S_TCR4_SYWD(15) | I2S_TCR4_MF
  624. | I2S_TCR4_FSE | I2S_TCR4_FSP;
  625. I2S0_TCR5 = I2S_TCR5_WNW(15) | I2S_TCR5_W0W(15) | I2S_TCR5_FBT(15);
  626. // configure receiver (sync'd to transmitter clocks)
  627. I2S0_RMR = 0;
  628. I2S0_RCR1 = I2S_RCR1_RFW(1);
  629. I2S0_RCR2 = I2S_RCR2_SYNC(1) | I2S_TCR2_BCP;
  630. I2S0_RCR3 = I2S_RCR3_RCE;
  631. I2S0_RCR4 = I2S_RCR4_FRSZ(1) | I2S_RCR4_SYWD(15) | I2S_RCR4_MF
  632. | I2S_RCR4_FSE | I2S_RCR4_FSP | I2S_RCR4_FSD;
  633. I2S0_RCR5 = I2S_RCR5_WNW(15) | I2S_RCR5_W0W(15) | I2S_RCR5_FBT(15);
  634. // configure pin mux for 3 clock signals
  635. CORE_PIN23_CONFIG = PORT_PCR_MUX(6); // pin 23, PTC2, I2S0_TX_FS (LRCLK)
  636. CORE_PIN9_CONFIG = PORT_PCR_MUX(6); // pin 9, PTC3, I2S0_TX_BCLK
  637. CORE_PIN11_CONFIG = PORT_PCR_MUX(6); // pin 11, PTC6, I2S0_MCLK
  638. }
  639. /******************************************************************/
  640. DMAMEM static uint32_t i2s_rx_buffer[AUDIO_BLOCK_SAMPLES];
  641. audio_block_t * AudioInputI2S::block_left = NULL;
  642. audio_block_t * AudioInputI2S::block_right = NULL;
  643. uint16_t AudioInputI2S::block_offset = 0;
  644. bool AudioInputI2S::update_responsibility = false;
  645. void AudioInputI2S::begin(void)
  646. {
  647. //block_left_1st = NULL;
  648. //block_right_1st = NULL;
  649. //pinMode(3, OUTPUT);
  650. //digitalWriteFast(3, HIGH);
  651. //delayMicroseconds(500);
  652. //digitalWriteFast(3, LOW);
  653. AudioOutputI2S::config_i2s();
  654. CORE_PIN13_CONFIG = PORT_PCR_MUX(4); // pin 13, PTC5, I2S0_RXD0
  655. DMA_CR = 0;
  656. DMA_TCD1_SADDR = &I2S0_RDR0;
  657. DMA_TCD1_SOFF = 0;
  658. DMA_TCD1_ATTR = DMA_TCD_ATTR_SSIZE(1) | DMA_TCD_ATTR_DSIZE(1);
  659. DMA_TCD1_NBYTES_MLNO = 2;
  660. DMA_TCD1_SLAST = 0;
  661. DMA_TCD1_DADDR = i2s_rx_buffer;
  662. DMA_TCD1_DOFF = 2;
  663. DMA_TCD1_CITER_ELINKNO = sizeof(i2s_rx_buffer) / 2;
  664. DMA_TCD1_DLASTSGA = -sizeof(i2s_rx_buffer);
  665. DMA_TCD1_BITER_ELINKNO = sizeof(i2s_rx_buffer) / 2;
  666. DMA_TCD1_CSR = DMA_TCD_CSR_INTHALF | DMA_TCD_CSR_INTMAJOR;
  667. DMAMUX0_CHCFG1 = DMAMUX_DISABLE;
  668. DMAMUX0_CHCFG1 = DMAMUX_SOURCE_I2S0_RX | DMAMUX_ENABLE;
  669. update_responsibility = update_setup();
  670. DMA_SERQ = 1;
  671. // TODO: is I2S_RCSR_BCE appropriate if sync'd to transmitter clock?
  672. //I2S0_RCSR |= I2S_RCSR_RE | I2S_RCSR_BCE | I2S_RCSR_FRDE | I2S_RCSR_FR;
  673. I2S0_RCSR |= I2S_RCSR_RE | I2S_RCSR_FRDE | I2S_RCSR_FR;
  674. NVIC_ENABLE_IRQ(IRQ_DMA_CH1);
  675. }
  676. void dma_ch1_isr(void)
  677. {
  678. uint32_t daddr, offset;
  679. const int16_t *src, *end;
  680. int16_t *dest_left, *dest_right;
  681. audio_block_t *left, *right;
  682. //digitalWriteFast(3, HIGH);
  683. daddr = (uint32_t)DMA_TCD1_DADDR;
  684. DMA_CINT = 1;
  685. if (daddr < (uint32_t)i2s_rx_buffer + sizeof(i2s_rx_buffer) / 2) {
  686. // DMA is receiving to the first half of the buffer
  687. // need to remove data from the second half
  688. src = (int16_t *)&i2s_rx_buffer[AUDIO_BLOCK_SAMPLES/2];
  689. end = (int16_t *)&i2s_rx_buffer[AUDIO_BLOCK_SAMPLES];
  690. if (AudioInputI2S::update_responsibility) AudioStream::update_all();
  691. } else {
  692. // DMA is receiving to the second half of the buffer
  693. // need to remove data from the first half
  694. src = (int16_t *)&i2s_rx_buffer[0];
  695. end = (int16_t *)&i2s_rx_buffer[AUDIO_BLOCK_SAMPLES/2];
  696. }
  697. left = AudioInputI2S::block_left;
  698. right = AudioInputI2S::block_right;
  699. if (left != NULL && right != NULL) {
  700. offset = AudioInputI2S::block_offset;
  701. if (offset <= AUDIO_BLOCK_SAMPLES/2) {
  702. dest_left = &(left->data[offset]);
  703. dest_right = &(right->data[offset]);
  704. AudioInputI2S::block_offset = offset + AUDIO_BLOCK_SAMPLES/2;
  705. do {
  706. //n = *src++;
  707. //*dest_left++ = (int16_t)n;
  708. //*dest_right++ = (int16_t)(n >> 16);
  709. *dest_left++ = *src++;
  710. *dest_right++ = *src++;
  711. } while (src < end);
  712. }
  713. }
  714. //digitalWriteFast(3, LOW);
  715. }
  716. void AudioInputI2S::update(void)
  717. {
  718. audio_block_t *new_left=NULL, *new_right=NULL, *out_left=NULL, *out_right=NULL;
  719. // allocate 2 new blocks, but if one fails, allocate neither
  720. new_left = allocate();
  721. if (new_left != NULL) {
  722. new_right = allocate();
  723. if (new_right == NULL) {
  724. release(new_left);
  725. new_left = NULL;
  726. }
  727. }
  728. __disable_irq();
  729. if (block_offset >= AUDIO_BLOCK_SAMPLES) {
  730. // the DMA filled 2 blocks, so grab them and get the
  731. // 2 new blocks to the DMA, as quickly as possible
  732. out_left = block_left;
  733. block_left = new_left;
  734. out_right = block_right;
  735. block_right = new_right;
  736. block_offset = 0;
  737. __enable_irq();
  738. // then transmit the DMA's former blocks
  739. transmit(out_left, 0);
  740. release(out_left);
  741. transmit(out_right, 1);
  742. release(out_right);
  743. //Serial.print(".");
  744. } else if (new_left != NULL) {
  745. // the DMA didn't fill blocks, but we allocated blocks
  746. if (block_left == NULL) {
  747. // the DMA doesn't have any blocks to fill, so
  748. // give it the ones we just allocated
  749. block_left = new_left;
  750. block_right = new_right;
  751. block_offset = 0;
  752. __enable_irq();
  753. } else {
  754. // the DMA already has blocks, doesn't need these
  755. __enable_irq();
  756. release(new_left);
  757. release(new_right);
  758. }
  759. } else {
  760. // The DMA didn't fill blocks, and we could not allocate
  761. // memory... the system is likely starving for memory!
  762. // Sadly, there's nothing we can do.
  763. __enable_irq();
  764. }
  765. }
  766. /******************************************************************/
  767. void AudioInputI2Sslave::begin(void)
  768. {
  769. //block_left_1st = NULL;
  770. //block_right_1st = NULL;
  771. //pinMode(3, OUTPUT);
  772. //digitalWriteFast(3, HIGH);
  773. //delayMicroseconds(500);
  774. //digitalWriteFast(3, LOW);
  775. AudioOutputI2Sslave::config_i2s();
  776. CORE_PIN13_CONFIG = PORT_PCR_MUX(4); // pin 13, PTC5, I2S0_RXD0
  777. DMA_CR = 0;
  778. DMA_TCD1_SADDR = &I2S0_RDR0;
  779. DMA_TCD1_SOFF = 0;
  780. DMA_TCD1_ATTR = DMA_TCD_ATTR_SSIZE(1) | DMA_TCD_ATTR_DSIZE(1);
  781. DMA_TCD1_NBYTES_MLNO = 2;
  782. DMA_TCD1_SLAST = 0;
  783. DMA_TCD1_DADDR = i2s_rx_buffer;
  784. DMA_TCD1_DOFF = 2;
  785. DMA_TCD1_CITER_ELINKNO = sizeof(i2s_rx_buffer) / 2;
  786. DMA_TCD1_DLASTSGA = -sizeof(i2s_rx_buffer);
  787. DMA_TCD1_BITER_ELINKNO = sizeof(i2s_rx_buffer) / 2;
  788. DMA_TCD1_CSR = DMA_TCD_CSR_INTHALF | DMA_TCD_CSR_INTMAJOR;
  789. DMAMUX0_CHCFG1 = DMAMUX_DISABLE;
  790. DMAMUX0_CHCFG1 = DMAMUX_SOURCE_I2S0_RX | DMAMUX_ENABLE;
  791. update_responsibility = update_setup();
  792. DMA_SERQ = 1;
  793. // TODO: is I2S_RCSR_BCE appropriate if sync'd to transmitter clock?
  794. //I2S0_RCSR |= I2S_RCSR_RE | I2S_RCSR_BCE | I2S_RCSR_FRDE | I2S_RCSR_FR;
  795. I2S0_RCSR |= I2S_RCSR_RE | I2S_RCSR_FRDE | I2S_RCSR_FR;
  796. NVIC_ENABLE_IRQ(IRQ_DMA_CH1);
  797. }
  798. /******************************************************************/
  799. DMAMEM static uint16_t analog_rx_buffer[AUDIO_BLOCK_SAMPLES];
  800. audio_block_t * AudioInputAnalog::block_left = NULL;
  801. uint16_t AudioInputAnalog::block_offset = 0;
  802. bool AudioInputAnalog::update_responsibility = false;
  803. #define PDB_CONFIG (PDB_SC_TRGSEL(15) | PDB_SC_PDBEN | PDB_SC_CONT)
  804. #define PDB_PERIOD 1087 // 48e6 / 44100
  805. void AudioInputAnalog::begin(unsigned int pin)
  806. {
  807. uint32_t i, sum=0;
  808. // pin must be 0 to 13 (for A0 to A13)
  809. // or 14 to 23 for digital pin numbers A0-A9
  810. // or 34 to 37 corresponding to A10-A13
  811. if (pin > 23 && !(pin >= 34 && pin <= 37)) return;
  812. //pinMode(2, OUTPUT);
  813. //pinMode(3, OUTPUT);
  814. //digitalWriteFast(3, HIGH);
  815. //delayMicroseconds(500);
  816. //digitalWriteFast(3, LOW);
  817. // Configure the ADC and run at least one software-triggered
  818. // conversion. This completes the self calibration stuff and
  819. // leaves the ADC in a state that's mostly ready to use
  820. analogReadRes(16);
  821. analogReference(INTERNAL); // range 0 to 1.2 volts
  822. //analogReference(DEFAULT); // range 0 to 3.3 volts
  823. analogReadAveraging(8);
  824. // Actually, do many normal reads, to start with a nice DC level
  825. for (i=0; i < 1024; i++) {
  826. sum += analogRead(pin);
  827. }
  828. dc_average = sum >> 10;
  829. // testing only, enable adc interrupt
  830. //ADC0_SC1A |= ADC_SC1_AIEN;
  831. //while ((ADC0_SC1A & ADC_SC1_COCO) == 0) ; // wait
  832. //NVIC_ENABLE_IRQ(IRQ_ADC0);
  833. // set the programmable delay block to trigger the ADC at 44.1 kHz
  834. SIM_SCGC6 |= SIM_SCGC6_PDB;
  835. PDB0_MOD = PDB_PERIOD;
  836. PDB0_SC = PDB_CONFIG | PDB_SC_LDOK;
  837. PDB0_SC = PDB_CONFIG | PDB_SC_SWTRIG;
  838. PDB0_CH0C1 = 0x0101;
  839. // enable the ADC for hardware trigger and DMA
  840. ADC0_SC2 |= ADC_SC2_ADTRG | ADC_SC2_DMAEN;
  841. // set up a DMA channel to store the ADC data
  842. SIM_SCGC7 |= SIM_SCGC7_DMA;
  843. SIM_SCGC6 |= SIM_SCGC6_DMAMUX;
  844. DMA_CR = 0;
  845. DMA_TCD2_SADDR = &ADC0_RA;
  846. DMA_TCD2_SOFF = 0;
  847. DMA_TCD2_ATTR = DMA_TCD_ATTR_SSIZE(1) | DMA_TCD_ATTR_DSIZE(1);
  848. DMA_TCD2_NBYTES_MLNO = 2;
  849. DMA_TCD2_SLAST = 0;
  850. DMA_TCD2_DADDR = analog_rx_buffer;
  851. DMA_TCD2_DOFF = 2;
  852. DMA_TCD2_CITER_ELINKNO = sizeof(analog_rx_buffer) / 2;
  853. DMA_TCD2_DLASTSGA = -sizeof(analog_rx_buffer);
  854. DMA_TCD2_BITER_ELINKNO = sizeof(analog_rx_buffer) / 2;
  855. DMA_TCD2_CSR = DMA_TCD_CSR_INTHALF | DMA_TCD_CSR_INTMAJOR;
  856. DMAMUX0_CHCFG2 = DMAMUX_DISABLE;
  857. DMAMUX0_CHCFG2 = DMAMUX_SOURCE_ADC0 | DMAMUX_ENABLE;
  858. update_responsibility = update_setup();
  859. DMA_SERQ = 2;
  860. NVIC_ENABLE_IRQ(IRQ_DMA_CH2);
  861. }
  862. void dma_ch2_isr(void)
  863. {
  864. uint32_t daddr, offset;
  865. const uint16_t *src, *end;
  866. uint16_t *dest_left;
  867. audio_block_t *left;
  868. //digitalWriteFast(3, HIGH);
  869. daddr = (uint32_t)DMA_TCD2_DADDR;
  870. DMA_CINT = 2;
  871. if (daddr < (uint32_t)analog_rx_buffer + sizeof(analog_rx_buffer) / 2) {
  872. // DMA is receiving to the first half of the buffer
  873. // need to remove data from the second half
  874. src = (uint16_t *)&analog_rx_buffer[AUDIO_BLOCK_SAMPLES/2];
  875. end = (uint16_t *)&analog_rx_buffer[AUDIO_BLOCK_SAMPLES];
  876. if (AudioInputAnalog::update_responsibility) AudioStream::update_all();
  877. } else {
  878. // DMA is receiving to the second half of the buffer
  879. // need to remove data from the first half
  880. src = (uint16_t *)&analog_rx_buffer[0];
  881. end = (uint16_t *)&analog_rx_buffer[AUDIO_BLOCK_SAMPLES/2];
  882. }
  883. left = AudioInputAnalog::block_left;
  884. if (left != NULL) {
  885. offset = AudioInputAnalog::block_offset;
  886. if (offset > AUDIO_BLOCK_SAMPLES/2) offset = AUDIO_BLOCK_SAMPLES/2;
  887. //if (offset <= AUDIO_BLOCK_SAMPLES/2) {
  888. dest_left = (uint16_t *)&(left->data[offset]);
  889. AudioInputAnalog::block_offset = offset + AUDIO_BLOCK_SAMPLES/2;
  890. do {
  891. *dest_left++ = *src++;
  892. } while (src < end);
  893. //}
  894. }
  895. //digitalWriteFast(3, LOW);
  896. }
  897. #if 0
  898. void adc0_isr(void)
  899. {
  900. uint32_t tmp = ADC0_RA; // read ADC result to clear interrupt
  901. digitalWriteFast(3, HIGH);
  902. delayMicroseconds(1);
  903. digitalWriteFast(3, LOW);
  904. }
  905. #endif
  906. void AudioInputAnalog::update(void)
  907. {
  908. audio_block_t *new_left=NULL, *out_left=NULL;
  909. unsigned int dc, offset;
  910. int16_t s, *p, *end;
  911. // allocate new block (ok if NULL)
  912. new_left = allocate();
  913. __disable_irq();
  914. offset = block_offset;
  915. if (offset < AUDIO_BLOCK_SAMPLES) {
  916. // the DMA didn't fill a block
  917. if (new_left != NULL) {
  918. // but we allocated a block
  919. if (block_left == NULL) {
  920. // the DMA doesn't have any blocks to fill, so
  921. // give it the one we just allocated
  922. block_left = new_left;
  923. block_offset = 0;
  924. __enable_irq();
  925. //Serial.println("fail1");
  926. } else {
  927. // the DMA already has blocks, doesn't need this
  928. __enable_irq();
  929. release(new_left);
  930. //Serial.print("fail2, offset=");
  931. //Serial.println(offset);
  932. }
  933. } else {
  934. // The DMA didn't fill a block, and we could not allocate
  935. // memory... the system is likely starving for memory!
  936. // Sadly, there's nothing we can do.
  937. __enable_irq();
  938. //Serial.println("fail3");
  939. }
  940. return;
  941. }
  942. // the DMA filled a block, so grab it and get the
  943. // new block to the DMA, as quickly as possible
  944. out_left = block_left;
  945. block_left = new_left;
  946. block_offset = 0;
  947. __enable_irq();
  948. // find and subtract DC offset....
  949. // TODO: this may not be correct, needs testing with more types of signals
  950. dc = dc_average;
  951. p = out_left->data;
  952. end = p + AUDIO_BLOCK_SAMPLES;
  953. do {
  954. s = (uint16_t)(*p) - dc; // TODO: should be saturating subtract
  955. *p++ = s;
  956. dc += s >> 13; // approx 5.38 Hz high pass filter
  957. } while (p < end);
  958. dc_average = dc;
  959. // then transmit the AC data
  960. transmit(out_left);
  961. release(out_left);
  962. }
  963. /******************************************************************/
  964. // #define PDB_CONFIG (PDB_SC_TRGSEL(15) | PDB_SC_PDBEN | PDB_SC_CONT)
  965. // #define PDB_PERIOD 1087 // 48e6 / 44100
  966. #if defined(__MK20DX256__) && defined(DMA_TCD4_SADDR)
  967. DMAMEM static uint16_t dac_buffer[AUDIO_BLOCK_SAMPLES*2];
  968. audio_block_t * AudioOutputAnalog::block_left_1st = NULL;
  969. audio_block_t * AudioOutputAnalog::block_left_2nd = NULL;
  970. bool AudioOutputAnalog::update_responsibility = false;
  971. void AudioOutputAnalog::begin(void)
  972. {
  973. SIM_SCGC2 |= SIM_SCGC2_DAC0;
  974. DAC0_C0 = DAC_C0_DACEN | DAC_C0_DACRFS; // 3.3V VDDA is DACREF_2
  975. // slowly ramp up to DC voltage, approx 1/4 second
  976. for (int16_t i=0; i<128; i++) {
  977. analogWrite(A14, i);
  978. delay(2);
  979. }
  980. // set the programmable delay block to trigger DMA requests
  981. SIM_SCGC6 |= SIM_SCGC6_PDB;
  982. PDB0_IDLY = 1;
  983. PDB0_MOD = PDB_PERIOD;
  984. PDB0_SC = PDB_CONFIG | PDB_SC_LDOK;
  985. PDB0_SC = PDB_CONFIG | PDB_SC_SWTRIG | PDB_SC_PDBIE | PDB_SC_DMAEN;
  986. SIM_SCGC7 |= SIM_SCGC7_DMA;
  987. SIM_SCGC6 |= SIM_SCGC6_DMAMUX;
  988. DMA_CR = 0;
  989. DMA_TCD4_SADDR = dac_buffer;
  990. DMA_TCD4_SOFF = 2;
  991. DMA_TCD4_ATTR = DMA_TCD_ATTR_SSIZE(1) | DMA_TCD_ATTR_DSIZE(1);
  992. DMA_TCD4_NBYTES_MLNO = 2;
  993. DMA_TCD4_SLAST = -sizeof(dac_buffer);
  994. DMA_TCD4_DADDR = &DAC0_DAT0L;
  995. DMA_TCD4_DOFF = 0;
  996. DMA_TCD4_CITER_ELINKNO = sizeof(dac_buffer) / 2;
  997. DMA_TCD4_DLASTSGA = 0;
  998. DMA_TCD4_BITER_ELINKNO = sizeof(dac_buffer) / 2;
  999. DMA_TCD4_CSR = DMA_TCD_CSR_INTHALF | DMA_TCD_CSR_INTMAJOR;
  1000. DMAMUX0_CHCFG4 = DMAMUX_DISABLE;
  1001. DMAMUX0_CHCFG4 = DMAMUX_SOURCE_PDB | DMAMUX_ENABLE;
  1002. update_responsibility = update_setup();
  1003. DMA_SERQ = 4;
  1004. NVIC_ENABLE_IRQ(IRQ_DMA_CH4);
  1005. }
  1006. void AudioOutputAnalog::analogReference(int ref)
  1007. {
  1008. // TODO: this should ramp gradually to the new DC level
  1009. if (ref == INTERNAL) {
  1010. DAC0_C0 &= ~DAC_C0_DACRFS; // 1.2V
  1011. } else {
  1012. DAC0_C0 |= DAC_C0_DACRFS; // 3.3V
  1013. }
  1014. }
  1015. void AudioOutputAnalog::update(void)
  1016. {
  1017. audio_block_t *block;
  1018. block = receiveReadOnly(0); // input 0
  1019. if (block) {
  1020. __disable_irq();
  1021. if (block_left_1st == NULL) {
  1022. block_left_1st = block;
  1023. __enable_irq();
  1024. } else if (block_left_2nd == NULL) {
  1025. block_left_2nd = block;
  1026. __enable_irq();
  1027. } else {
  1028. audio_block_t *tmp = block_left_1st;
  1029. block_left_1st = block_left_2nd;
  1030. block_left_2nd = block;
  1031. __enable_irq();
  1032. release(tmp);
  1033. }
  1034. }
  1035. }
  1036. // TODO: the DAC has much higher bandwidth than the datasheet says
  1037. // can we output a 2X oversampled output, for easier filtering?
  1038. void dma_ch4_isr(void)
  1039. {
  1040. const int16_t *src, *end;
  1041. int16_t *dest;
  1042. audio_block_t *block;
  1043. uint32_t saddr, offset;
  1044. saddr = (uint32_t)DMA_TCD4_SADDR;
  1045. DMA_CINT = 4;
  1046. if (saddr < (uint32_t)dac_buffer + sizeof(dac_buffer) / 2) {
  1047. // DMA is transmitting the first half of the buffer
  1048. // so we must fill the second half
  1049. dest = (int16_t *)&dac_buffer[AUDIO_BLOCK_SAMPLES];
  1050. end = (int16_t *)&dac_buffer[AUDIO_BLOCK_SAMPLES*2];
  1051. } else {
  1052. // DMA is transmitting the second half of the buffer
  1053. // so we must fill the first half
  1054. dest = (int16_t *)dac_buffer;
  1055. end = (int16_t *)&dac_buffer[AUDIO_BLOCK_SAMPLES];
  1056. }
  1057. block = AudioOutputAnalog::block_left_1st;
  1058. if (block) {
  1059. src = &block->data[offset];
  1060. do {
  1061. // TODO: this should probably dither
  1062. *dest++ = ((*src++) + 32767) >> 4;
  1063. } while (dest < end);
  1064. AudioStream::release(block);
  1065. AudioOutputAnalog::block_left_1st = AudioOutputAnalog::block_left_2nd;
  1066. AudioOutputAnalog::block_left_2nd = NULL;
  1067. } else {
  1068. do {
  1069. *dest++ = 2047;
  1070. } while (dest < end);
  1071. }
  1072. if (AudioOutputAnalog::update_responsibility) AudioStream::update_all();
  1073. }
  1074. #else
  1075. void AudioOutputAnalog::begin(void)
  1076. {
  1077. }
  1078. void AudioOutputAnalog::update(void)
  1079. {
  1080. audio_block_t *block;
  1081. block = receiveReadOnly(0); // input 0
  1082. if (block) release(block);
  1083. }
  1084. #endif // defined(__MK20DX256__) && defined(DMA_TCD4_SADDR)
  1085. /******************************************************************/
  1086. #define STATE_DIRECT_8BIT_MONO 0 // playing mono at native sample rate
  1087. #define STATE_DIRECT_8BIT_STEREO 1 // playing stereo at native sample rate
  1088. #define STATE_DIRECT_16BIT_MONO 2 // playing mono at native sample rate
  1089. #define STATE_DIRECT_16BIT_STEREO 3 // playing stereo at native sample rate
  1090. #define STATE_CONVERT_8BIT_MONO 4 // playing mono, converting sample rate
  1091. #define STATE_CONVERT_8BIT_STEREO 5 // playing stereo, converting sample rate
  1092. #define STATE_CONVERT_16BIT_MONO 6 // playing mono, converting sample rate
  1093. #define STATE_CONVERT_16BIT_STEREO 7 // playing stereo, converting sample rate
  1094. #define STATE_PARSE1 8 // looking for 20 byte ID header
  1095. #define STATE_PARSE2 9 // looking for 16 byte format header
  1096. #define STATE_PARSE3 10 // looking for 8 byte data header
  1097. #define STATE_PARSE4 11 // ignoring unknown chunk
  1098. #define STATE_STOP 12
  1099. void AudioPlaySDcardWAV::begin(void)
  1100. {
  1101. state = STATE_STOP;
  1102. state_play = STATE_STOP;
  1103. data_length = 0;
  1104. if (block_left) {
  1105. release(block_left);
  1106. block_left = NULL;
  1107. }
  1108. if (block_right) {
  1109. release(block_right);
  1110. block_right = NULL;
  1111. }
  1112. }
  1113. bool AudioPlaySDcardWAV::play(const char *filename)
  1114. {
  1115. stop();
  1116. wavfile = SD.open(filename);
  1117. if (!wavfile) return false;
  1118. buffer_remaining = 0;
  1119. state_play = STATE_STOP;
  1120. data_length = 0;
  1121. state = STATE_PARSE1;
  1122. return true;
  1123. }
  1124. void AudioPlaySDcardWAV::stop(void)
  1125. {
  1126. __disable_irq();
  1127. if (state != STATE_STOP) {
  1128. state = STATE_STOP;
  1129. __enable_irq();
  1130. wavfile.close();
  1131. } else {
  1132. __enable_irq();
  1133. }
  1134. }
  1135. bool AudioPlaySDcardWAV::start(void)
  1136. {
  1137. __disable_irq();
  1138. if (state == STATE_STOP) {
  1139. if (state_play == STATE_STOP) {
  1140. __enable_irq();
  1141. return false;
  1142. }
  1143. state = state_play;
  1144. }
  1145. __enable_irq();
  1146. return true;
  1147. }
  1148. void AudioPlaySDcardWAV::update(void)
  1149. {
  1150. // only update if we're playing
  1151. if (state == STATE_STOP) return;
  1152. // allocate the audio blocks to transmit
  1153. block_left = allocate();
  1154. if (block_left == NULL) return;
  1155. if (state < 8 && (state & 1) == 1) {
  1156. // if we're playing stereo, allocate another
  1157. // block for the right channel output
  1158. block_right = allocate();
  1159. if (block_right == NULL) {
  1160. release(block_left);
  1161. return;
  1162. }
  1163. } else {
  1164. // if we're playing mono or just parsing
  1165. // the WAV file header, no right-side block
  1166. block_right = NULL;
  1167. }
  1168. block_offset = 0;
  1169. //Serial.println("update");
  1170. // is there buffered data?
  1171. if (buffer_remaining > 0) {
  1172. // we have buffered data
  1173. if (consume()) return; // it was enough to transmit audio
  1174. }
  1175. // we only get to this point when buffer[512] is empty
  1176. if (state != STATE_STOP && wavfile.available()) {
  1177. // we can read more data from the file...
  1178. buffer_remaining = wavfile.read(buffer, 512);
  1179. if (consume()) {
  1180. // good, it resulted in audio transmit
  1181. return;
  1182. } else {
  1183. // not good, no audio was transmitted
  1184. buffer_remaining = 0;
  1185. if (block_left) release(block_left);
  1186. if (block_right) release(block_right);
  1187. // if we're still playing, well, there's going to
  1188. // be a gap in output, but we can't keep burning
  1189. // time trying to read more data. Hopefully things
  1190. // will go better next time?
  1191. if (state != STATE_STOP) return;
  1192. }
  1193. }
  1194. // end of file reached or other reason to stop
  1195. wavfile.close();
  1196. state_play = STATE_STOP;
  1197. state = STATE_STOP;
  1198. }
  1199. // https://ccrma.stanford.edu/courses/422/projects/WaveFormat/
  1200. // Consume already buffered data. Returns true if audio transmitted.
  1201. bool AudioPlaySDcardWAV::consume(void)
  1202. {
  1203. uint32_t len, size;
  1204. uint8_t lsb, msb;
  1205. const uint8_t *p;
  1206. size = buffer_remaining;
  1207. p = buffer + 512 - size;
  1208. start:
  1209. if (size == 0) return false;
  1210. //Serial.print("AudioPlaySDcardWAV write, size = ");
  1211. //Serial.print(size);
  1212. //Serial.print(", data_length = ");
  1213. //Serial.print(data_length);
  1214. //Serial.print(", state = ");
  1215. //Serial.println(state);
  1216. switch (state) {
  1217. // parse wav file header, is this really a .wav file?
  1218. case STATE_PARSE1:
  1219. len = 20 - data_length;
  1220. if (size < len) len = size;
  1221. memcpy((uint8_t *)header + data_length, p, len);
  1222. data_length += len;
  1223. if (data_length < 20) return false;
  1224. // parse the header...
  1225. if (header[0] == 0x46464952 && header[2] == 0x45564157
  1226. && header[3] == 0x20746D66 && header[4] == 16) {
  1227. //Serial.println("header ok");
  1228. state = STATE_PARSE2;
  1229. p += len;
  1230. size -= len;
  1231. data_length = 0;
  1232. goto start;
  1233. }
  1234. //Serial.println("unknown WAV header");
  1235. break;
  1236. // check & extract key audio parameters
  1237. case STATE_PARSE2:
  1238. len = 16 - data_length;
  1239. if (size < len) len = size;
  1240. memcpy((uint8_t *)header + data_length, p, len);
  1241. data_length += len;
  1242. if (data_length < 16) return false;
  1243. if (parse_format()) {
  1244. //Serial.println("audio format ok");
  1245. p += len;
  1246. size -= len;
  1247. data_length = 0;
  1248. state = STATE_PARSE3;
  1249. goto start;
  1250. }
  1251. //Serial.println("unknown audio format");
  1252. break;
  1253. // find the data chunk
  1254. case STATE_PARSE3:
  1255. len = 8 - data_length;
  1256. if (size < len) len = size;
  1257. memcpy((uint8_t *)header + data_length, p, len);
  1258. data_length += len;
  1259. if (data_length < 8) return false;
  1260. //Serial.print("chunk id = ");
  1261. //Serial.print(header[0], HEX);
  1262. //Serial.print(", length = ");
  1263. //Serial.println(header[1]);
  1264. p += len;
  1265. size -= len;
  1266. data_length = header[1];
  1267. if (header[0] == 0x61746164) {
  1268. //Serial.println("found data chunk");
  1269. // TODO: verify offset in file is an even number
  1270. // as required by WAV format. abort if odd. Code
  1271. // below will depend upon this and fail if not even.
  1272. leftover_bytes = 0;
  1273. state = state_play;
  1274. if (state & 1) {
  1275. // if we're going to start stereo
  1276. // better allocate another output block
  1277. block_right = allocate();
  1278. if (!block_right) return false;
  1279. }
  1280. } else {
  1281. state = STATE_PARSE4;
  1282. }
  1283. goto start;
  1284. // ignore any extra unknown chunks (title & artist info)
  1285. case STATE_PARSE4:
  1286. if (size < data_length) {
  1287. data_length -= size;
  1288. return false;
  1289. }
  1290. p += data_length;
  1291. size -= data_length;
  1292. data_length = 0;
  1293. state = STATE_PARSE3;
  1294. goto start;
  1295. // playing mono at native sample rate
  1296. case STATE_DIRECT_8BIT_MONO:
  1297. return false;
  1298. // playing stereo at native sample rate
  1299. case STATE_DIRECT_8BIT_STEREO:
  1300. return false;
  1301. // playing mono at native sample rate
  1302. case STATE_DIRECT_16BIT_MONO:
  1303. if (size > data_length) size = data_length;
  1304. data_length -= size;
  1305. while (1) {
  1306. lsb = *p++;
  1307. msb = *p++;
  1308. size -= 2;
  1309. block_left->data[block_offset++] = (msb << 8) | lsb;
  1310. if (block_offset >= AUDIO_BLOCK_SAMPLES) {
  1311. transmit(block_left, 0);
  1312. transmit(block_left, 1);
  1313. //Serial1.print('%');
  1314. //delayMicroseconds(90);
  1315. release(block_left);
  1316. block_left = NULL;
  1317. data_length += size;
  1318. buffer_remaining = size;
  1319. if (block_right) release(block_right);
  1320. return true;
  1321. }
  1322. if (size == 0) {
  1323. if (data_length == 0) break;
  1324. return false;
  1325. }
  1326. }
  1327. // end of file reached
  1328. if (block_offset > 0) {
  1329. // TODO: fill remainder of last block with zero and transmit
  1330. }
  1331. state = STATE_STOP;
  1332. return false;
  1333. // playing stereo at native sample rate
  1334. case STATE_DIRECT_16BIT_STEREO:
  1335. if (size > data_length) size = data_length;
  1336. data_length -= size;
  1337. if (leftover_bytes) {
  1338. block_left->data[block_offset] = header[0];
  1339. goto right16;
  1340. }
  1341. while (1) {
  1342. lsb = *p++;
  1343. msb = *p++;
  1344. size -= 2;
  1345. if (size == 0) {
  1346. if (data_length == 0) break;
  1347. header[0] = (msb << 8) | lsb;
  1348. leftover_bytes = 2;
  1349. return false;
  1350. }
  1351. block_left->data[block_offset] = (msb << 8) | lsb;
  1352. right16:
  1353. lsb = *p++;
  1354. msb = *p++;
  1355. size -= 2;
  1356. block_right->data[block_offset++] = (msb << 8) | lsb;
  1357. if (block_offset >= AUDIO_BLOCK_SAMPLES) {
  1358. transmit(block_left, 0);
  1359. release(block_left);
  1360. block_left = NULL;
  1361. transmit(block_right, 1);
  1362. release(block_right);
  1363. block_right = NULL;
  1364. data_length += size;
  1365. buffer_remaining = size;
  1366. return true;
  1367. }
  1368. if (size == 0) {
  1369. if (data_length == 0) break;
  1370. leftover_bytes = 0;
  1371. return false;
  1372. }
  1373. }
  1374. // end of file reached
  1375. if (block_offset > 0) {
  1376. // TODO: fill remainder of last block with zero and transmit
  1377. }
  1378. state = STATE_STOP;
  1379. return false;
  1380. // playing mono, converting sample rate
  1381. case STATE_CONVERT_8BIT_MONO :
  1382. return false;
  1383. // playing stereo, converting sample rate
  1384. case STATE_CONVERT_8BIT_STEREO:
  1385. return false;
  1386. // playing mono, converting sample rate
  1387. case STATE_CONVERT_16BIT_MONO:
  1388. return false;
  1389. // playing stereo, converting sample rate
  1390. case STATE_CONVERT_16BIT_STEREO:
  1391. return false;
  1392. // ignore any extra data after playing
  1393. // or anything following any error
  1394. case STATE_STOP:
  1395. return false;
  1396. // this is not supposed to happen!
  1397. //default:
  1398. //Serial.println("AudioPlaySDcardWAV, unknown state");
  1399. }
  1400. state_play = STATE_STOP;
  1401. state = STATE_STOP;
  1402. return false;
  1403. }
  1404. /*
  1405. 00000000 52494646 66EA6903 57415645 666D7420 RIFFf.i.WAVEfmt
  1406. 00000010 10000000 01000200 44AC0000 10B10200 ........D.......
  1407. 00000020 04001000 4C495354 3A000000 494E464F ....LIST:...INFO
  1408. 00000030 494E414D 14000000 49205761 6E742054 INAM....I Want T
  1409. 00000040 6F20436F 6D65204F 76657200 49415254 o Come Over.IART
  1410. 00000050 12000000 4D656C69 73736120 45746865 ....Melissa Ethe
  1411. 00000060 72696467 65006461 746100EA 69030100 ridge.data..i...
  1412. 00000070 FEFF0300 FCFF0400 FDFF0200 0000FEFF ................
  1413. 00000080 0300FDFF 0200FFFF 00000100 FEFF0300 ................
  1414. 00000090 FDFF0300 FDFF0200 FFFF0100 0000FFFF ................
  1415. */
  1416. // SD library on Teensy3 at 96 MHz
  1417. // 256 byte chunks, speed is 443272 bytes/sec
  1418. // 512 byte chunks, speed is 468023 bytes/sec
  1419. bool AudioPlaySDcardWAV::parse_format(void)
  1420. {
  1421. uint8_t num = 0;
  1422. uint16_t format;
  1423. uint16_t channels;
  1424. uint32_t rate;
  1425. uint16_t bits;
  1426. format = header[0];
  1427. //Serial.print(" format = ");
  1428. //Serial.println(format);
  1429. if (format != 1) return false;
  1430. channels = header[0] >> 16;
  1431. //Serial.print(" channels = ");
  1432. //Serial.println(channels);
  1433. if (channels == 1) {
  1434. } else if (channels == 2) {
  1435. num = 1;
  1436. } else {
  1437. return false;
  1438. }
  1439. bits = header[3] >> 16;
  1440. //Serial.print(" bits = ");
  1441. //Serial.println(bits);
  1442. if (bits == 8) {
  1443. } else if (bits == 16) {
  1444. num |= 2;
  1445. } else {
  1446. return false;
  1447. }
  1448. rate = header[1];
  1449. //Serial.print(" rate = ");
  1450. //Serial.println(rate);
  1451. if (rate == AUDIO_SAMPLE_RATE) {
  1452. } else if (rate >= 8000 && rate <= 48000) {
  1453. num |= 4;
  1454. } else {
  1455. return false;
  1456. }
  1457. // we're not checking the byte rate and block align fields
  1458. // if they're not the expected values, all we could do is
  1459. // return false. Do any real wav files have unexpected
  1460. // values in these other fields?
  1461. state_play = num;
  1462. return true;
  1463. }
  1464. /******************************************************************/
  1465. void AudioPlaySDcardRAW::begin(void)
  1466. {
  1467. playing = false;
  1468. if (block) {
  1469. release(block);
  1470. block = NULL;
  1471. }
  1472. }
  1473. bool AudioPlaySDcardRAW::play(const char *filename)
  1474. {
  1475. stop();
  1476. rawfile = SD.open(filename);
  1477. if (!rawfile) {
  1478. Serial.println("unable to open file");
  1479. return false;
  1480. }
  1481. Serial.println("able to open file");
  1482. playing = true;
  1483. return true;
  1484. }
  1485. void AudioPlaySDcardRAW::stop(void)
  1486. {
  1487. __disable_irq();
  1488. if (playing) {
  1489. playing = false;
  1490. __enable_irq();
  1491. rawfile.close();
  1492. } else {
  1493. __enable_irq();
  1494. }
  1495. }
  1496. void AudioPlaySDcardRAW::update(void)
  1497. {
  1498. unsigned int i, n;
  1499. // only update if we're playing
  1500. if (!playing) return;
  1501. // allocate the audio blocks to transmit
  1502. block = allocate();
  1503. if (block == NULL) return;
  1504. if (rawfile.available()) {
  1505. // we can read more data from the file...
  1506. n = rawfile.read(block->data, AUDIO_BLOCK_SAMPLES*2);
  1507. for (i=n/2; i < AUDIO_BLOCK_SAMPLES; i++) {
  1508. block->data[i] = 0;
  1509. }
  1510. transmit(block);
  1511. release(block);
  1512. } else {
  1513. rawfile.close();
  1514. playing = false;
  1515. }
  1516. }
  1517. /******************************************************************/
  1518. void AudioPlayMemory::play(const unsigned int *data)
  1519. {
  1520. uint32_t format;
  1521. playing = 0;
  1522. prior = 0;
  1523. format = *data++;
  1524. next = data;
  1525. length = format & 0xFFFFFF;
  1526. playing = format >> 24;
  1527. }
  1528. void AudioPlayMemory::stop(void)
  1529. {
  1530. playing = 0;
  1531. }
  1532. extern "C" {
  1533. extern const int16_t ulaw_decode_table[256];
  1534. };
  1535. void AudioPlayMemory::update(void)
  1536. {
  1537. audio_block_t *block;
  1538. const unsigned int *in;
  1539. int16_t *out;
  1540. uint32_t tmp32, consumed;
  1541. int16_t s0, s1, s2, s3, s4;
  1542. int i;
  1543. if (!playing) return;
  1544. block = allocate();
  1545. if (block == NULL) return;
  1546. //Serial.write('.');
  1547. out = block->data;
  1548. in = next;
  1549. s0 = prior;
  1550. switch (playing) {
  1551. case 0x01: // u-law encoded, 44100 Hz
  1552. for (i=0; i < AUDIO_BLOCK_SAMPLES; i += 4) {
  1553. tmp32 = *in++;
  1554. *out++ = ulaw_decode_table[(tmp32 >> 0) & 255];
  1555. *out++ = ulaw_decode_table[(tmp32 >> 8) & 255];
  1556. *out++ = ulaw_decode_table[(tmp32 >> 16) & 255];
  1557. *out++ = ulaw_decode_table[(tmp32 >> 24) & 255];
  1558. }
  1559. consumed = 128;
  1560. break;
  1561. case 0x81: // 16 bit PCM, 44100 Hz
  1562. for (i=0; i < AUDIO_BLOCK_SAMPLES; i += 2) {
  1563. tmp32 = *in++;
  1564. *out++ = (int16_t)(tmp32 & 65535);
  1565. *out++ = (int16_t)(tmp32 >> 16);
  1566. }
  1567. consumed = 128;
  1568. break;
  1569. case 0x02: // u-law encoded, 22050 Hz
  1570. for (i=0; i < AUDIO_BLOCK_SAMPLES; i += 8) {
  1571. tmp32 = *in++;
  1572. s1 = ulaw_decode_table[(tmp32 >> 0) & 255];
  1573. s2 = ulaw_decode_table[(tmp32 >> 8) & 255];
  1574. s3 = ulaw_decode_table[(tmp32 >> 16) & 255];
  1575. s4 = ulaw_decode_table[(tmp32 >> 24) & 255];
  1576. *out++ = (s0 + s1) >> 1;
  1577. *out++ = s1;
  1578. *out++ = (s1 + s2) >> 1;
  1579. *out++ = s2;
  1580. *out++ = (s2 + s3) >> 1;
  1581. *out++ = s3;
  1582. *out++ = (s3 + s4) >> 1;
  1583. *out++ = s4;
  1584. s0 = s4;
  1585. }
  1586. consumed = 64;
  1587. break;
  1588. case 0x82: // 16 bits PCM, 22050 Hz
  1589. for (i=0; i < AUDIO_BLOCK_SAMPLES; i += 4) {
  1590. tmp32 = *in++;
  1591. s1 = (int16_t)(tmp32 & 65535);
  1592. s2 = (int16_t)(tmp32 >> 16);
  1593. *out++ = (s0 + s1) >> 1;
  1594. *out++ = s1;
  1595. *out++ = (s1 + s2) >> 1;
  1596. *out++ = s2;
  1597. s0 = s2;
  1598. }
  1599. consumed = 64;
  1600. break;
  1601. case 0x03: // u-law encoded, 11025 Hz
  1602. for (i=0; i < AUDIO_BLOCK_SAMPLES; i += 16) {
  1603. tmp32 = *in++;
  1604. s1 = ulaw_decode_table[(tmp32 >> 0) & 255];
  1605. s2 = ulaw_decode_table[(tmp32 >> 8) & 255];
  1606. s3 = ulaw_decode_table[(tmp32 >> 16) & 255];
  1607. s4 = ulaw_decode_table[(tmp32 >> 24) & 255];
  1608. *out++ = (s0 * 3 + s1) >> 2;
  1609. *out++ = (s0 + s1) >> 1;
  1610. *out++ = (s0 + s1 * 3) >> 2;
  1611. *out++ = s1;
  1612. *out++ = (s1 * 3 + s2) >> 2;
  1613. *out++ = (s1 + s2) >> 1;
  1614. *out++ = (s1 + s2 * 3) >> 2;
  1615. *out++ = s2;
  1616. *out++ = (s2 * 3 + s3) >> 2;
  1617. *out++ = (s2 + s3) >> 1;
  1618. *out++ = (s2 + s3 * 3) >> 2;
  1619. *out++ = s3;
  1620. *out++ = (s3 * 3 + s4) >> 2;
  1621. *out++ = (s3 + s4) >> 1;
  1622. *out++ = (s3 + s4 * 3) >> 2;
  1623. *out++ = s4;
  1624. s0 = s4;
  1625. }
  1626. consumed = 32;
  1627. break;
  1628. case 0x83: // 16 bit PCM, 11025 Hz
  1629. for (i=0; i < AUDIO_BLOCK_SAMPLES; i += 8) {
  1630. tmp32 = *in++;
  1631. s1 = (int16_t)(tmp32 & 65535);
  1632. s2 = (int16_t)(tmp32 >> 16);
  1633. *out++ = (s0 * 3 + s1) >> 2;
  1634. *out++ = (s0 + s1) >> 1;
  1635. *out++ = (s0 + s1 * 3) >> 2;
  1636. *out++ = s1;
  1637. *out++ = (s1 * 3 + s2) >> 2;
  1638. *out++ = (s1 + s2) >> 1;
  1639. *out++ = (s1 + s2 * 3) >> 2;
  1640. *out++ = s2;
  1641. s0 = s2;
  1642. }
  1643. consumed = 32;
  1644. break;
  1645. default:
  1646. release(block);
  1647. playing = 0;
  1648. return;
  1649. }
  1650. prior = s0;
  1651. next = in;
  1652. if (length > consumed) {
  1653. length -= consumed;
  1654. } else {
  1655. playing = 0;
  1656. }
  1657. transmit(block);
  1658. release(block);
  1659. }
  1660. /******************************************************************/
  1661. // computes ((a[31:0] * b[15:0]) >> 16)
  1662. static inline int32_t signed_multiply_32x16b(int32_t a, uint32_t b) __attribute__((always_inline));
  1663. static inline int32_t signed_multiply_32x16b(int32_t a, uint32_t b)
  1664. {
  1665. int32_t out;
  1666. asm volatile("smulwb %0, %1, %2" : "=r" (out) : "r" (a), "r" (b));
  1667. return out;
  1668. }
  1669. // computes ((a[31:0] * b[31:16]) >> 16)
  1670. static inline int32_t signed_multiply_32x16t(int32_t a, uint32_t b) __attribute__((always_inline));
  1671. static inline int32_t signed_multiply_32x16t(int32_t a, uint32_t b)
  1672. {
  1673. int32_t out;
  1674. asm volatile("smulwt %0, %1, %2" : "=r" (out) : "r" (a), "r" (b));
  1675. return out;
  1676. }
  1677. // computes (((int64_t)a[31:0] * (int64_t)b[31:0]) >> 32)
  1678. static inline int32_t multiply_32x32_rshift32(int32_t a, int32_t b) __attribute__((always_inline));
  1679. static inline int32_t multiply_32x32_rshift32(int32_t a, int32_t b)
  1680. {
  1681. int32_t out;
  1682. asm volatile("smmul %0, %1, %2" : "=r" (out) : "r" (a), "r" (b));
  1683. return out;
  1684. }
  1685. // computes (((int64_t)a[31:0] * (int64_t)b[31:0] + 0x8000000) >> 32)
  1686. static inline int32_t multiply_32x32_rshift32_rounded(int32_t a, int32_t b) __attribute__((always_inline));
  1687. static inline int32_t multiply_32x32_rshift32_rounded(int32_t a, int32_t b)
  1688. {
  1689. int32_t out;
  1690. asm volatile("smmulr %0, %1, %2" : "=r" (out) : "r" (a), "r" (b));
  1691. return out;
  1692. }
  1693. // computes sum + (((int64_t)a[31:0] * (int64_t)b[31:0] + 0x8000000) >> 32)
  1694. static inline int32_t multiply_accumulate_32x32_rshift32_rounded(int32_t sum, int32_t a, int32_t b) __attribute__((always_inline));
  1695. static inline int32_t multiply_accumulate_32x32_rshift32_rounded(int32_t sum, int32_t a, int32_t b)
  1696. {
  1697. int32_t out;
  1698. asm volatile("smmlar %0, %2, %3, %1" : "=r" (out) : "r" (sum), "r" (a), "r" (b));
  1699. return out;
  1700. }
  1701. // computes sum - (((int64_t)a[31:0] * (int64_t)b[31:0] + 0x8000000) >> 32)
  1702. static inline int32_t multiply_subtract_32x32_rshift32_rounded(int32_t sum, int32_t a, int32_t b) __attribute__((always_inline));
  1703. static inline int32_t multiply_subtract_32x32_rshift32_rounded(int32_t sum, int32_t a, int32_t b)
  1704. {
  1705. int32_t out;
  1706. asm volatile("smmlsr %0, %2, %3, %1" : "=r" (out) : "r" (sum), "r" (a), "r" (b));
  1707. return out;
  1708. }
  1709. // computes ((a[15:0] << 16) | b[15:0])
  1710. static inline uint32_t pack_16x16(int32_t a, int32_t b) __attribute__((always_inline));
  1711. static inline uint32_t pack_16x16(int32_t a, int32_t b)
  1712. {
  1713. int32_t out;
  1714. asm volatile("pkhbt %0, %1, %2, lsl #16" : "=r" (out) : "r" (b), "r" (a));
  1715. return out;
  1716. }
  1717. // computes (((a[31:16] + b[31:16]) << 16) | (a[15:0 + b[15:0]))
  1718. static inline uint32_t signed_add_16_and_16(uint32_t a, uint32_t b) __attribute__((always_inline));
  1719. static inline uint32_t signed_add_16_and_16(uint32_t a, uint32_t b)
  1720. {
  1721. int32_t out;
  1722. asm volatile("qadd16 %0, %1, %2" : "=r" (out) : "r" (a), "r" (b));
  1723. return out;
  1724. }
  1725. // computes (sum + ((a[31:0] * b[15:0]) >> 16))
  1726. static inline int32_t signed_multiply_accumulate_32x16b(int32_t sum, int32_t a, uint32_t b)
  1727. {
  1728. int32_t out;
  1729. asm volatile("smlawb %0, %2, %3, %1" : "=r" (out) : "r" (sum), "r" (a), "r" (b));
  1730. return out;
  1731. }
  1732. // computes (sum + ((a[31:0] * b[31:16]) >> 16))
  1733. static inline int32_t signed_multiply_accumulate_32x16t(int32_t sum, int32_t a, uint32_t b)
  1734. {
  1735. int32_t out;
  1736. asm volatile("smlawt %0, %2, %3, %1" : "=r" (out) : "r" (sum), "r" (a), "r" (b));
  1737. return out;
  1738. }
  1739. // computes logical and, forces compiler to allocate register and use single cycle instruction
  1740. static inline uint32_t logical_and(uint32_t a, uint32_t b)
  1741. {
  1742. asm volatile("and %0, %1" : "+r" (a) : "r" (b));
  1743. return a;
  1744. }
  1745. void applyGain(int16_t *data, int32_t mult)
  1746. {
  1747. uint32_t *p = (uint32_t *)data;
  1748. const uint32_t *end = (uint32_t *)(data + AUDIO_BLOCK_SAMPLES);
  1749. do {
  1750. uint32_t tmp32 = *p; // read 2 samples from *data
  1751. int32_t val1 = signed_multiply_32x16b(mult, tmp32);
  1752. int32_t val2 = signed_multiply_32x16t(mult, tmp32);
  1753. val1 = signed_saturate_rshift(val1, 16, 0);
  1754. val2 = signed_saturate_rshift(val2, 16, 0);
  1755. *p++ = pack_16x16(val2, val1);
  1756. } while (p < end);
  1757. }
  1758. // page 133
  1759. void applyGainThenAdd(int16_t *data, const int16_t *in, int32_t mult)
  1760. {
  1761. uint32_t *dst = (uint32_t *)data;
  1762. const uint32_t *src = (uint32_t *)in;
  1763. const uint32_t *end = (uint32_t *)(data + AUDIO_BLOCK_SAMPLES);
  1764. if (mult == 65536) {
  1765. do {
  1766. uint32_t tmp32 = *dst;
  1767. *dst++ = signed_add_16_and_16(tmp32, *src++);
  1768. tmp32 = *dst;
  1769. *dst++ = signed_add_16_and_16(tmp32, *src++);
  1770. } while (dst < end);
  1771. } else {
  1772. do {
  1773. uint32_t tmp32 = *src++; // read 2 samples from *data
  1774. int32_t val1 = signed_multiply_32x16b(mult, tmp32);
  1775. int32_t val2 = signed_multiply_32x16t(mult, tmp32);
  1776. val1 = signed_saturate_rshift(val1, 16, 0);
  1777. val2 = signed_saturate_rshift(val2, 16, 0);
  1778. tmp32 = pack_16x16(val2, val1);
  1779. uint32_t tmp32b = *dst;
  1780. *dst++ = signed_add_16_and_16(tmp32, tmp32b);
  1781. } while (dst < end);
  1782. }
  1783. }
  1784. void AudioMixer4::update(void)
  1785. {
  1786. audio_block_t *in, *out=NULL;
  1787. unsigned int channel;
  1788. for (channel=0; channel < 4; channel++) {
  1789. if (!out) {
  1790. out = receiveWritable(channel);
  1791. if (out) {
  1792. int32_t mult = multiplier[channel];
  1793. if (mult != 65536) applyGain(out->data, mult);
  1794. }
  1795. } else {
  1796. in = receiveReadOnly(channel);
  1797. if (in) {
  1798. applyGainThenAdd(out->data, in->data, multiplier[channel]);
  1799. release(in);
  1800. }
  1801. }
  1802. }
  1803. if (out) {
  1804. transmit(out);
  1805. release(out);
  1806. }
  1807. }
  1808. /******************************************************************/
  1809. void AudioFilterBiquad::update(void)
  1810. {
  1811. audio_block_t *block;
  1812. int32_t a0, a1, a2, b1, b2, sum;
  1813. uint32_t in2, out2, aprev, bprev, flag;
  1814. uint32_t *data, *end;
  1815. int32_t *state;
  1816. block = receiveWritable();
  1817. if (!block) return;
  1818. data = (uint32_t *)(block->data);
  1819. end = data + AUDIO_BLOCK_SAMPLES/2;
  1820. state = (int32_t *)definition;
  1821. do {
  1822. a0 = *state++;
  1823. a1 = *state++;
  1824. a2 = *state++;
  1825. b1 = *state++;
  1826. b2 = *state++;
  1827. aprev = *state++;
  1828. bprev = *state++;
  1829. sum = *state & 0x3FFF;
  1830. do {
  1831. in2 = *data;
  1832. sum = signed_multiply_accumulate_32x16b(sum, a0, in2);
  1833. sum = signed_multiply_accumulate_32x16t(sum, a1, aprev);
  1834. sum = signed_multiply_accumulate_32x16b(sum, a2, aprev);
  1835. sum = signed_multiply_accumulate_32x16t(sum, b1, bprev);
  1836. sum = signed_multiply_accumulate_32x16b(sum, b2, bprev);
  1837. out2 = (uint32_t)sum >> 14;
  1838. sum &= 0x3FFF;
  1839. sum = signed_multiply_accumulate_32x16t(sum, a0, in2);
  1840. sum = signed_multiply_accumulate_32x16b(sum, a1, in2);
  1841. sum = signed_multiply_accumulate_32x16t(sum, a2, aprev);
  1842. sum = signed_multiply_accumulate_32x16b(sum, b1, out2);
  1843. sum = signed_multiply_accumulate_32x16t(sum, b2, bprev);
  1844. aprev = in2;
  1845. bprev = pack_16x16(sum >> 14, out2);
  1846. sum &= 0x3FFF;
  1847. aprev = in2;
  1848. *data++ = bprev;
  1849. } while (data < end);
  1850. flag = *state & 0x80000000;
  1851. *state++ = sum | flag;
  1852. *(state-2) = bprev;
  1853. *(state-3) = aprev;
  1854. } while (flag);
  1855. transmit(block);
  1856. release(block);
  1857. }
  1858. /******************************************************************/
  1859. extern "C" {
  1860. extern const int16_t fader_table[256];
  1861. };
  1862. void AudioEffectFade::update(void)
  1863. {
  1864. audio_block_t *block;
  1865. uint32_t i, pos, inc, index, scale;
  1866. int32_t val1, val2, val, sample;
  1867. uint8_t dir;
  1868. pos = position;
  1869. if (pos == 0) {
  1870. // output is silent
  1871. block = receiveReadOnly();
  1872. if (block) release(block);
  1873. return;
  1874. } else if (pos == 0xFFFFFFFF) {
  1875. // output is 100%
  1876. block = receiveReadOnly();
  1877. if (!block) return;
  1878. transmit(block);
  1879. release(block);
  1880. return;
  1881. }
  1882. block = receiveWritable();
  1883. if (!block) return;
  1884. inc = rate;
  1885. dir = direction;
  1886. for (i=0; i < AUDIO_BLOCK_SAMPLES; i++) {
  1887. index = pos >> 24;
  1888. val1 = fader_table[index];
  1889. val2 = fader_table[index+1];
  1890. scale = (pos >> 8) & 0xFFFF;
  1891. val2 *= scale;
  1892. val1 *= 0x10000 - scale;
  1893. val = (val1 + val2) >> 16;
  1894. sample = block->data[i];
  1895. sample = (sample * val) >> 15;
  1896. block->data[i] = sample;
  1897. if (dir > 0) {
  1898. // output is increasing
  1899. if (inc < 0xFFFFFFFF - pos) pos += inc;
  1900. else pos = 0xFFFFFFFF;
  1901. } else {
  1902. // output is decreasing
  1903. if (inc < pos) pos -= inc;
  1904. else pos = 0;
  1905. }
  1906. }
  1907. position = pos;
  1908. transmit(block);
  1909. release(block);
  1910. }
  1911. void AudioEffectFade::fadeBegin(uint32_t newrate, uint8_t dir)
  1912. {
  1913. __disable_irq();
  1914. uint32_t pos = position;
  1915. if (pos == 0) position = 1;
  1916. else if (pos == 0xFFFFFFFF) position = 0xFFFFFFFE;
  1917. rate = newrate;
  1918. direction = dir;
  1919. __enable_irq();
  1920. }
  1921. /******************************************************************/
  1922. static inline int32_t multiply_32x32_rshift30(int32_t a, int32_t b) __attribute__((always_inline));
  1923. static inline int32_t multiply_32x32_rshift30(int32_t a, int32_t b)
  1924. {
  1925. return ((int64_t)a * (int64_t)b) >> 30;
  1926. }
  1927. //#define TONE_DETECT_FAST
  1928. void AudioAnalyzeToneDetect::update(void)
  1929. {
  1930. audio_block_t *block;
  1931. int32_t q0, q1, q2, coef;
  1932. const int16_t *p, *end;
  1933. uint16_t n;
  1934. block = receiveReadOnly();
  1935. if (!block) return;
  1936. if (!enabled) {
  1937. release(block);
  1938. return;
  1939. }
  1940. p = block->data;
  1941. end = p + AUDIO_BLOCK_SAMPLES;
  1942. n = count;
  1943. coef = coefficient;
  1944. q1 = s1;
  1945. q2 = s2;
  1946. do {
  1947. // the Goertzel algorithm is kinda magical ;-)
  1948. #ifdef TONE_DETECT_FAST
  1949. q0 = (*p++) + (multiply_32x32_rshift32_rounded(coef, q1) << 2) - q2;
  1950. #else
  1951. q0 = (*p++) + multiply_32x32_rshift30(coef, q1) - q2;
  1952. // TODO: is this only 1 cycle slower? if so, always use it
  1953. #endif
  1954. q2 = q1;
  1955. q1 = q0;
  1956. if (--n == 0) {
  1957. out1 = q1;
  1958. out2 = q2;
  1959. q1 = 0; // TODO: does clearing these help or hinder?
  1960. q2 = 0;
  1961. new_output = true;
  1962. n = length;
  1963. }
  1964. } while (p < end);
  1965. count = n;
  1966. s1 = q1;
  1967. s2 = q2;
  1968. release(block);
  1969. }
  1970. void AudioAnalyzeToneDetect::set_params(int32_t coef, uint16_t cycles, uint16_t len)
  1971. {
  1972. __disable_irq();
  1973. coefficient = coef;
  1974. ncycles = cycles;
  1975. length = len;
  1976. count = len;
  1977. s1 = 0;
  1978. s2 = 0;
  1979. enabled = true;
  1980. __enable_irq();
  1981. //Serial.printf("Tone: coef=%d, ncycles=%d, length=%d\n", coefficient, ncycles, length);
  1982. }
  1983. float AudioAnalyzeToneDetect::read(void)
  1984. {
  1985. int32_t coef, q1, q2, power;
  1986. uint16_t len;
  1987. __disable_irq();
  1988. coef = coefficient;
  1989. q1 = out1;
  1990. q2 = out2;
  1991. len = length;
  1992. __enable_irq();
  1993. #ifdef TONE_DETECT_FAST
  1994. power = multiply_32x32_rshift32_rounded(q2, q2);
  1995. power = multiply_accumulate_32x32_rshift32_rounded(power, q1, q1);
  1996. power = multiply_subtract_32x32_rshift32_rounded(power,
  1997. multiply_32x32_rshift30(q1, q2), coef);
  1998. power <<= 4;
  1999. #else
  2000. int64_t power64;
  2001. power64 = (int64_t)q2 * (int64_t)q2;
  2002. power64 += (int64_t)q1 * (int64_t)q1;
  2003. power64 -= (((int64_t)q1 * (int64_t)q2) >> 30) * (int64_t)coef;
  2004. power = power64 >> 28;
  2005. #endif
  2006. return sqrtf((float)power) / (float)len;
  2007. }
  2008. AudioAnalyzeToneDetect::operator bool()
  2009. {
  2010. int32_t coef, q1, q2, power, trigger;
  2011. uint16_t len;
  2012. __disable_irq();
  2013. coef = coefficient;
  2014. q1 = out1;
  2015. q2 = out2;
  2016. len = length;
  2017. __enable_irq();
  2018. #ifdef TONE_DETECT_FAST
  2019. power = multiply_32x32_rshift32_rounded(q2, q2);
  2020. power = multiply_accumulate_32x32_rshift32_rounded(power, q1, q1);
  2021. power = multiply_subtract_32x32_rshift32_rounded(power,
  2022. multiply_32x32_rshift30(q1, q2), coef);
  2023. power <<= 4;
  2024. #else
  2025. int64_t power64;
  2026. power64 = (int64_t)q2 * (int64_t)q2;
  2027. power64 += (int64_t)q1 * (int64_t)q1;
  2028. power64 -= (((int64_t)q1 * (int64_t)q2) >> 30) * (int64_t)coef;
  2029. power = power64 >> 28;
  2030. #endif
  2031. trigger = (uint32_t)len * thresh;
  2032. trigger = multiply_32x32_rshift32(trigger, trigger);
  2033. Serial.printf("bool: power=%d, trig=%d\n", power, trigger);
  2034. return (power >= trigger);
  2035. }
  2036. /******************************************************************/
  2037. #include "Wire.h"
  2038. #define WM8731_I2C_ADDR 0x1A
  2039. //#define WM8731_I2C_ADDR 0x1B
  2040. #define WM8731_REG_LLINEIN 0
  2041. #define WM8731_REG_RLINEIN 1
  2042. #define WM8731_REG_LHEADOUT 2
  2043. #define WM8731_REG_RHEADOUT 3
  2044. #define WM8731_REG_ANALOG 4
  2045. #define WM8731_REG_DIGITAL 5
  2046. #define WM8731_REG_POWERDOWN 6
  2047. #define WM8731_REG_INTERFACE 7
  2048. #define WM8731_REG_SAMPLING 8
  2049. #define WM8731_REG_ACTIVE 9
  2050. #define WM8731_REG_RESET 15
  2051. bool AudioControlWM8731::enable(void)
  2052. {
  2053. Wire.begin();
  2054. delay(5);
  2055. //write(WM8731_REG_RESET, 0);
  2056. write(WM8731_REG_INTERFACE, 0x02); // I2S, 16 bit, MCLK slave
  2057. write(WM8731_REG_SAMPLING, 0x20); // 256*Fs, 44.1 kHz, MCLK/1
  2058. // In order to prevent pops, the DAC should first be soft-muted (DACMU),
  2059. // the output should then be de-selected from the line and headphone output
  2060. // (DACSEL), then the DAC powered down (DACPD).
  2061. write(WM8731_REG_DIGITAL, 0x08); // DAC soft mute
  2062. write(WM8731_REG_ANALOG, 0x00); // disable all
  2063. write(WM8731_REG_POWERDOWN, 0x00); // codec powerdown
  2064. write(WM8731_REG_LHEADOUT, 0x80); // volume off
  2065. write(WM8731_REG_RHEADOUT, 0x80);
  2066. delay(100); // how long to power up?
  2067. write(WM8731_REG_ACTIVE, 1);
  2068. delay(5);
  2069. write(WM8731_REG_DIGITAL, 0x00); // DAC unmuted
  2070. write(WM8731_REG_ANALOG, 0x10); // DAC selected
  2071. return true;
  2072. }
  2073. bool AudioControlWM8731::write(unsigned int reg, unsigned int val)
  2074. {
  2075. Wire.beginTransmission(WM8731_I2C_ADDR);
  2076. Wire.write((reg << 1) | ((val >> 8) & 1));
  2077. Wire.write(val & 0xFF);
  2078. Wire.endTransmission();
  2079. return true;
  2080. }
  2081. bool AudioControlWM8731::volumeInteger(unsigned int n)
  2082. {
  2083. if (n > 127) n = 127;
  2084. //Serial.print("volumeInteger, n = ");
  2085. //Serial.println(n);
  2086. write(WM8731_REG_LHEADOUT, n | 0x180);
  2087. write(WM8731_REG_RHEADOUT, n | 0x80);
  2088. return true;
  2089. }
  2090. /******************************************************************/
  2091. bool AudioControlWM8731master::enable(void)
  2092. {
  2093. Wire.begin();
  2094. delay(5);
  2095. //write(WM8731_REG_RESET, 0);
  2096. write(WM8731_REG_INTERFACE, 0x42); // I2S, 16 bit, MCLK master
  2097. write(WM8731_REG_SAMPLING, 0x20); // 256*Fs, 44.1 kHz, MCLK/1
  2098. // In order to prevent pops, the DAC should first be soft-muted (DACMU),
  2099. // the output should then be de-selected from the line and headphone output
  2100. // (DACSEL), then the DAC powered down (DACPD).
  2101. write(WM8731_REG_DIGITAL, 0x08); // DAC soft mute
  2102. write(WM8731_REG_ANALOG, 0x00); // disable all
  2103. write(WM8731_REG_POWERDOWN, 0x00); // codec powerdown
  2104. write(WM8731_REG_LHEADOUT, 0x80); // volume off
  2105. write(WM8731_REG_RHEADOUT, 0x80);
  2106. delay(100); // how long to power up?
  2107. write(WM8731_REG_ACTIVE, 1);
  2108. delay(5);
  2109. write(WM8731_REG_DIGITAL, 0x00); // DAC unmuted
  2110. write(WM8731_REG_ANALOG, 0x10); // DAC selected
  2111. return true;
  2112. }
  2113. /******************************************************************/
  2114. #define CHIP_ID 0x0000
  2115. // 15:8 PARTID 0xA0 - 8 bit identifier for SGTL5000
  2116. // 7:0 REVID 0x00 - revision number for SGTL5000.
  2117. #define CHIP_DIG_POWER 0x0002
  2118. // 6 ADC_POWERUP 1=Enable, 0=disable the ADC block, both digital & analog,
  2119. // 5 DAC_POWERUP 1=Enable, 0=disable the DAC block, both analog and digital
  2120. // 4 DAP_POWERUP 1=Enable, 0=disable the DAP block
  2121. // 1 I2S_OUT_POWERUP 1=Enable, 0=disable the I2S data output
  2122. // 0 I2S_IN_POWERUP 1=Enable, 0=disable the I2S data input
  2123. #define CHIP_CLK_CTRL 0x0004
  2124. // 5:4 RATE_MODE Sets the sample rate mode. MCLK_FREQ is still specified
  2125. // relative to the rate in SYS_FS
  2126. // 0x0 = SYS_FS specifies the rate
  2127. // 0x1 = Rate is 1/2 of the SYS_FS rate
  2128. // 0x2 = Rate is 1/4 of the SYS_FS rate
  2129. // 0x3 = Rate is 1/6 of the SYS_FS rate
  2130. // 3:2 SYS_FS Sets the internal system sample rate (default=2)
  2131. // 0x0 = 32 kHz
  2132. // 0x1 = 44.1 kHz
  2133. // 0x2 = 48 kHz
  2134. // 0x3 = 96 kHz
  2135. // 1:0 MCLK_FREQ Identifies incoming SYS_MCLK frequency and if the PLL should be used
  2136. // 0x0 = 256*Fs
  2137. // 0x1 = 384*Fs
  2138. // 0x2 = 512*Fs
  2139. // 0x3 = Use PLL
  2140. // The 0x3 (Use PLL) setting must be used if the SYS_MCLK is not
  2141. // a standard multiple of Fs (256, 384, or 512). This setting can
  2142. // also be used if SYS_MCLK is a standard multiple of Fs.
  2143. // Before this field is set to 0x3 (Use PLL), the PLL must be
  2144. // powered up by setting CHIP_ANA_POWER->PLL_POWERUP and
  2145. // CHIP_ANA_POWER->VCOAMP_POWERUP. Also, the PLL dividers must
  2146. // be calculated based on the external MCLK rate and
  2147. // CHIP_PLL_CTRL register must be set (see CHIP_PLL_CTRL register
  2148. // description details on how to calculate the divisors).
  2149. #define CHIP_I2S_CTRL 0x0006
  2150. // 8 SCLKFREQ Sets frequency of I2S_SCLK when in master mode (MS=1). When in slave
  2151. // mode (MS=0), this field must be set appropriately to match SCLK input
  2152. // rate.
  2153. // 0x0 = 64Fs
  2154. // 0x1 = 32Fs - Not supported for RJ mode (I2S_MODE = 1)
  2155. // 7 MS Configures master or slave of I2S_LRCLK and I2S_SCLK.
  2156. // 0x0 = Slave: I2S_LRCLK an I2S_SCLK are inputs
  2157. // 0x1 = Master: I2S_LRCLK and I2S_SCLK are outputs
  2158. // NOTE: If the PLL is used (CHIP_CLK_CTRL->MCLK_FREQ==0x3),
  2159. // the SGTL5000 must be a master of the I2S port (MS==1)
  2160. // 6 SCLK_INV Sets the edge that data (input and output) is clocked in on for I2S_SCLK
  2161. // 0x0 = data is valid on rising edge of I2S_SCLK
  2162. // 0x1 = data is valid on falling edge of I2S_SCLK
  2163. // 5:4 DLEN I2S data length (default=1)
  2164. // 0x0 = 32 bits (only valid when SCLKFREQ=0),
  2165. // not valid for Right Justified Mode
  2166. // 0x1 = 24 bits (only valid when SCLKFREQ=0)
  2167. // 0x2 = 20 bits
  2168. // 0x3 = 16 bits
  2169. // 3:2 I2S_MODE Sets the mode for the I2S port
  2170. // 0x0 = I2S mode or Left Justified (Use LRALIGN to select)
  2171. // 0x1 = Right Justified Mode
  2172. // 0x2 = PCM Format A/B
  2173. // 0x3 = RESERVED
  2174. // 1 LRALIGN I2S_LRCLK Alignment to data word. Not used for Right Justified mode
  2175. // 0x0 = Data word starts 1 I2S_SCLK delay after I2S_LRCLK
  2176. // transition (I2S format, PCM format A)
  2177. // 0x1 = Data word starts after I2S_LRCLK transition (left
  2178. // justified format, PCM format B)
  2179. // 0 LRPOL I2S_LRCLK Polarity when data is presented.
  2180. // 0x0 = I2S_LRCLK = 0 - Left, 1 - Right
  2181. // 1x0 = I2S_LRCLK = 0 - Right, 1 - Left
  2182. // The left subframe should be presented first regardless of
  2183. // the setting of LRPOL.
  2184. #define CHIP_SSS_CTRL 0x000A
  2185. // 14 DAP_MIX_LRSWAP DAP Mixer Input Swap
  2186. // 0x0 = Normal Operation
  2187. // 0x1 = Left and Right channels for the DAP MIXER Input are swapped.
  2188. // 13 DAP_LRSWAP DAP Mixer Input Swap
  2189. // 0x0 = Normal Operation
  2190. // 0x1 = Left and Right channels for the DAP Input are swapped
  2191. // 12 DAC_LRSWAP DAC Input Swap
  2192. // 0x0 = Normal Operation
  2193. // 0x1 = Left and Right channels for the DAC are swapped
  2194. // 10 I2S_LRSWAP I2S_DOUT Swap
  2195. // 0x0 = Normal Operation
  2196. // 0x1 = Left and Right channels for the I2S_DOUT are swapped
  2197. // 9:8 DAP_MIX_SELECT Select data source for DAP mixer
  2198. // 0x0 = ADC
  2199. // 0x1 = I2S_IN
  2200. // 0x2 = Reserved
  2201. // 0x3 = Reserved
  2202. // 7:6 DAP_SELECT Select data source for DAP
  2203. // 0x0 = ADC
  2204. // 0x1 = I2S_IN
  2205. // 0x2 = Reserved
  2206. // 0x3 = Reserved
  2207. // 5:4 DAC_SELECT Select data source for DAC (default=1)
  2208. // 0x0 = ADC
  2209. // 0x1 = I2S_IN
  2210. // 0x2 = Reserved
  2211. // 0x3 = DAP
  2212. // 1:0 I2S_SELECT Select data source for I2S_DOUT
  2213. // 0x0 = ADC
  2214. // 0x1 = I2S_IN
  2215. // 0x2 = Reserved
  2216. // 0x3 = DAP
  2217. #define CHIP_ADCDAC_CTRL 0x000E
  2218. // 13 VOL_BUSY_DAC_RIGHT Volume Busy DAC Right
  2219. // 0x0 = Ready
  2220. // 0x1 = Busy - This indicates the channel has not reached its
  2221. // programmed volume/mute level
  2222. // 12 VOL_BUSY_DAC_LEFT Volume Busy DAC Left
  2223. // 0x0 = Ready
  2224. // 0x1 = Busy - This indicates the channel has not reached its
  2225. // programmed volume/mute level
  2226. // 9 VOL_RAMP_EN Volume Ramp Enable (default=1)
  2227. // 0x0 = Disables volume ramp. New volume settings take immediate
  2228. // effect without a ramp
  2229. // 0x1 = Enables volume ramp
  2230. // This field affects DAC_VOL. The volume ramp effects both
  2231. // volume settings and mute When set to 1 a soft mute is enabled.
  2232. // 8 VOL_EXPO_RAMP Exponential Volume Ramp Enable
  2233. // 0x0 = Linear ramp over top 4 volume octaves
  2234. // 0x1 = Exponential ramp over full volume range
  2235. // This bit only takes effect if VOL_RAMP_EN is 1.
  2236. // 3 DAC_MUTE_RIGHT DAC Right Mute (default=1)
  2237. // 0x0 = Unmute
  2238. // 0x1 = Muted
  2239. // If VOL_RAMP_EN = 1, this is a soft mute.
  2240. // 2 DAC_MUTE_LEFT DAC Left Mute (default=1)
  2241. // 0x0 = Unmute
  2242. // 0x1 = Muted
  2243. // If VOL_RAMP_EN = 1, this is a soft mute.
  2244. // 1 ADC_HPF_FREEZE ADC High Pass Filter Freeze
  2245. // 0x0 = Normal operation
  2246. // 0x1 = Freeze the ADC high-pass filter offset register. The
  2247. // offset continues to be subtracted from the ADC data stream.
  2248. // 0 ADC_HPF_BYPASS ADC High Pass Filter Bypass
  2249. // 0x0 = Normal operation
  2250. // 0x1 = Bypassed and offset not updated
  2251. #define CHIP_DAC_VOL 0x0010
  2252. // 15:8 DAC_VOL_RIGHT DAC Right Channel Volume. Set the Right channel DAC volume
  2253. // with 0.5017 dB steps from 0 to -90 dB
  2254. // 0x3B and less = Reserved
  2255. // 0x3C = 0 dB
  2256. // 0x3D = -0.5 dB
  2257. // 0xF0 = -90 dB
  2258. // 0xFC and greater = Muted
  2259. // If VOL_RAMP_EN = 1, there is an automatic ramp to the
  2260. // new volume setting.
  2261. // 7:0 DAC_VOL_LEFT DAC Left Channel Volume. Set the Left channel DAC volume
  2262. // with 0.5017 dB steps from 0 to -90 dB
  2263. // 0x3B and less = Reserved
  2264. // 0x3C = 0 dB
  2265. // 0x3D = -0.5 dB
  2266. // 0xF0 = -90 dB
  2267. // 0xFC and greater = Muted
  2268. // If VOL_RAMP_EN = 1, there is an automatic ramp to the
  2269. // new volume setting.
  2270. #define CHIP_PAD_STRENGTH 0x0014
  2271. // 9:8 I2S_LRCLK I2S LRCLK Pad Drive Strength (default=1)
  2272. // Sets drive strength for output pads per the table below.
  2273. // VDDIO 1.8 V 2.5 V 3.3 V
  2274. // 0x0 = Disable
  2275. // 0x1 = 1.66 mA 2.87 mA 4.02 mA
  2276. // 0x2 = 3.33 mA 5.74 mA 8.03 mA
  2277. // 0x3 = 4.99 mA 8.61 mA 12.05 mA
  2278. // 7:6 I2S_SCLK I2S SCLK Pad Drive Strength (default=1)
  2279. // 5:4 I2S_DOUT I2S DOUT Pad Drive Strength (default=1)
  2280. // 3:2 CTRL_DATA I2C DATA Pad Drive Strength (default=3)
  2281. // 1:0 CTRL_CLK I2C CLK Pad Drive Strength (default=3)
  2282. // (all use same table as I2S_LRCLK)
  2283. #define CHIP_ANA_ADC_CTRL 0x0020
  2284. // 8 ADC_VOL_M6DB ADC Volume Range Reduction
  2285. // This bit shifts both right and left analog ADC volume
  2286. // range down by 6.0 dB.
  2287. // 0x0 = No change in ADC range
  2288. // 0x1 = ADC range reduced by 6.0 dB
  2289. // 7:4 ADC_VOL_RIGHT ADC Right Channel Volume
  2290. // Right channel analog ADC volume control in 1.5 dB steps.
  2291. // 0x0 = 0 dB
  2292. // 0x1 = +1.5 dB
  2293. // ...
  2294. // 0xF = +22.5 dB
  2295. // This range is -6.0 dB to +16.5 dB if ADC_VOL_M6DB is set to 1.
  2296. // 3:0 ADC_VOL_LEFT ADC Left Channel Volume
  2297. // (same scale as ADC_VOL_RIGHT)
  2298. #define CHIP_ANA_HP_CTRL 0x0022
  2299. // 14:8 HP_VOL_RIGHT Headphone Right Channel Volume (default 0x18)
  2300. // Right channel headphone volume control with 0.5 dB steps.
  2301. // 0x00 = +12 dB
  2302. // 0x01 = +11.5 dB
  2303. // 0x18 = 0 dB
  2304. // ...
  2305. // 0x7F = -51.5 dB
  2306. // 6:0 HP_VOL_LEFT Headphone Left Channel Volume (default 0x18)
  2307. // (same scale as HP_VOL_RIGHT)
  2308. #define CHIP_ANA_CTRL 0x0024
  2309. // 8 MUTE_LO LINEOUT Mute, 0 = Unmute, 1 = Mute (default 1)
  2310. // 6 SELECT_HP Select the headphone input, 0 = DAC, 1 = LINEIN
  2311. // 5 EN_ZCD_HP Enable the headphone zero cross detector (ZCD)
  2312. // 0x0 = HP ZCD disabled
  2313. // 0x1 = HP ZCD enabled
  2314. // 4 MUTE_HP Mute the headphone outputs, 0 = Unmute, 1 = Mute (default)
  2315. // 2 SELECT_ADC Select the ADC input, 0 = Microphone, 1 = LINEIN
  2316. // 1 EN_ZCD_ADC Enable the ADC analog zero cross detector (ZCD)
  2317. // 0x0 = ADC ZCD disabled
  2318. // 0x1 = ADC ZCD enabled
  2319. // 0 MUTE_ADC Mute the ADC analog volume, 0 = Unmute, 1 = Mute (default)
  2320. #define CHIP_LINREG_CTRL 0x0026
  2321. // 6 VDDC_MAN_ASSN Determines chargepump source when VDDC_ASSN_OVRD is set.
  2322. // 0x0 = VDDA
  2323. // 0x1 = VDDIO
  2324. // 5 VDDC_ASSN_OVRD Charge pump Source Assignment Override
  2325. // 0x0 = Charge pump source is automatically assigned based
  2326. // on higher of VDDA and VDDIO
  2327. // 0x1 = the source of charge pump is manually assigned by
  2328. // VDDC_MAN_ASSN If VDDIO and VDDA are both the same
  2329. // and greater than 3.1 V, VDDC_ASSN_OVRD and
  2330. // VDDC_MAN_ASSN should be used to manually assign
  2331. // VDDIO as the source for charge pump.
  2332. // 3:0 D_PROGRAMMING Sets the VDDD linear regulator output voltage in 50 mV steps.
  2333. // Must clear the LINREG_SIMPLE_POWERUP and STARTUP_POWERUP bits
  2334. // in the 0x0030 (CHIP_ANA_POWER) register after power-up, for
  2335. // this setting to produce the proper VDDD voltage.
  2336. // 0x0 = 1.60
  2337. // 0xF = 0.85
  2338. #define CHIP_REF_CTRL 0x0028 // bandgap reference bias voltage and currents
  2339. // 8:4 VAG_VAL Analog Ground Voltage Control
  2340. // These bits control the analog ground voltage in 25 mV steps.
  2341. // This should usually be set to VDDA/2 or lower for best
  2342. // performance (maximum output swing at minimum THD). This VAG
  2343. // reference is also used for the DAC and ADC voltage reference.
  2344. // So changing this voltage scales the output swing of the DAC
  2345. // and the output signal of the ADC.
  2346. // 0x00 = 0.800 V
  2347. // 0x1F = 1.575 V
  2348. // 3:1 BIAS_CTRL Bias control
  2349. // These bits adjust the bias currents for all of the analog
  2350. // blocks. By lowering the bias current a lower quiescent power
  2351. // is achieved. It should be noted that this mode can affect
  2352. // performance by 3-4 dB.
  2353. // 0x0 = Nominal
  2354. // 0x1-0x3=+12.5%
  2355. // 0x4=-12.5%
  2356. // 0x5=-25%
  2357. // 0x6=-37.5%
  2358. // 0x7=-50%
  2359. // 0 SMALL_POP VAG Ramp Control
  2360. // Setting this bit slows down the VAG ramp from ~200 to ~400 ms
  2361. // to reduce the startup pop, but increases the turn on/off time.
  2362. // 0x0 = Normal VAG ramp
  2363. // 0x1 = Slow down VAG ramp
  2364. #define CHIP_MIC_CTRL 0x002A // microphone gain & internal microphone bias
  2365. // 9:8 BIAS_RESISTOR MIC Bias Output Impedance Adjustment
  2366. // Controls an adjustable output impedance for the microphone bias.
  2367. // If this is set to zero the micbias block is powered off and
  2368. // the output is highZ.
  2369. // 0x0 = Powered off
  2370. // 0x1 = 2.0 kohm
  2371. // 0x2 = 4.0 kohm
  2372. // 0x3 = 8.0 kohm
  2373. // 6:4 BIAS_VOLT MIC Bias Voltage Adjustment
  2374. // Controls an adjustable bias voltage for the microphone bias
  2375. // amp in 250 mV steps. This bias voltage setting should be no
  2376. // more than VDDA-200 mV for adequate power supply rejection.
  2377. // 0x0 = 1.25 V
  2378. // ...
  2379. // 0x7 = 3.00 V
  2380. // 1:0 GAIN MIC Amplifier Gain
  2381. // Sets the microphone amplifier gain. At 0 dB setting the THD
  2382. // can be slightly higher than other paths- typically around
  2383. // ~65 dB. At other gain settings the THD are better.
  2384. // 0x0 = 0 dB
  2385. // 0x1 = +20 dB
  2386. // 0x2 = +30 dB
  2387. // 0x3 = +40 dB
  2388. #define CHIP_LINE_OUT_CTRL 0x002C
  2389. // 11:8 OUT_CURRENT Controls the output bias current for the LINEOUT amplifiers. The
  2390. // nominal recommended setting for a 10 kohm load with 1.0 nF load cap
  2391. // is 0x3. There are only 5 valid settings.
  2392. // 0x0=0.18 mA
  2393. // 0x1=0.27 mA
  2394. // 0x3=0.36 mA
  2395. // 0x7=0.45 mA
  2396. // 0xF=0.54 mA
  2397. // 5:0 LO_VAGCNTRL LINEOUT Amplifier Analog Ground Voltage
  2398. // Controls the analog ground voltage for the LINEOUT amplifiers
  2399. // in 25 mV steps. This should usually be set to VDDIO/2.
  2400. // 0x00 = 0.800 V
  2401. // ...
  2402. // 0x1F = 1.575 V
  2403. // ...
  2404. // 0x23 = 1.675 V
  2405. // 0x24-0x3F are invalid
  2406. #define CHIP_LINE_OUT_VOL 0x002E
  2407. // 12:8 LO_VOL_RIGHT LINEOUT Right Channel Volume (default=4)
  2408. // Controls the right channel LINEOUT volume in 0.5 dB steps.
  2409. // Higher codes have more attenuation.
  2410. // 4:0 LO_VOL_LEFT LINEOUT Left Channel Output Level (default=4)
  2411. // Used to normalize the output level of the left line output
  2412. // to full scale based on the values used to set
  2413. // LINE_OUT_CTRL->LO_VAGCNTRL and CHIP_REF_CTRL->VAG_VAL.
  2414. // In general this field should be set to:
  2415. // 40*log((VAG_VAL)/(LO_VAGCNTRL)) + 15
  2416. // Suggested values based on typical VDDIO and VDDA voltages.
  2417. // VDDA VAG_VAL VDDIO LO_VAGCNTRL LO_VOL_*
  2418. // 1.8 V 0.9 3.3 V 1.55 0x06
  2419. // 1.8 V 0.9 1.8 V 0.9 0x0F
  2420. // 3.3 V 1.55 1.8 V 0.9 0x19
  2421. // 3.3 V 1.55 3.3 V 1.55 0x0F
  2422. // After setting to the nominal voltage, this field can be used
  2423. // to adjust the output level in +/-0.5 dB increments by using
  2424. // values higher or lower than the nominal setting.
  2425. #define CHIP_ANA_POWER 0x0030 // power down controls for the analog blocks.
  2426. // The only other power-down controls are BIAS_RESISTOR in the MIC_CTRL register
  2427. // and the EN_ZCD control bits in ANA_CTRL.
  2428. // 14 DAC_MONO While DAC_POWERUP is set, this allows the DAC to be put into left only
  2429. // mono operation for power savings. 0=mono, 1=stereo (default)
  2430. // 13 LINREG_SIMPLE_POWERUP Power up the simple (low power) digital supply regulator.
  2431. // After reset, this bit can be cleared IF VDDD is driven
  2432. // externally OR the primary digital linreg is enabled with
  2433. // LINREG_D_POWERUP
  2434. // 12 STARTUP_POWERUP Power up the circuitry needed during the power up ramp and reset.
  2435. // After reset this bit can be cleared if VDDD is coming from
  2436. // an external source.
  2437. // 11 VDDC_CHRGPMP_POWERUP Power up the VDDC charge pump block. If neither VDDA or VDDIO
  2438. // is 3.0 V or larger this bit should be cleared before analog
  2439. // blocks are powered up.
  2440. // 10 PLL_POWERUP PLL Power Up, 0 = Power down, 1 = Power up
  2441. // When cleared, the PLL is turned off. This must be set before
  2442. // CHIP_CLK_CTRL->MCLK_FREQ is programmed to 0x3. The
  2443. // CHIP_PLL_CTRL register must be configured correctly before
  2444. // setting this bit.
  2445. // 9 LINREG_D_POWERUP Power up the primary VDDD linear regulator, 0 = Power down, 1 = Power up
  2446. // 8 VCOAMP_POWERUP Power up the PLL VCO amplifier, 0 = Power down, 1 = Power up
  2447. // 7 VAG_POWERUP Power up the VAG reference buffer.
  2448. // Setting this bit starts the power up ramp for the headphone
  2449. // and LINEOUT. The headphone (and/or LINEOUT) powerup should
  2450. // be set BEFORE clearing this bit. When this bit is cleared
  2451. // the power-down ramp is started. The headphone (and/or LINEOUT)
  2452. // powerup should stay set until the VAG is fully ramped down
  2453. // (200 to 400 ms after clearing this bit).
  2454. // 0x0 = Power down, 0x1 = Power up
  2455. // 6 ADC_MONO While ADC_POWERUP is set, this allows the ADC to be put into left only
  2456. // mono operation for power savings. This mode is useful when
  2457. // only using the microphone input.
  2458. // 0x0 = Mono (left only), 0x1 = Stereo
  2459. // 5 REFTOP_POWERUP Power up the reference bias currents
  2460. // 0x0 = Power down, 0x1 = Power up
  2461. // This bit can be cleared when the part is a sleep state
  2462. // to minimize analog power.
  2463. // 4 HEADPHONE_POWERUP Power up the headphone amplifiers
  2464. // 0x0 = Power down, 0x1 = Power up
  2465. // 3 DAC_POWERUP Power up the DACs
  2466. // 0x0 = Power down, 0x1 = Power up
  2467. // 2 CAPLESS_HEADPHONE_POWERUP Power up the capless headphone mode
  2468. // 0x0 = Power down, 0x1 = Power up
  2469. // 1 ADC_POWERUP Power up the ADCs
  2470. // 0x0 = Power down, 0x1 = Power up
  2471. // 0 LINEOUT_POWERUP Power up the LINEOUT amplifiers
  2472. // 0x0 = Power down, 0x1 = Power up
  2473. #define CHIP_PLL_CTRL 0x0032
  2474. // 15:11 INT_DIVISOR
  2475. // 10:0 FRAC_DIVISOR
  2476. #define CHIP_CLK_TOP_CTRL 0x0034
  2477. // 11 ENABLE_INT_OSC Setting this bit enables an internal oscillator to be used for the
  2478. // zero cross detectors, the short detect recovery, and the
  2479. // charge pump. This allows the I2S clock to be shut off while
  2480. // still operating an analog signal path. This bit can be kept
  2481. // on when the I2S clock is enabled, but the I2S clock is more
  2482. // accurate so it is preferred to clear this bit when I2S is present.
  2483. // 3 INPUT_FREQ_DIV2 SYS_MCLK divider before PLL input
  2484. // 0x0 = pass through
  2485. // 0x1 = SYS_MCLK is divided by 2 before entering PLL
  2486. // This must be set when the input clock is above 17 Mhz. This
  2487. // has no effect when the PLL is powered down.
  2488. #define CHIP_ANA_STATUS 0x0036
  2489. // 9 LRSHORT_STS This bit is high whenever a short is detected on the left or right
  2490. // channel headphone drivers.
  2491. // 8 CSHORT_STS This bit is high whenever a short is detected on the capless headphone
  2492. // common/center channel driver.
  2493. // 4 PLL_IS_LOCKED This bit goes high after the PLL is locked.
  2494. #define CHIP_ANA_TEST1 0x0038 // intended only for debug.
  2495. #define CHIP_ANA_TEST2 0x003A // intended only for debug.
  2496. #define CHIP_SHORT_CTRL 0x003C
  2497. // 14:12 LVLADJR Right channel headphone short detector in 25 mA steps.
  2498. // 0x3=25 mA
  2499. // 0x2=50 mA
  2500. // 0x1=75 mA
  2501. // 0x0=100 mA
  2502. // 0x4=125 mA
  2503. // 0x5=150 mA
  2504. // 0x6=175 mA
  2505. // 0x7=200 mA
  2506. // This trip point can vary by ~30% over process so leave plenty
  2507. // of guard band to avoid false trips. This short detect trip
  2508. // point is also effected by the bias current adjustments made
  2509. // by CHIP_REF_CTRL->BIAS_CTRL and by CHIP_ANA_TEST1->HP_IALL_ADJ.
  2510. // 10:8 LVLADJL Left channel headphone short detector in 25 mA steps.
  2511. // (same scale as LVLADJR)
  2512. // 6:4 LVLADJC Capless headphone center channel short detector in 50 mA steps.
  2513. // 0x3=50 mA
  2514. // 0x2=100 mA
  2515. // 0x1=150 mA
  2516. // 0x0=200 mA
  2517. // 0x4=250 mA
  2518. // 0x5=300 mA
  2519. // 0x6=350 mA
  2520. // 0x7=400 mA
  2521. // 3:2 MODE_LR Behavior of left/right short detection
  2522. // 0x0 = Disable short detector, reset short detect latch,
  2523. // software view non-latched short signal
  2524. // 0x1 = Enable short detector and reset the latch at timeout
  2525. // (every ~50 ms)
  2526. // 0x2 = This mode is not used/invalid
  2527. // 0x3 = Enable short detector with only manual reset (have
  2528. // to return to 0x0 to reset the latch)
  2529. // 1:0 MODE_CM Behavior of capless headphone central short detection
  2530. // (same settings as MODE_LR)
  2531. #define DAP_CONTROL 0x0100
  2532. #define DAP_PEQ 0x0102
  2533. #define DAP_BASS_ENHANCE 0x0104
  2534. #define DAP_BASS_ENHANCE_CTRL 0x0106
  2535. #define DAP_AUDIO_EQ 0x0108
  2536. #define DAP_SGTL_SURROUND 0x010A
  2537. #define DAP_FILTER_COEF_ACCES 0x010C
  2538. #define DAP_COEF_WR_B0_MSB 0x010E
  2539. #define DAP_COEF_WR_B0_LSB 0x0110
  2540. #define DAP_AUDIO_EQ_BASS_BAND0 0x0116 // 115 Hz
  2541. #define DAP_AUDIO_EQ_BAND1 0x0118 // 330 Hz
  2542. #define DAP_AUDIO_EQ_BAND2 0x011A // 990 Hz
  2543. #define DAP_AUDIO_EQ_BAND3 0x011C // 3000 Hz
  2544. #define DAP_AUDIO_EQ_TREBLE_BAND4 0x011E // 9900 Hz
  2545. #define DAP_MAIN_CHAN 0x0120
  2546. #define DAP_MIX_CHAN 0x0122
  2547. #define DAP_AVC_CTRL 0x0124
  2548. #define DAP_AVC_THRESHOLD 0x0126
  2549. #define DAP_AVC_ATTACK 0x0128
  2550. #define DAP_AVC_DECAY 0x012A
  2551. #define DAP_COEF_WR_B1_MSB 0x012C
  2552. #define DAP_COEF_WR_B1_LSB 0x012E
  2553. #define DAP_COEF_WR_B2_MSB 0x0130
  2554. #define DAP_COEF_WR_B2_LSB 0x0132
  2555. #define DAP_COEF_WR_A1_MSB 0x0134
  2556. #define DAP_COEF_WR_A1_LSB 0x0136
  2557. #define DAP_COEF_WR_A2_MSB 0x0138
  2558. #define DAP_COEF_WR_A2_LSB 0x013A
  2559. #define SGTL5000_I2C_ADDR 0x0A // CTRL_ADR0_CS pin low (normal configuration)
  2560. //#define SGTL5000_I2C_ADDR 0x2A // CTRL_ADR0_CS pin high
  2561. bool AudioControlSGTL5000::enable(void)
  2562. {
  2563. //unsigned int n;
  2564. muted = true;
  2565. Wire.begin();
  2566. delay(5);
  2567. //Serial.print("chip ID = ");
  2568. //delay(5);
  2569. //n = read(CHIP_ID);
  2570. //Serial.println(n, HEX);
  2571. write(CHIP_ANA_POWER, 0x4060); // VDDD is externally driven with 1.8V
  2572. write(CHIP_LINREG_CTRL, 0x006C); // VDDA & VDDIO both over 3.1V
  2573. write(CHIP_REF_CTRL, 0x01F1); // VAG=1.575 slow ramp, normal bias current
  2574. write(CHIP_LINE_OUT_CTRL, 0x0322);
  2575. write(CHIP_SHORT_CTRL, 0x4446); // allow up to 125mA
  2576. write(CHIP_ANA_CTRL, 0x0137); // enable zero cross detectors
  2577. write(CHIP_ANA_POWER, 0x40FF); // power up: lineout, hp, adc, dac
  2578. write(CHIP_DIG_POWER, 0x0073); // power up all digital stuff
  2579. delay(400);
  2580. write(CHIP_LINE_OUT_VOL, 0x0505); // TODO: correct value for 3.3V
  2581. write(CHIP_CLK_CTRL, 0x0004); // 44.1 kHz, 256*Fs
  2582. write(CHIP_I2S_CTRL, 0x0130); // SCLK=32*Fs, 16bit, I2S format
  2583. // default signal routing is ok?
  2584. write(CHIP_SSS_CTRL, 0x0010); // ADC->I2S, I2S->DAC
  2585. write(CHIP_ADCDAC_CTRL, 0x0000); // disable dac mute
  2586. write(CHIP_DAC_VOL, 0x3C3C); // digital gain, 0dB
  2587. write(CHIP_ANA_HP_CTRL, 0x7F7F); // set volume (lowest level)
  2588. write(CHIP_ANA_CTRL, 0x0136); // enable zero cross detectors
  2589. //mute = false;
  2590. return true;
  2591. }
  2592. unsigned int AudioControlSGTL5000::read(unsigned int reg)
  2593. {
  2594. unsigned int val;
  2595. Wire.beginTransmission(SGTL5000_I2C_ADDR);
  2596. Wire.write(reg >> 8);
  2597. Wire.write(reg);
  2598. if (Wire.endTransmission(false) != 0) return 0;
  2599. if (Wire.requestFrom(SGTL5000_I2C_ADDR, 2) < 2) return 0;
  2600. val = Wire.read() << 8;
  2601. val |= Wire.read();
  2602. return val;
  2603. }
  2604. bool AudioControlSGTL5000::write(unsigned int reg, unsigned int val)
  2605. {
  2606. if (reg == CHIP_ANA_CTRL) ana_ctrl = val;
  2607. Wire.beginTransmission(SGTL5000_I2C_ADDR);
  2608. Wire.write(reg >> 8);
  2609. Wire.write(reg);
  2610. Wire.write(val >> 8);
  2611. Wire.write(val);
  2612. if (Wire.endTransmission() == 0) return true;
  2613. return false;
  2614. }
  2615. bool AudioControlSGTL5000::volumeInteger(unsigned int n)
  2616. {
  2617. if (n == 0) {
  2618. muted = true;
  2619. write(CHIP_ANA_HP_CTRL, 0x7F7F);
  2620. return muteHeadphone();
  2621. } else if (n > 0x80) {
  2622. n = 0;
  2623. } else {
  2624. n = 0x80 - n;
  2625. }
  2626. if (muted) {
  2627. muted = false;
  2628. unmuteHeadphone();
  2629. }
  2630. n = n | (n << 8);
  2631. return write(CHIP_ANA_HP_CTRL, n); // set volume
  2632. }