Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

387 Zeilen
13KB

  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 "output_spdif3.h"
  32. #include "biquad.h"
  33. #include <utility/imxrt_hw.h>
  34. //Parameters
  35. namespace {
  36. #define SPDIF_RX_BUFFER_LENGTH AUDIO_BLOCK_SAMPLES
  37. const int32_t bufferLength=8*AUDIO_BLOCK_SAMPLES;
  38. const uint16_t noSamplerPerIsr=SPDIF_RX_BUFFER_LENGTH/4;
  39. const float toFloatAudio= 1.f/pow(2., 23.);
  40. }
  41. #ifdef DEBUG_SPDIF_IN
  42. volatile bool AsyncAudioInputSPDIF3::bufferOverflow=false;
  43. #endif
  44. volatile uint32_t AsyncAudioInputSPDIF3::microsLast;
  45. DMAMEM __attribute__((aligned(32)))
  46. static int32_t spdif_rx_buffer[SPDIF_RX_BUFFER_LENGTH];
  47. static float bufferR[bufferLength];
  48. static float bufferL[bufferLength];
  49. 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
  50. int32_t AsyncAudioInputSPDIF3::resample_offset = 0; // read/written by resample/ read in spdif input isr -> no protection needed?
  51. DMAChannel AsyncAudioInputSPDIF3::dma(false);
  52. AsyncAudioInputSPDIF3::~AsyncAudioInputSPDIF3(){
  53. delete [] _bufferLPFilter.pCoeffs;
  54. delete [] _bufferLPFilter.pState;
  55. delete quantizer[0];
  56. delete quantizer[1];
  57. }
  58. PROGMEM
  59. AsyncAudioInputSPDIF3::AsyncAudioInputSPDIF3(bool dither, bool noiseshaping,float attenuation, int32_t minHalfFilterLength) : AudioStream(0, NULL) {
  60. _attenuation=attenuation;
  61. _minHalfFilterLength=minHalfFilterLength;
  62. const float factor = powf(2, 15)-1.f; // to 16 bit audio
  63. quantizer[0]=new Quantizer(AUDIO_SAMPLE_RATE_EXACT);
  64. quantizer[0]->configure(noiseshaping, dither, factor);
  65. quantizer[1]=new Quantizer(AUDIO_SAMPLE_RATE_EXACT);
  66. quantizer[1]->configure(noiseshaping, dither, factor);
  67. begin();
  68. }
  69. PROGMEM
  70. void AsyncAudioInputSPDIF3::begin()
  71. {
  72. AudioOutputSPDIF3::config_spdif3();
  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. #ifdef DEBUG_SPDIF_IN
  92. while (!Serial);
  93. #endif
  94. _bufferLPFilter.pCoeffs=new float[5];
  95. _bufferLPFilter.numStages=1;
  96. _bufferLPFilter.pState=new float[2];
  97. getCoefficients(_bufferLPFilter.pCoeffs, BiquadType::LOW_PASS, 0., 5., AUDIO_SAMPLE_RATE_EXACT/AUDIO_BLOCK_SAMPLES, 0.5);
  98. SPDIF_SCR &=(~SPDIF_SCR_RXFIFO_OFF_ON); //receive fifo is turned on again
  99. SPDIF_SRCD = 0;
  100. SPDIF_SCR |= SPDIF_SCR_DMA_RX_EN;
  101. CORE_PIN15_CONFIG = 3;
  102. IOMUXC_SPDIF_IN_SELECT_INPUT = 0; // GPIO_AD_B1_03_ALT3
  103. }
  104. bool AsyncAudioInputSPDIF3::isLocked() {
  105. return (SPDIF_SRPC & SPDIF_SRPC_LOCK) == SPDIF_SRPC_LOCK;
  106. }
  107. void AsyncAudioInputSPDIF3::resample(int16_t* data_left, int16_t* data_right, int32_t& block_offset){
  108. block_offset=0;
  109. if(!_resampler.initialized() || !isLocked()){
  110. return;
  111. }
  112. int32_t bOffset=buffer_offset;
  113. int32_t resOffset=resample_offset;
  114. uint16_t inputBufferStop = bOffset >= resOffset ? bOffset-resOffset : bufferLength-resOffset;
  115. if (inputBufferStop==0){
  116. return;
  117. }
  118. uint16_t processedLength;
  119. uint16_t outputCount=0;
  120. uint16_t outputLength=AUDIO_BLOCK_SAMPLES;
  121. float resampledBufferL[AUDIO_BLOCK_SAMPLES];
  122. float resampledBufferR[AUDIO_BLOCK_SAMPLES];
  123. _resampler.resample(&bufferL[resOffset],&bufferR[resOffset], inputBufferStop, processedLength, resampledBufferL, resampledBufferR, outputLength, outputCount);
  124. resOffset=(resOffset+processedLength)%bufferLength;
  125. block_offset=outputCount;
  126. if (bOffset > resOffset && block_offset< AUDIO_BLOCK_SAMPLES){
  127. inputBufferStop= bOffset-resOffset;
  128. outputLength=AUDIO_BLOCK_SAMPLES-block_offset;
  129. _resampler.resample(&bufferL[resOffset],&bufferR[resOffset], inputBufferStop, processedLength, resampledBufferL+block_offset, resampledBufferR+block_offset, outputLength, outputCount);
  130. resOffset=(resOffset+processedLength)%bufferLength;
  131. block_offset+=outputCount;
  132. }
  133. quantizer[0]->quantize(resampledBufferL, data_left, block_offset);
  134. quantizer[1]->quantize(resampledBufferR, data_right, block_offset);
  135. __disable_irq();
  136. resample_offset=resOffset;
  137. __enable_irq();
  138. }
  139. void AsyncAudioInputSPDIF3::isr(void)
  140. {
  141. dma.clearInterrupt();
  142. microsLast=micros();
  143. const int32_t *src, *end;
  144. uint32_t daddr = (uint32_t)(dma.TCD->DADDR);
  145. if (daddr < (uint32_t)spdif_rx_buffer + sizeof(spdif_rx_buffer) / 2) {
  146. // DMA is receiving to the first half of the buffer
  147. // need to remove data from the second half
  148. src = (int32_t *)&spdif_rx_buffer[SPDIF_RX_BUFFER_LENGTH/2];
  149. end = (int32_t *)&spdif_rx_buffer[SPDIF_RX_BUFFER_LENGTH];
  150. //if (AsyncAudioInputSPDIF3::update_responsibility) AudioStream::update_all();
  151. } else {
  152. // DMA is receiving to the second half of the buffer
  153. // need to remove data from the first half
  154. src = (int32_t *)&spdif_rx_buffer[0];
  155. end = (int32_t *)&spdif_rx_buffer[SPDIF_RX_BUFFER_LENGTH/2];
  156. }
  157. if (buffer_offset >=resample_offset ||
  158. (buffer_offset + SPDIF_RX_BUFFER_LENGTH/4) < resample_offset) {
  159. #if IMXRT_CACHE_ENABLED >=1
  160. arm_dcache_delete((void*)src, sizeof(spdif_rx_buffer) / 2);
  161. #endif
  162. float *destR = &(bufferR[buffer_offset]);
  163. float *destL = &(bufferL[buffer_offset]);
  164. do {
  165. int32_t n=(*src) & 0x800000 ? (*src)|0xFF800000 : (*src) & 0xFFFFFF;
  166. *destL++ = (float)(n)*toFloatAudio;
  167. ++src;
  168. n=(*src) & 0x800000 ? (*src)|0xFF800000 : (*src) & 0xFFFFFF;
  169. *destR++ = (float)(n)*toFloatAudio;
  170. ++src;
  171. } while (src < end);
  172. buffer_offset=(buffer_offset+SPDIF_RX_BUFFER_LENGTH/4)%bufferLength;
  173. }
  174. #ifdef DEBUG_SPDIF_IN
  175. else {
  176. bufferOverflow=true;
  177. }
  178. #endif
  179. }
  180. double AsyncAudioInputSPDIF3::getNewValidInputFrequ(){
  181. //page 2129: FrequMeas[23:0]=FreqMeas_CLK / BUS_CLK * 2^10 * GAIN
  182. if (isLocked()){
  183. const double f=(float)F_BUS_ACTUAL/(1024.*1024.*AudioOutputSPDIF3::dpll_Gain()*128.);// bit clock = 128 * sampling frequency
  184. const double freqMeas=(SPDIF_SRFM & 0xFFFFFF)*f;
  185. if (_lastValidInputFrequ != freqMeas){//frequency not stable yet;
  186. _lastValidInputFrequ=freqMeas;
  187. return -1.;
  188. }
  189. return _lastValidInputFrequ;
  190. }
  191. return -1.;
  192. }
  193. double AsyncAudioInputSPDIF3::getBufferedTime() const{
  194. __disable_irq();
  195. double n=_bufferedTime;
  196. __enable_irq();
  197. return n;
  198. }
  199. void AsyncAudioInputSPDIF3::configure(){
  200. if(!isLocked()){
  201. _resampler.reset();
  202. return;
  203. }
  204. #ifdef DEBUG_SPDIF_IN
  205. const bool bOverf=bufferOverflow;
  206. bufferOverflow=false;
  207. if (bOverf){
  208. Serial.print("buffer overflow, buffer offset: ");
  209. Serial.print(buffer_offset);
  210. Serial.print(", resample_offset: ");
  211. Serial.println(resample_offset);
  212. if (!_resampler.initialized()){
  213. Serial.println("_resampler not initialized. ");
  214. }
  215. }
  216. #endif
  217. const double inputF=getNewValidInputFrequ(); //returns: -1 ... invalid frequency
  218. if (inputF > 0.){
  219. //we got a valid sample frequency
  220. const double frequDiff=inputF/_inputFrequency-1.;
  221. if (abs(frequDiff) > 0.01 || !_resampler.initialized()){
  222. //the new sample frequency differs from the last one -> configure the _resampler again
  223. _inputFrequency=inputF;
  224. _targetLatencyS=max(0.001,(noSamplerPerIsr*3./2./_inputFrequency));
  225. _maxLatency=max(2.*_blockDuration, 2*noSamplerPerIsr/_inputFrequency);
  226. const int32_t targetLatency=round(_targetLatencyS*inputF);
  227. __disable_irq();
  228. resample_offset = targetLatency <= buffer_offset ? buffer_offset - targetLatency : bufferLength -(targetLatency-buffer_offset);
  229. __enable_irq();
  230. _resampler.configure(inputF, AUDIO_SAMPLE_RATE_EXACT, _attenuation, _minHalfFilterLength);
  231. #ifdef DEBUG_SPDIF_IN
  232. Serial.print("_maxLatency: ");
  233. Serial.println(_maxLatency);
  234. Serial.print("targetLatency: ");
  235. Serial.println(targetLatency);
  236. Serial.print("relative frequ diff: ");
  237. Serial.println(frequDiff, 8);
  238. Serial.print("configure _resampler with frequency ");
  239. Serial.println(inputF,8);
  240. #endif
  241. }
  242. }
  243. }
  244. void AsyncAudioInputSPDIF3::monitorResampleBuffer(){
  245. if(!_resampler.initialized()){
  246. return;
  247. }
  248. __disable_irq();
  249. const double dmaOffset=(micros()-microsLast)*1e-6; //[seconds]
  250. double bTime = resample_offset <= buffer_offset ? (buffer_offset-resample_offset-_resampler.getXPos())/_lastValidInputFrequ+dmaOffset : (bufferLength-resample_offset +buffer_offset-_resampler.getXPos())/_lastValidInputFrequ+dmaOffset; //[seconds]
  251. double diff = bTime- (_blockDuration+ _targetLatencyS); //seconds
  252. biquad_cascade_df2T<double, arm_biquad_cascade_df2T_instance_f32, float>(&_bufferLPFilter, &diff, &diff, 1);
  253. bool settled=_resampler.addToSampleDiff(diff);
  254. if (bTime > _maxLatency || bTime-dmaOffset<= _blockDuration || settled) {
  255. double distance=(_blockDuration+_targetLatencyS-dmaOffset)*_lastValidInputFrequ+_resampler.getXPos();
  256. diff=0.;
  257. if (distance > bufferLength-noSamplerPerIsr){
  258. diff=bufferLength-noSamplerPerIsr-distance;
  259. distance=bufferLength-noSamplerPerIsr;
  260. }
  261. if (distance < 0.){
  262. distance=0.;
  263. diff=- (_blockDuration+ _targetLatencyS);
  264. }
  265. double resample_offsetF=buffer_offset-distance;
  266. resample_offset=(int32_t)floor(resample_offsetF);
  267. _resampler.addToPos(resample_offsetF-resample_offset);
  268. while (resample_offset<0){
  269. resample_offset+=bufferLength;
  270. }
  271. #ifdef DEBUG_SPDIF_IN
  272. double bTimeFixed = resample_offset <= buffer_offset ? (buffer_offset-resample_offset-_resampler.getXPos())/_lastValidInputFrequ+dmaOffset : (bufferLength-resample_offset +buffer_offset-_resampler.getXPos())/_lastValidInputFrequ+dmaOffset; //[seconds]
  273. #endif
  274. __enable_irq();
  275. #ifdef DEBUG_SPDIF_IN
  276. Serial.print("settled: ");
  277. Serial.println(settled);
  278. Serial.print("bTime: ");
  279. Serial.println(bTime*1e6,3);
  280. Serial.print("_maxLatency: ");
  281. Serial.println(_maxLatency*1e6,3);
  282. Serial.print("bTime-dmaOffset: ");
  283. Serial.println((bTime-dmaOffset)*1e6,3);
  284. Serial.print(", _blockDuration: ");
  285. Serial.println(_blockDuration*1e6,3);
  286. Serial.print("bTimeFixed: ");
  287. Serial.println(bTimeFixed*1e6,3);
  288. #endif
  289. preload(&_bufferLPFilter, diff);
  290. _resampler.fixStep();
  291. }
  292. else {
  293. __enable_irq();
  294. }
  295. _bufferedTime=_targetLatencyS+diff;
  296. }
  297. void AsyncAudioInputSPDIF3::update(void)
  298. {
  299. configure();
  300. monitorResampleBuffer(); //important first call 'monitorResampleBuffer' then 'resample'
  301. audio_block_t *block_left =allocate();
  302. audio_block_t *block_right =nullptr;
  303. if (block_left!= nullptr) {
  304. block_right = allocate();
  305. if (block_right == nullptr) {
  306. release(block_left);
  307. block_left = nullptr;
  308. }
  309. }
  310. if (block_left && block_right) {
  311. int32_t block_offset;
  312. resample(block_left->data, block_right->data,block_offset);
  313. if(block_offset < AUDIO_BLOCK_SAMPLES){
  314. memset(block_left->data+block_offset, 0, (AUDIO_BLOCK_SAMPLES-block_offset)*sizeof(int16_t));
  315. memset(block_right->data+block_offset, 0, (AUDIO_BLOCK_SAMPLES-block_offset)*sizeof(int16_t));
  316. #ifdef DEBUG_SPDIF_IN
  317. Serial.print("filled only ");
  318. Serial.print(block_offset);
  319. Serial.println(" samples.");
  320. #endif
  321. }
  322. transmit(block_left, 0);
  323. release(block_left);
  324. block_left=nullptr;
  325. transmit(block_right, 1);
  326. release(block_right);
  327. block_right=nullptr;
  328. }
  329. #ifdef DEBUG_SPDIF_IN
  330. else {
  331. Serial.println("Not enough blocks available. Too few audio memory?");
  332. }
  333. #endif
  334. }
  335. double AsyncAudioInputSPDIF3::getInputFrequency() const{
  336. __disable_irq();
  337. double f=_lastValidInputFrequ;
  338. __enable_irq();
  339. return isLocked() ? f : 0.;
  340. }
  341. double AsyncAudioInputSPDIF3::getTargetLantency() const {
  342. __disable_irq();
  343. double l=_targetLatencyS;
  344. __enable_irq();
  345. return l ;
  346. }
  347. double AsyncAudioInputSPDIF3::getAttenuation() const{
  348. return _resampler.getAttenuation();
  349. }
  350. int32_t AsyncAudioInputSPDIF3::getHalfFilterLength() const{
  351. return _resampler.getHalfFilterLength();
  352. }
  353. #endif