Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

386 linhas
12KB

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