PlatformIO package of the Teensy core framework compatible with GCC 10 & C++20
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

468 lines
16KB

  1. /* Audio Library for Teensy 3.X
  2. * Copyright (c) 2019, Paul Stoffregen, paul@pjrc.com
  3. *
  4. * Development of this audio library was funded by PJRC.COM, LLC by sales of
  5. * Teensy and Audio Adaptor boards. Please support PJRC's efforts to develop
  6. * open source software by purchasing Teensy or other PJRC products.
  7. *
  8. * Permission is hereby granted, free of charge, to any person obtaining a copy
  9. * of this software and associated documentation files (the "Software"), to deal
  10. * in the Software without restriction, including without limitation the rights
  11. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. * copies of the Software, and to permit persons to whom the Software is
  13. * furnished to do so, subject to the following conditions:
  14. *
  15. * The above copyright notice, development funding notice, and this permission
  16. * notice shall be included in all copies or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  23. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  24. * THE SOFTWARE.
  25. */
  26. /*
  27. by Alexander Walch
  28. */
  29. #if defined(__IMXRT1052__) || defined(__IMXRT1062__)
  30. #include "async_input_spdif3.h"
  31. #include "biquad.h"
  32. #include <utility/imxrt_hw.h>
  33. //Parameters
  34. namespace {
  35. #define SPDIF_RX_BUFFER_LENGTH AUDIO_BLOCK_SAMPLES
  36. const int32_t bufferLength=8*AUDIO_BLOCK_SAMPLES;
  37. const uint16_t noSamplerPerIsr=SPDIF_RX_BUFFER_LENGTH/4;
  38. }
  39. volatile bool AsyncAudioInputSPDIF3::resetResampler=true;
  40. #ifdef DEBUG_SPDIF_IN
  41. volatile bool AsyncAudioInputSPDIF3::bufferOverflow=false;
  42. #endif
  43. volatile uint32_t AsyncAudioInputSPDIF3::microsLast;
  44. DMAMEM __attribute__((aligned(32)))
  45. static int32_t spdif_rx_buffer[SPDIF_RX_BUFFER_LENGTH];
  46. static float bufferR[bufferLength];
  47. static float bufferL[bufferLength];
  48. volatile int32_t AsyncAudioInputSPDIF3::buffer_offset = 0; // read by resample/ written in spdif input isr -> copied at the beginning of 'resmaple' protected by __disable_irq() in resample
  49. int32_t AsyncAudioInputSPDIF3::resample_offset = 0; // read/written by resample/ read in spdif input isr -> no protection needed?
  50. volatile bool AsyncAudioInputSPDIF3::lockChanged=false;
  51. volatile bool AsyncAudioInputSPDIF3::locked=false;
  52. DMAChannel AsyncAudioInputSPDIF3::dma(false);
  53. AsyncAudioInputSPDIF3::~AsyncAudioInputSPDIF3(){
  54. delete [] _bufferLPFilter.pCoeffs;
  55. delete [] _bufferLPFilter.pState;
  56. delete quantizer[0];
  57. delete quantizer[1];
  58. }
  59. PROGMEM
  60. AsyncAudioInputSPDIF3::AsyncAudioInputSPDIF3(bool dither, bool noiseshaping,float attenuation, int32_t minHalfFilterLength) : AudioStream(0, NULL) {
  61. _attenuation=attenuation;
  62. _minHalfFilterLength=minHalfFilterLength;
  63. const float factor = powf(2, 15)-1.f; // to 16 bit audio
  64. quantizer[0]=new Quantizer(AUDIO_SAMPLE_RATE_EXACT);
  65. quantizer[0]->configure(noiseshaping, dither, factor);
  66. quantizer[1]=new Quantizer(AUDIO_SAMPLE_RATE_EXACT);
  67. quantizer[1]->configure(noiseshaping, dither, factor);
  68. begin();
  69. }
  70. PROGMEM
  71. void AsyncAudioInputSPDIF3::begin()
  72. {
  73. dma.begin(true); // Allocate the DMA channel first
  74. const uint32_t noByteMinorLoop=2*4;
  75. dma.TCD->SOFF = 4;
  76. dma.TCD->ATTR = DMA_TCD_ATTR_SSIZE(2) | DMA_TCD_ATTR_DSIZE(2);
  77. dma.TCD->NBYTES_MLNO = DMA_TCD_NBYTES_MLOFFYES_NBYTES(noByteMinorLoop) | DMA_TCD_NBYTES_SMLOE |
  78. DMA_TCD_NBYTES_MLOFFYES_MLOFF(-8);
  79. dma.TCD->SLAST = -8;
  80. dma.TCD->DOFF = 4;
  81. dma.TCD->CITER_ELINKNO = sizeof(spdif_rx_buffer) / noByteMinorLoop;
  82. dma.TCD->DLASTSGA = -sizeof(spdif_rx_buffer);
  83. dma.TCD->BITER_ELINKNO = sizeof(spdif_rx_buffer) / noByteMinorLoop;
  84. dma.TCD->CSR = DMA_TCD_CSR_INTHALF | DMA_TCD_CSR_INTMAJOR;
  85. dma.TCD->SADDR = (void *)((uint32_t)&SPDIF_SRL);
  86. dma.TCD->DADDR = spdif_rx_buffer;
  87. dma.triggerAtHardwareEvent(DMAMUX_SOURCE_SPDIF_RX);
  88. SPDIF_SCR |=SPDIF_SCR_DMA_RX_EN; //DMA Receive Request Enable
  89. dma.enable();
  90. dma.attachInterrupt(isr);
  91. config_spdifIn();
  92. #ifdef DEBUG_SPDIF_IN
  93. while (!Serial);
  94. #endif
  95. _bufferLPFilter.pCoeffs=new float[5];
  96. _bufferLPFilter.numStages=1;
  97. _bufferLPFilter.pState=new float[2];
  98. getCoefficients(_bufferLPFilter.pCoeffs, BiquadType::LOW_PASS, 0., 5., AUDIO_SAMPLE_RATE_EXACT/AUDIO_BLOCK_SAMPLES, 0.5);
  99. }
  100. bool AsyncAudioInputSPDIF3::isLocked() const {
  101. __disable_irq();
  102. bool l=locked;
  103. __enable_irq();
  104. return l;
  105. }
  106. void AsyncAudioInputSPDIF3::spdif_interrupt(){
  107. if(SPDIF_SIS & SPDIF_SIS_LOCK){
  108. if (!locked){
  109. locked=true;
  110. lockChanged=true;
  111. }
  112. }
  113. else if(SPDIF_SIS & SPDIF_SIS_LOCKLOSS){
  114. if (locked){
  115. locked=false;
  116. lockChanged=true;
  117. resetResampler=true;
  118. }
  119. }
  120. SPDIF_SIC |= SPDIF_SIC_LOCKLOSS;//clear SPDIF_SIC_LOCKLOSS interrupt
  121. SPDIF_SIC |= SPDIF_SIC_LOCK; //clear SPDIF_SIC_LOCK interrupt
  122. }
  123. void AsyncAudioInputSPDIF3::resample(int16_t* data_left, int16_t* data_right, int32_t& block_offset){
  124. block_offset=0;
  125. if(!_resampler.initialized()){
  126. return;
  127. }
  128. __disable_irq();
  129. if(!locked){
  130. __enable_irq();
  131. return;
  132. }
  133. int32_t bOffset=buffer_offset;
  134. int32_t resOffset=resample_offset;
  135. __enable_irq();
  136. uint16_t inputBufferStop = bOffset >= resOffset ? bOffset-resOffset : bufferLength-resOffset;
  137. if (inputBufferStop==0){
  138. return;
  139. }
  140. uint16_t processedLength;
  141. uint16_t outputCount=0;
  142. uint16_t outputLength=AUDIO_BLOCK_SAMPLES;
  143. float resampledBufferL[AUDIO_BLOCK_SAMPLES];
  144. float resampledBufferR[AUDIO_BLOCK_SAMPLES];
  145. _resampler.resample(&bufferL[resOffset],&bufferR[resOffset], inputBufferStop, processedLength, resampledBufferL, resampledBufferR, outputLength, outputCount);
  146. resOffset=(resOffset+processedLength)%bufferLength;
  147. block_offset=outputCount;
  148. if (bOffset > resOffset && block_offset< AUDIO_BLOCK_SAMPLES){
  149. inputBufferStop= bOffset-resOffset;
  150. outputLength=AUDIO_BLOCK_SAMPLES-block_offset;
  151. _resampler.resample(&bufferL[resOffset],&bufferR[resOffset], inputBufferStop, processedLength, resampledBufferL+block_offset, resampledBufferR+block_offset, outputLength, outputCount);
  152. resOffset=(resOffset+processedLength)%bufferLength;
  153. block_offset+=outputCount;
  154. }
  155. quantizer[0]->quantize(resampledBufferL, data_left, block_offset);
  156. quantizer[1]->quantize(resampledBufferR, data_right, block_offset);
  157. __disable_irq();
  158. resample_offset=resOffset;
  159. __enable_irq();
  160. }
  161. void AsyncAudioInputSPDIF3::isr(void)
  162. {
  163. dma.clearInterrupt();
  164. microsLast=micros();
  165. const int32_t *src, *end;
  166. uint32_t daddr = (uint32_t)(dma.TCD->DADDR);
  167. if (daddr < (uint32_t)spdif_rx_buffer + sizeof(spdif_rx_buffer) / 2) {
  168. // DMA is receiving to the first half of the buffer
  169. // need to remove data from the second half
  170. src = (int32_t *)&spdif_rx_buffer[SPDIF_RX_BUFFER_LENGTH/2];
  171. end = (int32_t *)&spdif_rx_buffer[SPDIF_RX_BUFFER_LENGTH];
  172. //if (AsyncAudioInputSPDIF3::update_responsibility) AudioStream::update_all();
  173. } else {
  174. // DMA is receiving to the second half of the buffer
  175. // need to remove data from the first half
  176. src = (int32_t *)&spdif_rx_buffer[0];
  177. end = (int32_t *)&spdif_rx_buffer[SPDIF_RX_BUFFER_LENGTH/2];
  178. }
  179. if (buffer_offset >=resample_offset ||
  180. (buffer_offset + SPDIF_RX_BUFFER_LENGTH/4) < resample_offset) {
  181. #if IMXRT_CACHE_ENABLED >=1
  182. arm_dcache_delete((void*)src, sizeof(spdif_rx_buffer) / 2);
  183. #endif
  184. float *destR = &(bufferR[buffer_offset]);
  185. float *destL = &(bufferL[buffer_offset]);
  186. const float factor= pow(2., 23.)+1;
  187. do {
  188. int32_t n=(*src) & 0x800000 ? (*src)|0xFF800000 : (*src) & 0xFFFFFF;
  189. *destL++ = (float)(n)/factor;
  190. ++src;
  191. n=(*src) & 0x800000 ? (*src)|0xFF800000 : (*src) & 0xFFFFFF;
  192. *destR++ = (float)(n)/factor;
  193. ++src;
  194. } while (src < end);
  195. buffer_offset=(buffer_offset+SPDIF_RX_BUFFER_LENGTH/4)%bufferLength;
  196. }
  197. #ifdef DEBUG_SPDIF_IN
  198. else {
  199. bufferOverflow=true;
  200. }
  201. #endif
  202. }
  203. double AsyncAudioInputSPDIF3::getNewValidInputFrequ(){
  204. //page 2129: FrequMeas[23:0]=FreqMeas_CLK / BUS_CLK * 2^10 * GAIN
  205. if (SPDIF_SRPC & SPDIF_SRPC_LOCK){
  206. const double f=(float)F_BUS_ACTUAL/(1024.*1024.*24.*128.);// bit clock = 128 * sampling frequency
  207. const double freqMeas=(SPDIF_SRFM & 0xFFFFFF)*f;
  208. if (_lastValidInputFrequ != freqMeas){//frequency not stable yet;
  209. _lastValidInputFrequ=freqMeas;
  210. return -1.;
  211. }
  212. return _lastValidInputFrequ;
  213. }
  214. return -1.;
  215. }
  216. double AsyncAudioInputSPDIF3::getBufferedTime() const{
  217. __disable_irq();
  218. double n=_bufferedTime;
  219. __enable_irq();
  220. return n;
  221. }
  222. void AsyncAudioInputSPDIF3::configure(){
  223. __disable_irq();
  224. if(resetResampler){
  225. _resampler.reset();
  226. resetResampler=false;
  227. }
  228. if(!locked){
  229. __enable_irq();
  230. #ifdef DEBUG_SPDIF_IN
  231. Serial.println("lock lost");
  232. #endif
  233. return;
  234. }
  235. #ifdef DEBUG_SPDIF_IN
  236. const bool bOverf=bufferOverflow;
  237. bufferOverflow=false;
  238. #endif
  239. const bool lc=lockChanged;
  240. __enable_irq();
  241. #ifdef DEBUG_SPDIF_IN
  242. if (bOverf){
  243. Serial.print("buffer overflow, buffer offset: ");
  244. Serial.print(buffer_offset);
  245. Serial.print(", resample_offset: ");
  246. Serial.println(resample_offset);
  247. if (!_resampler.initialized()){
  248. Serial.println("_resampler not initialized. ");
  249. }
  250. }
  251. #endif
  252. if (lc || !_resampler.initialized()){
  253. const double inputF=getNewValidInputFrequ(); //returns: -1 ... invalid frequency
  254. if (inputF > 0.){
  255. __disable_irq();
  256. lockChanged=false; //only reset lockChanged if a valid frequency was received (inputFrequ > 0.)
  257. __enable_irq();
  258. //we got a valid sample frequency
  259. const double frequDiff=inputF/_inputFrequency-1.;
  260. if (abs(frequDiff) > 0.01 || !_resampler.initialized()){
  261. //the new sample frequency differs from the last one -> configure the _resampler again
  262. _inputFrequency=inputF;
  263. const int32_t targetLatency=round(_targetLatencyS*inputF);
  264. _targetLatencyS=max(0.001,(noSamplerPerIsr*3./2./_inputFrequency));
  265. __disable_irq();
  266. resample_offset = targetLatency <= buffer_offset ? buffer_offset - targetLatency : bufferLength -(targetLatency-buffer_offset);
  267. __enable_irq();
  268. _resampler.configure(inputF, AUDIO_SAMPLE_RATE_EXACT, _attenuation, _minHalfFilterLength);
  269. #ifdef DEBUG_SPDIF_IN
  270. Serial.print("_maxLatency: ");
  271. Serial.println(_maxLatency);
  272. Serial.print("targetLatency: ");
  273. Serial.println(targetLatency);
  274. Serial.print("relative frequ diff: ");
  275. Serial.println(frequDiff, 8);
  276. Serial.print("configure _resampler with frequency ");
  277. Serial.println(inputF,8);
  278. #endif
  279. }
  280. }
  281. }
  282. }
  283. void AsyncAudioInputSPDIF3::monitorResampleBuffer(){
  284. if(!_resampler.initialized()){
  285. return;
  286. }
  287. __disable_irq();
  288. const double dmaOffset=(micros()-microsLast)*1e-6; //[seconds]
  289. double bTime = resample_offset <= buffer_offset ? (buffer_offset-resample_offset-_resampler.getXPos())/_lastValidInputFrequ+dmaOffset : (bufferLength-resample_offset +buffer_offset-_resampler.getXPos())/_lastValidInputFrequ+dmaOffset; //[seconds]
  290. double diff = bTime- (_blockDuration+ _targetLatencyS); //seconds
  291. biquad_cascade_df2T<double, arm_biquad_cascade_df2T_instance_f32, float>(&_bufferLPFilter, &diff, &diff, 1);
  292. bool settled=_resampler.addToSampleDiff(diff);
  293. if (bTime > _maxLatency || bTime-dmaOffset<= _blockDuration || settled) {
  294. double distance=(_blockDuration+_targetLatencyS-dmaOffset)*_lastValidInputFrequ+_resampler.getXPos();
  295. diff=0.;
  296. if (distance > bufferLength-noSamplerPerIsr){
  297. diff=bufferLength-noSamplerPerIsr-distance;
  298. distance=bufferLength-noSamplerPerIsr;
  299. }
  300. if (distance < 0.){
  301. distance=0.;
  302. diff=- (_blockDuration+ _targetLatencyS);
  303. }
  304. double resample_offsetF=buffer_offset-distance;
  305. resample_offset=(int32_t)floor(resample_offsetF);
  306. _resampler.addToPos(resample_offsetF-resample_offset);
  307. while (resample_offset<0){
  308. resample_offset+=bufferLength;
  309. }
  310. //int32_t b_offset=buffer_offset;
  311. #ifdef DEBUG_SPDIF_IN
  312. double bTimeFixed = resample_offset <= buffer_offset ? (buffer_offset-resample_offset-_resampler.getXPos())/_lastValidInputFrequ+dmaOffset : (bufferLength-resample_offset +buffer_offset-_resampler.getXPos())/_lastValidInputFrequ+dmaOffset; //[seconds]
  313. #endif
  314. __enable_irq();
  315. #ifdef DEBUG_SPDIF_IN
  316. // Serial.print("settled: ");
  317. // Serial.println(settled);
  318. Serial.print("bTime: ");
  319. Serial.print(bTime*1e6,3);
  320. Serial.print("_maxLatency: ");
  321. Serial.println(_maxLatency*1e6,3);
  322. Serial.print("bTime-dmaOffset: ");
  323. Serial.print((bTime-dmaOffset)*1e6,3);
  324. Serial.print(", _blockDuration: ");
  325. Serial.print(_blockDuration*1e6,3);
  326. Serial.print("bTimeFixed: ");
  327. Serial.print(bTimeFixed*1e6,3);
  328. #endif
  329. preload(&_bufferLPFilter, diff);
  330. _resampler.fixStep();
  331. }
  332. else {
  333. __enable_irq();
  334. }
  335. _bufferedTime=_targetLatencyS+diff;
  336. }
  337. void AsyncAudioInputSPDIF3::update(void)
  338. {
  339. configure();
  340. monitorResampleBuffer(); //important first call 'monitorResampleBuffer' then 'resample'
  341. audio_block_t *block_left =allocate();
  342. audio_block_t *block_right =nullptr;
  343. if (block_left!= nullptr) {
  344. block_right = allocate();
  345. if (block_right == nullptr) {
  346. release(block_left);
  347. block_left = nullptr;
  348. }
  349. }
  350. if (block_left && block_right) {
  351. int32_t block_offset;
  352. resample(block_left->data, block_right->data,block_offset);
  353. if(block_offset < AUDIO_BLOCK_SAMPLES){
  354. memset(block_left->data+block_offset, 0, (AUDIO_BLOCK_SAMPLES-block_offset)*sizeof(int16_t));
  355. memset(block_right->data+block_offset, 0, (AUDIO_BLOCK_SAMPLES-block_offset)*sizeof(int16_t));
  356. #ifdef DEBUG_SPDIF_IN
  357. Serial.print("filled only ");
  358. Serial.print(block_offset);
  359. Serial.println(" samples.");
  360. #endif
  361. }
  362. transmit(block_left, 0);
  363. release(block_left);
  364. block_left=nullptr;
  365. transmit(block_right, 1);
  366. release(block_right);
  367. block_right=nullptr;
  368. }
  369. #ifdef DEBUG_SPDIF_IN
  370. else {
  371. Serial.println("Not enough blocks available. Too few audio memory?");
  372. }
  373. #endif
  374. }
  375. double AsyncAudioInputSPDIF3::getInputFrequency() const{
  376. __disable_irq();
  377. double f=_lastValidInputFrequ;
  378. __enable_irq();
  379. return f;
  380. }
  381. double AsyncAudioInputSPDIF3::getTargetLantency() const {
  382. __disable_irq();
  383. double l=_targetLatencyS;
  384. __enable_irq();
  385. return l ;
  386. }
  387. void AsyncAudioInputSPDIF3::config_spdifIn(){
  388. //CCM Clock Gating Register 5, imxrt1060_rev1.pdf page 1145
  389. CCM_CCGR5 |=CCM_CCGR5_SPDIF(CCM_CCGR_ON); //turn spdif clock on - necessary for receiver!
  390. SPDIF_SCR |=SPDIF_SCR_RXFIFO_OFF_ON; //turn receive fifo off 1->off, 0->on
  391. SPDIF_SCR&=~(SPDIF_SCR_RXFIFO_CTR); //reset rx fifo control: normal opertation
  392. SPDIF_SCR&=~(SPDIF_SCR_RXFIFOFULL_SEL(3)); //reset rx full select
  393. SPDIF_SCR|=SPDIF_SCR_RXFIFOFULL_SEL(2); //full interrupt if at least 8 sample in Rx left and right FIFOs
  394. SPDIF_SCR|=SPDIF_SCR_RXAUTOSYNC; //Rx FIFO auto sync on
  395. SPDIF_SCR&=(~SPDIF_SCR_USRC_SEL(3)); //No embedded U channel
  396. CORE_PIN15_CONFIG = 3; //pin 15 set to alt3 -> spdif input
  397. /// from eval board sample code
  398. // IOMUXC_SetPinConfig(
  399. // IOMUXC_GPIO_AD_B1_03_SPDIF_IN, /* GPIO_AD_B1_03 PAD functional properties : */
  400. // 0x10B0u); /* Slew Rate Field: Slow Slew Rate
  401. // Drive Strength Field: R0/6
  402. // Speed Field: medium(100MHz)
  403. // Open Drain Enable Field: Open Drain Disabled
  404. // Pull / Keep Enable Field: Pull/Keeper Enabled
  405. // Pull / Keep Select Field: Keeper
  406. // Pull Up / Down Config. Field: 100K Ohm Pull Down
  407. // Hyst. Enable Field: Hysteresis Disabled */
  408. CORE_PIN15_PADCONFIG=0x10B0;
  409. SPDIF_SCR &=(~SPDIF_SCR_RXFIFO_OFF_ON); //receive fifo is turned on again
  410. SPDIF_SRPC &= ~SPDIF_SRPC_CLKSRC_SEL(15); //reset clock selection page 2136
  411. //SPDIF_SRPC |=SPDIF_SRPC_CLKSRC_SEL(6); //if (DPLL Locked) SPDIF_RxClk else tx_clk (SPDIF0_CLK_ROOT)
  412. //page 2129: FrequMeas[23:0]=FreqMeas_CLK / BUS_CLK * 2^10 * GAIN
  413. SPDIF_SRPC &=~SPDIF_SRPC_GAINSEL(7); //reset gain select 0 -> gain = 24*2^10
  414. //SPDIF_SRPC |= SPDIF_SRPC_GAINSEL(3); //gain select: 8*2^10
  415. //==============================================
  416. //interrupts
  417. SPDIF_SIE |= SPDIF_SIE_LOCK; //enable spdif receiver lock interrupt
  418. SPDIF_SIE |=SPDIF_SIE_LOCKLOSS;
  419. lockChanged=true;
  420. attachInterruptVector(IRQ_SPDIF, spdif_interrupt);
  421. NVIC_SET_PRIORITY(IRQ_SPDIF, 208); // 255 = lowest priority, 208 = priority of update
  422. NVIC_ENABLE_IRQ(IRQ_SPDIF);
  423. SPDIF_SIC |= SPDIF_SIC_LOCK; //clear SPDIF_SIC_LOCK interrupt
  424. SPDIF_SIC |= SPDIF_SIC_LOCKLOSS;//clear SPDIF_SIC_LOCKLOSS interrupt
  425. locked=(SPDIF_SRPC & SPDIF_SRPC_LOCK);
  426. }
  427. #endif