PlatformIO package of the Teensy core framework compatible with GCC 10 & C++20
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.

Resampler.cpp 12KB

3 jaren geleden
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. #include "Resampler.h"
  30. #include <math.h>
  31. Resampler::Resampler(StepAdaptionParameters settings){
  32. #ifdef DEBUG_RESAMPLER
  33. while (!Serial);
  34. #endif
  35. _settings=settings;
  36. kaiserWindowSamples[0]=1.;
  37. double step=1./(NO_EXACT_KAISER_SAMPLES-1);
  38. double* xSq=kaiserWindowXsq;
  39. for (uint16_t i = 1; i <NO_EXACT_KAISER_SAMPLES; i++){
  40. double x=(double)i*step;
  41. *xSq++=(1.-x*x);
  42. }
  43. }
  44. void Resampler::getKaiserExact(float beta){
  45. const double thres=1e-10;
  46. double* winS=&kaiserWindowSamples[1];
  47. double* t=tempRes;
  48. for (uint16_t i = 1; i <NO_EXACT_KAISER_SAMPLES; i++){
  49. *winS++=1.;
  50. *t++=1.;
  51. }
  52. double denomLastSummand=1.;
  53. const double halfBetaSq=beta*beta/4.;
  54. double denom=1.;
  55. double i=1.;
  56. while(i < 1000){
  57. denomLastSummand*=(halfBetaSq/(i*i));
  58. i+=1.;
  59. denom+=denomLastSummand;
  60. t=tempRes;
  61. winS=&kaiserWindowSamples[1];
  62. double* xSq=kaiserWindowXsq;
  63. for (uint16_t j=0; j< NO_EXACT_KAISER_SAMPLES-1;j++){
  64. (*t)*=(*xSq);
  65. double summand=(denomLastSummand*(*t));
  66. (*winS)+=summand;
  67. if (summand< thres){
  68. break;
  69. }
  70. ++winS;
  71. ++t;
  72. ++xSq;
  73. }
  74. if (denomLastSummand< thres){
  75. break;
  76. }
  77. }
  78. winS=&kaiserWindowSamples[1];
  79. for (int32_t i = 0; i <NO_EXACT_KAISER_SAMPLES-1; i++){
  80. *winS++/=denom;
  81. }
  82. }
  83. void Resampler::setKaiserWindow(float beta, int32_t noSamples){
  84. getKaiserExact(beta);
  85. double step=(float)(NO_EXACT_KAISER_SAMPLES-1.)/(noSamples-1.);
  86. double xPos=step;
  87. float* filterCoeff=filter;
  88. *filterCoeff=1.;
  89. ++filterCoeff;
  90. int32_t lower=(int)(xPos);
  91. double* windowLower=&kaiserWindowSamples[lower];
  92. double* windowUpper=&kaiserWindowSamples[lower+1];
  93. for (int32_t i =0; i< noSamples-2; i++){
  94. double lambda=xPos-lower;
  95. if (lambda > 1.){
  96. lambda-=1.;
  97. ++windowLower;
  98. ++windowUpper;
  99. lower++;
  100. }
  101. *filterCoeff++=(float)(lambda*(*windowUpper)+(1.-lambda)*(*windowLower));
  102. xPos+=step;
  103. if (xPos>=NO_EXACT_KAISER_SAMPLES-1 || lower >=NO_EXACT_KAISER_SAMPLES-1){
  104. break;
  105. }
  106. }
  107. *filterCoeff=*windowUpper;
  108. }
  109. void Resampler::setFilter(int32_t halfFiltLength,int32_t overSampling, float cutOffFrequ, float kaiserBeta){
  110. const int32_t noSamples=halfFiltLength*overSampling+1;
  111. setKaiserWindow(kaiserBeta, noSamples);
  112. float* filterCoeff=filter;
  113. *filterCoeff++=cutOffFrequ;
  114. double step=halfFiltLength/(noSamples-1.);
  115. double xPos=step;
  116. double factor=M_PI*cutOffFrequ;
  117. for (int32_t i = 0; i<noSamples-1; i++ ){
  118. *filterCoeff++*=(float)((sin(xPos*factor)/(xPos*M_PI)));
  119. xPos+=step;
  120. }
  121. }
  122. double Resampler::getStep() const {
  123. return _stepAdapted;
  124. }
  125. void Resampler::reset(){
  126. _initialized=false;
  127. }
  128. void Resampler::configure(float fs, float newFs, float attenuation, int32_t minHalfFilterLength){
  129. // Serial.print("configure, fs: ");
  130. // Serial.println(fs);
  131. if (fs<=0. || newFs <=0.){
  132. _initialized=false;
  133. return;
  134. }
  135. _step=(double)fs/newFs;
  136. _configuredStep=_step;
  137. _stepAdapted=_step;
  138. _sum=0.;
  139. _oldDiffs[0]=0.;
  140. _oldDiffs[1]=0.;
  141. for (uint8_t i =0; i< MAX_NO_CHANNELS; i++){
  142. memset(_buffer[i], 0, sizeof(float)*MAX_HALF_FILTER_LENGTH*2);
  143. }
  144. float cutOffFrequ, kaiserBeta;
  145. _overSamplingFactor=1024;
  146. if (fs <= newFs){
  147. cutOffFrequ=1.;
  148. kaiserBeta=10;
  149. _halfFilterLength=minHalfFilterLength;
  150. }
  151. else{
  152. cutOffFrequ=newFs/fs;
  153. double b=2.*(0.5*newFs-20000)/fs; //this transition band width causes aliasing. However the generated frequencies are above 20kHz
  154. #ifdef DEBUG_RESAMPLER
  155. Serial.print("b: ");
  156. Serial.println(b);
  157. #endif
  158. double hfl=(int32_t)((attenuation-8)/(2.*2.285*TWO_PI*b)+0.5);
  159. if (hfl >= minHalfFilterLength && hfl <= MAX_HALF_FILTER_LENGTH){
  160. _halfFilterLength=hfl;
  161. #ifdef DEBUG_RESAMPLER
  162. Serial.print("Attenuation: ");
  163. #endif
  164. }
  165. else if (hfl < minHalfFilterLength){
  166. _halfFilterLength=minHalfFilterLength;
  167. attenuation=((2*_halfFilterLength+1)-1)*(2.285*TWO_PI*b)+8;
  168. #ifdef DEBUG_RESAMPLER
  169. Serial.println("Resmapler: sinc filter length increased");
  170. Serial.print("Attenuation increased to ");
  171. #endif
  172. }
  173. else{
  174. _halfFilterLength=MAX_HALF_FILTER_LENGTH;
  175. attenuation=((2*_halfFilterLength+1)-1)*(2.285*TWO_PI*b)+8;
  176. #ifdef DEBUG_RESAMPLER
  177. Serial.println("Resmapler: needed sinc filter length too long");
  178. Serial.print("Attenuation decreased to ");
  179. #endif
  180. }
  181. #ifdef DEBUG_RESAMPLER
  182. Serial.print(attenuation);
  183. Serial.println("dB");
  184. #endif
  185. if (attenuation>50.){
  186. kaiserBeta=0.1102*(attenuation-8.7);
  187. }
  188. else if (21<=attenuation && attenuation<=50){
  189. kaiserBeta=0.5842*(float)pow(attenuation-21.,0.4)+0.07886*(attenuation-21.);
  190. }
  191. else{
  192. kaiserBeta=0.;
  193. }
  194. int32_t noSamples=_halfFilterLength*_overSamplingFactor+1;
  195. if (noSamples > MAX_FILTER_SAMPLES){
  196. int32_t f = (noSamples-1)/(MAX_FILTER_SAMPLES-1)+1;
  197. _overSamplingFactor/=f;
  198. }
  199. }
  200. #ifdef DEBUG_RESAMPLER
  201. Serial.print("fs: ");
  202. Serial.println(fs);
  203. Serial.print("cutOffFrequ: ");
  204. Serial.println(cutOffFrequ);
  205. Serial.print("filter length: ");
  206. Serial.println(2*_halfFilterLength+1);
  207. Serial.print("overSampling: ");
  208. Serial.println(_overSamplingFactor);
  209. Serial.print("kaiserBeta: ");
  210. Serial.println(kaiserBeta, 12);
  211. Serial.print("_step: ");
  212. Serial.println(_step, 12);
  213. #endif
  214. setFilter(_halfFilterLength, _overSamplingFactor, cutOffFrequ, kaiserBeta);
  215. _filterLength=_halfFilterLength*2;
  216. for (uint8_t i =0; i< MAX_NO_CHANNELS; i++){
  217. _endOfBuffer[i]=&_buffer[i][_filterLength];
  218. }
  219. _cPos=-_halfFilterLength; //marks the current center position of the filter
  220. _initialized=true;
  221. }
  222. bool Resampler::initialized() const {
  223. return _initialized;
  224. }
  225. void Resampler::resample(float* input0, float* input1, uint16_t inputLength, uint16_t& processedLength, float* output0, float* output1,uint16_t outputLength, uint16_t& outputCount) {
  226. outputCount=0;
  227. int32_t successorIndex=(int32_t)(ceil(_cPos)); //negative number -> currently the _buffer0 of the last iteration is used
  228. float* ip0, *ip1, *fPtr;
  229. float filterC;
  230. float si0[2];
  231. float si1[2];
  232. while (floor(_cPos + _halfFilterLength) < inputLength && outputCount < outputLength){
  233. float dist=successorIndex-_cPos;
  234. const float distScaled=dist*_overSamplingFactor;
  235. int32_t rightIndex=abs((int32_t)(ceil(distScaled))-_overSamplingFactor*_halfFilterLength);
  236. const int32_t indexData=successorIndex-_halfFilterLength;
  237. if (indexData>=0){
  238. ip0=input0+indexData;
  239. ip1=input1+indexData;
  240. }
  241. else {
  242. ip0=_buffer[0]+indexData+_filterLength;
  243. ip1=_buffer[1]+indexData+_filterLength;
  244. }
  245. fPtr=filter+rightIndex;
  246. if (rightIndex==_overSamplingFactor*_halfFilterLength){
  247. si1[0]=*ip0++**fPtr;
  248. si1[1]=*ip1++**fPtr;
  249. memset(si0, 0, 2*sizeof(float));
  250. fPtr-=_overSamplingFactor;
  251. rightIndex=(int32_t)(ceil(distScaled))+_overSamplingFactor; //needed below
  252. }
  253. else {
  254. memset(si0, 0, 2*sizeof(float));
  255. memset(si1, 0, 2*sizeof(float));
  256. rightIndex=(int32_t)(ceil(distScaled)); //needed below
  257. }
  258. for (uint16_t i =0 ; i<_halfFilterLength; i++){
  259. if(ip0==_endOfBuffer[0]){
  260. ip0=input0;
  261. ip1=input1;
  262. }
  263. si1[0]+=*ip0**fPtr;
  264. si1[1]+=*ip1**fPtr;
  265. filterC=*(fPtr+1);
  266. si0[0]+=*ip0*filterC;
  267. si0[1]+=*ip1*filterC;
  268. fPtr-=_overSamplingFactor;
  269. ++ip0;
  270. ++ip1;
  271. }
  272. fPtr=filter+rightIndex-1;
  273. for (uint16_t i =0 ; i<_halfFilterLength; i++){
  274. if(ip0==_endOfBuffer[0]){
  275. ip0=input0;
  276. ip1=input1;
  277. }
  278. si0[0]+=*ip0**fPtr;
  279. si0[1]+=*ip1**fPtr;
  280. filterC=*(fPtr+1);
  281. si1[0]+=*ip0*filterC;
  282. si1[1]+=*ip1*filterC;
  283. fPtr+=_overSamplingFactor;
  284. ++ip0;
  285. ++ip1;
  286. }
  287. const float w0=ceil(distScaled)-distScaled;
  288. const float w1=1.-w0;
  289. *output0++=si0[0]*w0 + si1[0]*w1;
  290. *output1++=si0[1]*w0 + si1[1]*w1;
  291. outputCount++;
  292. _cPos+=_stepAdapted;
  293. while (_cPos >successorIndex){
  294. successorIndex++;
  295. }
  296. }
  297. if(outputCount < outputLength){
  298. //ouput vector not full -> we ran out of input samples
  299. processedLength=inputLength;
  300. }
  301. else{
  302. processedLength=min(inputLength, (int16_t)floor(_cPos + _halfFilterLength));
  303. }
  304. //fill _buffer
  305. const int32_t indexData=processedLength-_filterLength;
  306. if (indexData>=0){
  307. ip0=input0+indexData;
  308. ip1=input1+indexData;
  309. const unsigned long long bytesToCopy= _filterLength*sizeof(float);
  310. memcpy((void *)_buffer[0], (void *)ip0, bytesToCopy);
  311. memcpy((void *)_buffer[1], (void *)ip1, bytesToCopy);
  312. }
  313. else {
  314. float* b0=_buffer[0];
  315. float* b1=_buffer[1];
  316. ip0=_buffer[0]+indexData+_filterLength;
  317. ip1=_buffer[1]+indexData+_filterLength;
  318. for (uint16_t i =0; i< _filterLength; i++){
  319. if(ip0==_endOfBuffer[0]){
  320. ip0=input0;
  321. ip1=input1;
  322. }
  323. *b0++ = *ip0++;
  324. *b1++ = *ip1++;
  325. }
  326. }
  327. _cPos-=processedLength;
  328. if (_cPos < -_halfFilterLength){
  329. _cPos=-_halfFilterLength;
  330. }
  331. }
  332. void Resampler::fixStep(){
  333. if (!_initialized){
  334. return;
  335. }
  336. _step=_stepAdapted;
  337. _sum=0.;
  338. _oldDiffs[0]=0.;
  339. _oldDiffs[1]=0.;
  340. }
  341. void Resampler::addToPos(double val){
  342. if(val < 0){
  343. return;
  344. }
  345. _cPos+=val;
  346. }
  347. bool Resampler::addToSampleDiff(double diff){
  348. _oldDiffs[0]=_oldDiffs[1];
  349. _oldDiffs[1]=(1.-_settings.alpha)*_oldDiffs[1]+_settings.alpha*diff;
  350. const double slope=_oldDiffs[1]-_oldDiffs[0];
  351. _sum+=diff;
  352. double correction=_settings.kp*diff+_settings.kd*slope+_settings.ki*_sum;
  353. const double oldStepAdapted=_stepAdapted;
  354. _stepAdapted=_step+correction;
  355. if (abs(_stepAdapted/_configuredStep-1.) > _settings.maxAdaption){
  356. _initialized=false;
  357. return false;
  358. }
  359. bool settled=false;
  360. if ((abs(oldStepAdapted- _stepAdapted)/_stepAdapted < _settledThrs*abs(diff) && abs(diff) > 1.5*1e-6)) {
  361. settled=true;
  362. }
  363. return settled;
  364. }
  365. double Resampler::getXPos() const{
  366. return _cPos+(double)_halfFilterLength;
  367. }