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.

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