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.

async_input_spdif3.cpp 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  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. FLASHMEM
  59. AsyncAudioInputSPDIF3::AsyncAudioInputSPDIF3(bool dither, bool noiseshaping,float attenuation, int32_t minHalfFilterLength, int32_t maxHalfFilterLength):
  60. AudioStream(0, NULL),
  61. _resampler(attenuation, minHalfFilterLength, maxHalfFilterLength)
  62. {
  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. FLASHMEM
  71. void AsyncAudioInputSPDIF3::begin()
  72. {
  73. AudioOutputSPDIF3::config_spdif3();
  74. dma.begin(true); // Allocate the DMA channel first
  75. const uint32_t noByteMinorLoop=2*4;
  76. dma.TCD->SOFF = 4;
  77. dma.TCD->ATTR = DMA_TCD_ATTR_SSIZE(2) | DMA_TCD_ATTR_DSIZE(2);
  78. dma.TCD->NBYTES_MLNO = DMA_TCD_NBYTES_MLOFFYES_NBYTES(noByteMinorLoop) | DMA_TCD_NBYTES_SMLOE |
  79. DMA_TCD_NBYTES_MLOFFYES_MLOFF(-8);
  80. dma.TCD->SLAST = -8;
  81. dma.TCD->DOFF = 4;
  82. dma.TCD->CITER_ELINKNO = sizeof(spdif_rx_buffer) / noByteMinorLoop;
  83. dma.TCD->DLASTSGA = -sizeof(spdif_rx_buffer);
  84. dma.TCD->BITER_ELINKNO = sizeof(spdif_rx_buffer) / noByteMinorLoop;
  85. dma.TCD->CSR = DMA_TCD_CSR_INTHALF | DMA_TCD_CSR_INTMAJOR;
  86. dma.TCD->SADDR = (void *)((uint32_t)&SPDIF_SRL);
  87. dma.TCD->DADDR = spdif_rx_buffer;
  88. dma.triggerAtHardwareEvent(DMAMUX_SOURCE_SPDIF_RX);
  89. //SPDIF_SCR |=SPDIF_SCR_DMA_RX_EN; //DMA Receive Request Enable
  90. dma.enable();
  91. dma.attachInterrupt(isr);
  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. SPDIF_SCR &=(~SPDIF_SCR_RXFIFO_OFF_ON); //receive fifo is turned on again
  100. SPDIF_SRCD = 0;
  101. SPDIF_SCR |= SPDIF_SCR_DMA_RX_EN;
  102. CORE_PIN15_CONFIG = 3;
  103. IOMUXC_SPDIF_IN_SELECT_INPUT = 0; // GPIO_AD_B1_03_ALT3
  104. }
  105. bool AsyncAudioInputSPDIF3::isLocked() {
  106. return (SPDIF_SRPC & SPDIF_SRPC_LOCK) == SPDIF_SRPC_LOCK;
  107. }
  108. void AsyncAudioInputSPDIF3::resample(int16_t* data_left, int16_t* data_right, int32_t& block_offset){
  109. block_offset=0;
  110. if(!_resampler.initialized() || !isLocked()){
  111. return;
  112. }
  113. int32_t bOffset=buffer_offset;
  114. int32_t resOffset=resample_offset;
  115. uint16_t inputBufferStop = bOffset >= resOffset ? bOffset-resOffset : bufferLength-resOffset;
  116. if (inputBufferStop==0){
  117. return;
  118. }
  119. uint16_t processedLength;
  120. uint16_t outputCount=0;
  121. uint16_t outputLength=AUDIO_BLOCK_SAMPLES;
  122. float resampledBufferL[AUDIO_BLOCK_SAMPLES];
  123. float resampledBufferR[AUDIO_BLOCK_SAMPLES];
  124. _resampler.resample(&bufferL[resOffset],&bufferR[resOffset], inputBufferStop, processedLength, resampledBufferL, resampledBufferR, outputLength, outputCount);
  125. resOffset=(resOffset+processedLength)%bufferLength;
  126. block_offset=outputCount;
  127. if (bOffset > resOffset && block_offset< AUDIO_BLOCK_SAMPLES){
  128. inputBufferStop= bOffset-resOffset;
  129. outputLength=AUDIO_BLOCK_SAMPLES-block_offset;
  130. _resampler.resample(&bufferL[resOffset],&bufferR[resOffset], inputBufferStop, processedLength, resampledBufferL+block_offset, resampledBufferR+block_offset, outputLength, outputCount);
  131. resOffset=(resOffset+processedLength)%bufferLength;
  132. block_offset+=outputCount;
  133. }
  134. quantizer[0]->quantize(resampledBufferL, data_left, block_offset);
  135. quantizer[1]->quantize(resampledBufferR, data_right, block_offset);
  136. __disable_irq();
  137. resample_offset=resOffset;
  138. __enable_irq();
  139. }
  140. void AsyncAudioInputSPDIF3::isr(void)
  141. {
  142. dma.clearInterrupt();
  143. microsLast=micros();
  144. const int32_t *src, *end;
  145. uint32_t daddr = (uint32_t)(dma.TCD->DADDR);
  146. if (daddr < (uint32_t)spdif_rx_buffer + sizeof(spdif_rx_buffer) / 2) {
  147. // DMA is receiving to the first half of the buffer
  148. // need to remove data from the second half
  149. src = (int32_t *)&spdif_rx_buffer[SPDIF_RX_BUFFER_LENGTH/2];
  150. end = (int32_t *)&spdif_rx_buffer[SPDIF_RX_BUFFER_LENGTH];
  151. //if (AsyncAudioInputSPDIF3::update_responsibility) AudioStream::update_all();
  152. } else {
  153. // DMA is receiving to the second half of the buffer
  154. // need to remove data from the first half
  155. src = (int32_t *)&spdif_rx_buffer[0];
  156. end = (int32_t *)&spdif_rx_buffer[SPDIF_RX_BUFFER_LENGTH/2];
  157. }
  158. if (buffer_offset >=resample_offset ||
  159. (buffer_offset + SPDIF_RX_BUFFER_LENGTH/4) < resample_offset) {
  160. #if IMXRT_CACHE_ENABLED >=1
  161. arm_dcache_delete((void*)src, sizeof(spdif_rx_buffer) / 2);
  162. #endif
  163. float *destR = &(bufferR[buffer_offset]);
  164. float *destL = &(bufferL[buffer_offset]);
  165. do {
  166. int32_t n=(*src) & 0x800000 ? (*src)|0xFF800000 : (*src) & 0xFFFFFF;
  167. *destL++ = (float)(n)*toFloatAudio;
  168. ++src;
  169. n=(*src) & 0x800000 ? (*src)|0xFF800000 : (*src) & 0xFFFFFF;
  170. *destR++ = (float)(n)*toFloatAudio;
  171. ++src;
  172. } while (src < end);
  173. buffer_offset=(buffer_offset+SPDIF_RX_BUFFER_LENGTH/4)%bufferLength;
  174. }
  175. #ifdef DEBUG_SPDIF_IN
  176. else {
  177. bufferOverflow=true;
  178. }
  179. #endif
  180. }
  181. double AsyncAudioInputSPDIF3::getNewValidInputFrequ(){
  182. //page 2129: FrequMeas[23:0]=FreqMeas_CLK / BUS_CLK * 2^10 * GAIN
  183. if (isLocked()){
  184. const double f=(float)F_BUS_ACTUAL/(1024.*1024.*AudioOutputSPDIF3::dpll_Gain()*128.);// bit clock = 128 * sampling frequency
  185. const double freqMeas=(SPDIF_SRFM & 0xFFFFFF)*f;
  186. if (_lastValidInputFrequ != freqMeas){//frequency not stable yet;
  187. _lastValidInputFrequ=freqMeas;
  188. return -1.;
  189. }
  190. return _lastValidInputFrequ;
  191. }
  192. return -1.;
  193. }
  194. double AsyncAudioInputSPDIF3::getBufferedTime() const{
  195. __disable_irq();
  196. double n=_bufferedTime;
  197. __enable_irq();
  198. return n;
  199. }
  200. void AsyncAudioInputSPDIF3::configure(){
  201. if(!isLocked()){
  202. _resampler.reset();
  203. return;
  204. }
  205. #ifdef DEBUG_SPDIF_IN
  206. const bool bOverf=bufferOverflow;
  207. bufferOverflow=false;
  208. if (bOverf){
  209. Serial.print("buffer overflow, buffer offset: ");
  210. Serial.print(buffer_offset);
  211. Serial.print(", resample_offset: ");
  212. Serial.println(resample_offset);
  213. if (!_resampler.initialized()){
  214. Serial.println("_resampler not initialized. ");
  215. }
  216. }
  217. #endif
  218. const double inputF=getNewValidInputFrequ(); //returns: -1 ... invalid frequency
  219. if (inputF > 0.){
  220. //we got a valid sample frequency
  221. const double frequDiff=inputF/_inputFrequency-1.;
  222. if (abs(frequDiff) > 0.01 || !_resampler.initialized()){
  223. //the new sample frequency differs from the last one -> configure the _resampler again
  224. _inputFrequency=inputF;
  225. _targetLatencyS=max(0.001,(noSamplerPerIsr*3./2./_inputFrequency));
  226. _maxLatency=max(2.*_blockDuration, 2*noSamplerPerIsr/_inputFrequency);
  227. const int32_t targetLatency=round(_targetLatencyS*inputF);
  228. __disable_irq();
  229. resample_offset = targetLatency <= buffer_offset ? buffer_offset - targetLatency : bufferLength -(targetLatency-buffer_offset);
  230. __enable_irq();
  231. _resampler.configure(inputF, AUDIO_SAMPLE_RATE_EXACT);
  232. #ifdef DEBUG_SPDIF_IN
  233. Serial.print("_maxLatency: ");
  234. Serial.println(_maxLatency);
  235. Serial.print("targetLatency: ");
  236. Serial.println(targetLatency);
  237. Serial.print("relative frequ diff: ");
  238. Serial.println(frequDiff, 8);
  239. Serial.print("configure _resampler with frequency ");
  240. Serial.println(inputF,8);
  241. #endif
  242. }
  243. }
  244. }
  245. void AsyncAudioInputSPDIF3::monitorResampleBuffer(){
  246. if(!_resampler.initialized()){
  247. return;
  248. }
  249. __disable_irq();
  250. const double dmaOffset=(micros()-microsLast)*1e-6; //[seconds]
  251. double bTime = resample_offset <= buffer_offset ? (buffer_offset-resample_offset-_resampler.getXPos())/_lastValidInputFrequ+dmaOffset : (bufferLength-resample_offset +buffer_offset-_resampler.getXPos())/_lastValidInputFrequ+dmaOffset; //[seconds]
  252. double diff = bTime- (_blockDuration+ _targetLatencyS); //seconds
  253. biquad_cascade_df2T<double, arm_biquad_cascade_df2T_instance_f32, float>(&_bufferLPFilter, &diff, &diff, 1);
  254. bool settled=_resampler.addToSampleDiff(diff);
  255. if (bTime > _maxLatency || bTime-dmaOffset<= _blockDuration || settled) {
  256. double distance=(_blockDuration+_targetLatencyS-dmaOffset)*_lastValidInputFrequ+_resampler.getXPos();
  257. diff=0.;
  258. if (distance > bufferLength-noSamplerPerIsr){
  259. diff=bufferLength-noSamplerPerIsr-distance;
  260. distance=bufferLength-noSamplerPerIsr;
  261. }
  262. if (distance < 0.){
  263. distance=0.;
  264. diff=- (_blockDuration+ _targetLatencyS);
  265. }
  266. double resample_offsetF=buffer_offset-distance;
  267. resample_offset=(int32_t)floor(resample_offsetF);
  268. _resampler.addToPos(resample_offsetF-resample_offset);
  269. while (resample_offset<0){
  270. resample_offset+=bufferLength;
  271. }
  272. #ifdef DEBUG_SPDIF_IN
  273. double bTimeFixed = resample_offset <= buffer_offset ? (buffer_offset-resample_offset-_resampler.getXPos())/_lastValidInputFrequ+dmaOffset : (bufferLength-resample_offset +buffer_offset-_resampler.getXPos())/_lastValidInputFrequ+dmaOffset; //[seconds]
  274. #endif
  275. __enable_irq();
  276. #ifdef DEBUG_SPDIF_IN
  277. Serial.print("settled: ");
  278. Serial.println(settled);
  279. Serial.print("bTime: ");
  280. Serial.println(bTime*1e6,3);
  281. Serial.print("_maxLatency: ");
  282. Serial.println(_maxLatency*1e6,3);
  283. Serial.print("bTime-dmaOffset: ");
  284. Serial.println((bTime-dmaOffset)*1e6,3);
  285. Serial.print(", _blockDuration: ");
  286. Serial.println(_blockDuration*1e6,3);
  287. Serial.print("bTimeFixed: ");
  288. Serial.println(bTimeFixed*1e6,3);
  289. #endif
  290. preload(&_bufferLPFilter, diff);
  291. _resampler.fixStep();
  292. }
  293. else {
  294. __enable_irq();
  295. }
  296. _bufferedTime=_targetLatencyS+diff;
  297. }
  298. void AsyncAudioInputSPDIF3::update(void)
  299. {
  300. configure();
  301. monitorResampleBuffer(); //important first call 'monitorResampleBuffer' then 'resample'
  302. audio_block_t *block_left =allocate();
  303. audio_block_t *block_right =nullptr;
  304. if (block_left!= nullptr) {
  305. block_right = allocate();
  306. if (block_right == nullptr) {
  307. release(block_left);
  308. block_left = nullptr;
  309. }
  310. }
  311. if (block_left && block_right) {
  312. int32_t block_offset;
  313. resample(block_left->data, block_right->data,block_offset);
  314. if(block_offset < AUDIO_BLOCK_SAMPLES){
  315. memset(block_left->data+block_offset, 0, (AUDIO_BLOCK_SAMPLES-block_offset)*sizeof(int16_t));
  316. memset(block_right->data+block_offset, 0, (AUDIO_BLOCK_SAMPLES-block_offset)*sizeof(int16_t));
  317. #ifdef DEBUG_SPDIF_IN
  318. Serial.print("filled only ");
  319. Serial.print(block_offset);
  320. Serial.println(" samples.");
  321. #endif
  322. }
  323. transmit(block_left, 0);
  324. release(block_left);
  325. block_left=nullptr;
  326. transmit(block_right, 1);
  327. release(block_right);
  328. block_right=nullptr;
  329. }
  330. #ifdef DEBUG_SPDIF_IN
  331. else {
  332. Serial.println("Not enough blocks available. Too few audio memory?");
  333. }
  334. #endif
  335. }
  336. double AsyncAudioInputSPDIF3::getInputFrequency() const{
  337. __disable_irq();
  338. double f=_lastValidInputFrequ;
  339. __enable_irq();
  340. return isLocked() ? f : 0.;
  341. }
  342. double AsyncAudioInputSPDIF3::getTargetLantency() const {
  343. __disable_irq();
  344. double l=_targetLatencyS;
  345. __enable_irq();
  346. return l ;
  347. }
  348. double AsyncAudioInputSPDIF3::getAttenuation() const{
  349. return _resampler.getAttenuation();
  350. }
  351. int32_t AsyncAudioInputSPDIF3::getHalfFilterLength() const{
  352. return _resampler.getHalfFilterLength();
  353. }
  354. #endif