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.

398 lines
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. #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. double Resampler::getAttenuation() const {
  126. return _attenuation;
  127. }
  128. int32_t Resampler::getHalfFilterLength() const{
  129. return _halfFilterLength;
  130. }
  131. void Resampler::reset(){
  132. _initialized=false;
  133. }
  134. void Resampler::configure(float fs, float newFs, float attenuation, int32_t minHalfFilterLength){
  135. // Serial.print("configure, fs: ");
  136. // Serial.println(fs);
  137. if (fs<=0. || newFs <=0.){
  138. _attenuation=0;
  139. _halfFilterLength=0;
  140. _initialized=false;
  141. return;
  142. }
  143. _step=(double)fs/newFs;
  144. _configuredStep=_step;
  145. _stepAdapted=_step;
  146. _sum=0.;
  147. _oldDiffs[0]=0.;
  148. _oldDiffs[1]=0.;
  149. for (uint8_t i =0; i< MAX_NO_CHANNELS; i++){
  150. memset(_buffer[i], 0, sizeof(float)*MAX_HALF_FILTER_LENGTH*2);
  151. }
  152. float cutOffFrequ, kaiserBeta;
  153. _overSamplingFactor=1024;
  154. if (fs <= newFs){
  155. _attenuation=0;
  156. cutOffFrequ=1.;
  157. kaiserBeta=10;
  158. _halfFilterLength=min(minHalfFilterLength,MAX_HALF_FILTER_LENGTH);
  159. }
  160. else{
  161. cutOffFrequ=newFs/fs;
  162. double b=2.*(0.5*newFs-20000)/fs; //this transition band width causes aliasing. However the generated frequencies are above 20kHz
  163. #ifdef DEBUG_RESAMPLER
  164. Serial.print("b: ");
  165. Serial.println(b);
  166. #endif
  167. double hfl=(int32_t)((attenuation-8)/(2.*2.285*TWO_PI*b)+0.5);
  168. if (hfl >= minHalfFilterLength && hfl <= MAX_HALF_FILTER_LENGTH){
  169. _halfFilterLength=hfl;
  170. #ifdef DEBUG_RESAMPLER
  171. Serial.print("Attenuation: ");
  172. #endif
  173. }
  174. else if (hfl < minHalfFilterLength){
  175. _halfFilterLength=minHalfFilterLength;
  176. attenuation=((2*_halfFilterLength+1)-1)*(2.285*TWO_PI*b)+8;
  177. #ifdef DEBUG_RESAMPLER
  178. Serial.println("Resmapler: sinc filter length increased");
  179. Serial.print("Attenuation increased to ");
  180. #endif
  181. }
  182. else{
  183. _halfFilterLength=MAX_HALF_FILTER_LENGTH;
  184. attenuation=((2*_halfFilterLength+1)-1)*(2.285*TWO_PI*b)+8;
  185. #ifdef DEBUG_RESAMPLER
  186. Serial.println("Resmapler: needed sinc filter length too long");
  187. Serial.print("Attenuation decreased to ");
  188. #endif
  189. }
  190. #ifdef DEBUG_RESAMPLER
  191. Serial.print(attenuation);
  192. Serial.println("dB");
  193. #endif
  194. if (attenuation>50.){
  195. kaiserBeta=0.1102*(attenuation-8.7);
  196. }
  197. else if (21<=attenuation && attenuation<=50){
  198. kaiserBeta=0.5842*(float)pow(attenuation-21.,0.4)+0.07886*(attenuation-21.);
  199. }
  200. else{
  201. kaiserBeta=0.;
  202. }
  203. int32_t noSamples=_halfFilterLength*_overSamplingFactor+1;
  204. if (noSamples > MAX_FILTER_SAMPLES){
  205. int32_t f = (noSamples-1)/(MAX_FILTER_SAMPLES-1)+1;
  206. _overSamplingFactor/=f;
  207. }
  208. _attenuation=attenuation;
  209. }
  210. #ifdef DEBUG_RESAMPLER
  211. Serial.print("fs: ");
  212. Serial.println(fs);
  213. Serial.print("cutOffFrequ: ");
  214. Serial.println(cutOffFrequ);
  215. Serial.print("filter length: ");
  216. Serial.println(2*_halfFilterLength+1);
  217. Serial.print("overSampling: ");
  218. Serial.println(_overSamplingFactor);
  219. Serial.print("kaiserBeta: ");
  220. Serial.println(kaiserBeta, 12);
  221. Serial.print("_step: ");
  222. Serial.println(_step, 12);
  223. #endif
  224. setFilter(_halfFilterLength, _overSamplingFactor, cutOffFrequ, kaiserBeta);
  225. _filterLength=_halfFilterLength*2;
  226. for (uint8_t i =0; i< MAX_NO_CHANNELS; i++){
  227. _endOfBuffer[i]=&_buffer[i][_filterLength];
  228. }
  229. _cPos=-_halfFilterLength; //marks the current center position of the filter
  230. _initialized=true;
  231. }
  232. bool Resampler::initialized() const {
  233. return _initialized;
  234. }
  235. void Resampler::resample(float* input0, float* input1, uint16_t inputLength, uint16_t& processedLength, float* output0, float* output1,uint16_t outputLength, uint16_t& outputCount) {
  236. outputCount=0;
  237. int32_t successorIndex=(int32_t)(ceil(_cPos)); //negative number -> currently the _buffer0 of the last iteration is used
  238. float* ip0, *ip1, *fPtr;
  239. float filterC;
  240. float si0[2];
  241. float si1[2];
  242. while (floor(_cPos + _halfFilterLength) < inputLength && outputCount < outputLength){
  243. float dist=successorIndex-_cPos;
  244. const float distScaled=dist*_overSamplingFactor;
  245. int32_t rightIndex=abs((int32_t)(ceil(distScaled))-_overSamplingFactor*_halfFilterLength);
  246. const int32_t indexData=successorIndex-_halfFilterLength;
  247. if (indexData>=0){
  248. ip0=input0+indexData;
  249. ip1=input1+indexData;
  250. }
  251. else {
  252. ip0=_buffer[0]+indexData+_filterLength;
  253. ip1=_buffer[1]+indexData+_filterLength;
  254. }
  255. fPtr=filter+rightIndex;
  256. if (rightIndex==_overSamplingFactor*_halfFilterLength){
  257. si1[0]=*ip0++**fPtr;
  258. si1[1]=*ip1++**fPtr;
  259. memset(si0, 0, 2*sizeof(float));
  260. fPtr-=_overSamplingFactor;
  261. rightIndex=(int32_t)(ceil(distScaled))+_overSamplingFactor; //needed below
  262. }
  263. else {
  264. memset(si0, 0, 2*sizeof(float));
  265. memset(si1, 0, 2*sizeof(float));
  266. rightIndex=(int32_t)(ceil(distScaled)); //needed below
  267. }
  268. for (uint16_t i =0 ; i<_halfFilterLength; i++){
  269. if(ip0==_endOfBuffer[0]){
  270. ip0=input0;
  271. ip1=input1;
  272. }
  273. si1[0]+=*ip0**fPtr;
  274. si1[1]+=*ip1**fPtr;
  275. filterC=*(fPtr+1);
  276. si0[0]+=*ip0*filterC;
  277. si0[1]+=*ip1*filterC;
  278. fPtr-=_overSamplingFactor;
  279. ++ip0;
  280. ++ip1;
  281. }
  282. fPtr=filter+rightIndex-1;
  283. for (uint16_t i =0 ; i<_halfFilterLength; i++){
  284. if(ip0==_endOfBuffer[0]){
  285. ip0=input0;
  286. ip1=input1;
  287. }
  288. si0[0]+=*ip0**fPtr;
  289. si0[1]+=*ip1**fPtr;
  290. filterC=*(fPtr+1);
  291. si1[0]+=*ip0*filterC;
  292. si1[1]+=*ip1*filterC;
  293. fPtr+=_overSamplingFactor;
  294. ++ip0;
  295. ++ip1;
  296. }
  297. const float w0=ceil(distScaled)-distScaled;
  298. const float w1=1.-w0;
  299. *output0++=si0[0]*w0 + si1[0]*w1;
  300. *output1++=si0[1]*w0 + si1[1]*w1;
  301. outputCount++;
  302. _cPos+=_stepAdapted;
  303. while (_cPos >successorIndex){
  304. successorIndex++;
  305. }
  306. }
  307. if(outputCount < outputLength){
  308. //ouput vector not full -> we ran out of input samples
  309. processedLength=inputLength;
  310. }
  311. else{
  312. processedLength=min(inputLength, (int16_t)floor(_cPos + _halfFilterLength));
  313. }
  314. //fill _buffer
  315. const int32_t indexData=processedLength-_filterLength;
  316. if (indexData>=0){
  317. ip0=input0+indexData;
  318. ip1=input1+indexData;
  319. const unsigned long long bytesToCopy= _filterLength*sizeof(float);
  320. memcpy((void *)_buffer[0], (void *)ip0, bytesToCopy);
  321. memcpy((void *)_buffer[1], (void *)ip1, bytesToCopy);
  322. }
  323. else {
  324. float* b0=_buffer[0];
  325. float* b1=_buffer[1];
  326. ip0=_buffer[0]+indexData+_filterLength;
  327. ip1=_buffer[1]+indexData+_filterLength;
  328. for (uint16_t i =0; i< _filterLength; i++){
  329. if(ip0==_endOfBuffer[0]){
  330. ip0=input0;
  331. ip1=input1;
  332. }
  333. *b0++ = *ip0++;
  334. *b1++ = *ip1++;
  335. }
  336. }
  337. _cPos-=processedLength;
  338. if (_cPos < -_halfFilterLength){
  339. _cPos=-_halfFilterLength;
  340. }
  341. }
  342. void Resampler::fixStep(){
  343. if (!_initialized){
  344. return;
  345. }
  346. _step=_stepAdapted;
  347. _sum=0.;
  348. _oldDiffs[0]=0.;
  349. _oldDiffs[1]=0.;
  350. }
  351. void Resampler::addToPos(double val){
  352. if(val < 0){
  353. return;
  354. }
  355. _cPos+=val;
  356. }
  357. bool Resampler::addToSampleDiff(double diff){
  358. _oldDiffs[0]=_oldDiffs[1];
  359. _oldDiffs[1]=(1.-_settings.alpha)*_oldDiffs[1]+_settings.alpha*diff;
  360. const double slope=_oldDiffs[1]-_oldDiffs[0];
  361. _sum+=diff;
  362. double correction=_settings.kp*diff+_settings.kd*slope+_settings.ki*_sum;
  363. const double oldStepAdapted=_stepAdapted;
  364. _stepAdapted=_step+correction;
  365. if (abs(_stepAdapted/_configuredStep-1.) > _settings.maxAdaption){
  366. _initialized=false;
  367. return false;
  368. }
  369. bool settled=false;
  370. if ((abs(oldStepAdapted- _stepAdapted)/_stepAdapted < _settledThrs*abs(diff) && abs(diff) > 1.5*1e-6)) {
  371. settled=true;
  372. }
  373. return settled;
  374. }
  375. double Resampler::getXPos() const{
  376. return _cPos+(double)_halfFilterLength;
  377. }