Skip to content

Commit

Permalink
feat(dsp): update DelayLine ctor, freqBin, update pkg
Browse files Browse the repository at this point in the history
  • Loading branch information
postspectacular committed Jan 3, 2020
1 parent 3970aca commit 228a81e
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 4 deletions.
3 changes: 2 additions & 1 deletion packages/dsp/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@thi.ng/dsp",
"version": "1.0.18",
"description": "Assorted oscillators / waveform generators & DSP utils",
"description": "Assorted oscillators / wave gens, FFT, windowing functions & DSP utils",
"module": "./index.js",
"main": "./lib/index.js",
"umd:main": "./lib/index.umd.js",
Expand Down Expand Up @@ -39,6 +39,7 @@
},
"dependencies": {
"@thi.ng/api": "^6.6.0",
"@thi.ng/checks": "^2.4.2",
"@thi.ng/math": "^1.5.1"
},
"keywords": [
Expand Down
27 changes: 25 additions & 2 deletions packages/dsp/src/delay.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import { Fn0 } from "@thi.ng/api";
import { isFunction } from "@thi.ng/checks";

/**
* Ring buffer / delay line for arbitrary values w/ support for tapping
* at any delay time (within configured buffer size).
Expand All @@ -7,10 +10,26 @@ export class DelayLine<T> {
readPos: number;
writePos: number;

constructor(n: number, empty: T) {
this.buf = new Array(n).fill(empty);
/**
* Constructs new delay line of size `n` and initializes all
* elements to `empty`. If the latter is a function, the buffer will
* be initialized with the results of that function (called for each
* element).
*
* @param n
* @param empty
*/
constructor(n: number, empty: T | Fn0<T>) {
this.writePos = n - 1;
this.readPos = 0;
this.buf = new Array(n);
if (isFunction(empty)) {
for (let i = 0; i < n; i++) {
this.buf[i] = empty();
}
} else {
this.buf.fill(empty);
}
}

/**
Expand Down Expand Up @@ -45,6 +64,10 @@ export class DelayLine<T> {
this.buf[this.writePos] = x;
}

/**
* Moves read & write cursors one step forward. Useful for skipping
* elements and/or to create gaps in the delay line.
*/
step() {
const n = this.buf.length;
++this.writePos >= n && (this.writePos -= n);
Expand Down
2 changes: 1 addition & 1 deletion packages/dsp/src/fft.ts
Original file line number Diff line number Diff line change
Expand Up @@ -326,7 +326,7 @@ export const spectrumPhase = (
* @param fs - sample rate
* @param n - window size
*/
export const freqBin = (f: number, fs: number, n: number) => (f * n) / fs;
export const freqBin = (f: number, fs: number, n: number) => ((f * n) / fs) | 0;

/**
* Returns frequency for given FFT bin index, sample rate and window
Expand Down

0 comments on commit 228a81e

Please sign in to comment.