| Name | Message | Date |
|---|---|---|
| 📁 assets | 5 hours ago | |
| 📄 birdnet.worker.ts | 3 hours ago | |
| 📄 index.ts | 5 hours ago | |
| 📄 types.ts | 3 hours ago |
📄
src/lib/birdnet.worker.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
import * as tf from "@tensorflow/tfjs";
import type { Prediction, WorkerInMessage, WorkerOutMessage } from "./types";
const MODEL_PATH = "/models/birdnet/model.json";
const LABELS_PATH = "/models/birdnet/labels/en_us.txt";
const WINDOW_SAMPLES = 144000;
const ALPHA = 5.0;
interface BirdLabel {
scientificName: string;
commonName: string;
}
let model: tf.LayersModel | null = null;
let labels: BirdLabel[] = [];
// ── Custom MelSpecLayerSimple ──────────────────────────────────────────────
// Ported from https://github.com/birdnet-team/real-time-pwa (MIT)
class MelSpecLayerSimple extends tf.layers.Layer {
sampleRate: number;
specShape: number[];
frameStep: number;
frameLength: number;
melFilterbank: tf.Tensor2D;
magScale!: tf.LayerVariable;
constructor(config: Record<string, unknown>) {
super(config as tf.serialization.ConfigDict);
this.sampleRate = config.sampleRate as number;
this.specShape = config.specShape as number[];
this.frameStep = config.frameStep as number;
this.frameLength = config.frameLength as number;
this.melFilterbank = tf.tensor2d(config.melFilterbank as number[][]);
}
build(_inputShape: tf.Shape | tf.Shape[]) {
this.magScale = this.addWeight(
"magnitude_scaling",
[],
"float32",
tf.initializers.constant({ value: 1.23 }),
);
super.build(_inputShape);
}
computeOutputShape(inputShape: tf.Shape): tf.Shape {
return [inputShape[0], this.specShape[0], this.specShape[1], 1];
}
call(inputs: tf.Tensor | tf.Tensor[]): tf.Tensor {
return tf.tidy(() => {
const x = Array.isArray(inputs) ? inputs[0] : inputs;
const frameLength = this.frameLength;
const frameStep = this.frameStep;
return tf.stack(
x.split(x.shape[0]).map((input) => {
let spec = input.squeeze();
spec = tf.sub(spec, tf.min(spec, -1, true));
spec = tf.div(spec, tf.max(spec, -1, true).add(1e-6));
spec = tf.sub(spec, 0.5).mul(2.0);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
spec = (tf.engine() as any).runKernel("STFT", {
signal: spec,
frameLength,
frameStep,
});
spec = tf.matMul(spec as tf.Tensor2D, this.melFilterbank).pow(2.0);
spec = spec.pow(
tf.div(1.0, tf.add(1.0, tf.exp(this.magScale.read()))),
);
spec = tf.reverse(spec, -1);
spec = tf.transpose(spec).expandDims(-1);
return spec;
}),
);
});
}
static get className() {
return "MelSpecLayerSimple";
}
}
// ── Custom STFT WebGL kernel ───────────────────────────────────────────────
// Ported from https://github.com/birdnet-team/real-time-pwa (MIT)
function registerStftKernel() {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const kernelFunc: tf.KernelFunc = (params: any) => {
const { backend, inputs } = params as {
backend: unknown;
inputs: { signal: unknown; frameLength: number; frameStep: number };
};
const b = backend as Record<string, (...args: unknown[]) => unknown>;
const { signal, frameLength, frameStep } = inputs;
const fl = frameLength as number;
const fs = frameStep as number;
const innerDim = fl / 2;
const log2Inner = Math.log2(innerDim);
// Stage 1: windowing + bit-reversal
let cur = b.runWebGLProgram(
{
variableNames: ["x"],
outputShape: [(signal as { size: number }).size],
userCode: `void main(){
ivec2 c=getOutputCoords();
int p=c[1]%${innerDim};
int k=0;
for(int i=0;i<${log2Inner};++i){
if((p & (1<<i))!=0){ k|=(1<<(${log2Inner - 1}-i)); }
}
int i=2*k;
if(c[1]>=${innerDim}){ i=2*(k%${innerDim})+1; }
int q=c[0]*${fl}+i;
float val=getX((q/${fl})*${fs}+ q % ${fl});
float cosArg=${(2.0 * Math.PI) / fl}*float(q);
float mul=0.5-0.5*cos(cosArg);
setOutput(val*mul);
}`,
} as unknown,
[signal],
"float32",
) as unknown;
// Stage 2: FFT butterflies
for (let len = 1; len < innerDim; len *= 2) {
const prev = cur;
cur = b.runWebGLProgram(
{
variableNames: ["x"],
outputShape: [innerDim * 2],
userCode: `void main(){
ivec2 c=getOutputCoords();
int b=c[0];
int i=c[1];
int k=i%${innerDim};
int isHigh=(k%${len * 2})/${len};
int highSign=(1 - isHigh*2);
int baseIndex=k - isHigh*${len};
float t=${Math.PI / len}*float(k%${len});
float a=cos(t);
float bsin=sin(-t);
float oddK_re=getX(b, baseIndex+${len});
float oddK_im=getX(b, baseIndex+${len + innerDim});
if(i<${innerDim}){
float evenK_re=getX(b, baseIndex);
setOutput(evenK_re + (oddK_re*a - oddK_im*bsin)*float(highSign));
} else {
float evenK_im=getX(b, baseIndex+${innerDim});
setOutput(evenK_im + (oddK_re*bsin + oddK_im*a)*float(highSign));
}
}`,
} as unknown,
[prev],
"float32",
) as unknown;
(
b.disposeIntermediateTensorInfo as (t: unknown) => void
)(prev);
}
// Stage 3: real RFFT output
const real = b.runWebGLProgram(
{
variableNames: ["x"],
outputShape: [innerDim + 1],
userCode: `void main(){
ivec2 c=getOutputCoords();
int b=c[0];
int i=c[1];
int zI=i%${innerDim};
int conjI=(${innerDim}-i)%${innerDim};
float Zk0=getX(b,zI);
float Zk1=getX(b,zI+${innerDim});
float Zk_conj0=getX(b,conjI);
float Zk_conj1=-getX(b,conjI+${innerDim});
float t=${-2.0 * Math.PI}*float(i)/float(${innerDim * 2});
float diff0=Zk0 - Zk_conj0;
float diff1=Zk1 - Zk_conj1;
float result=(Zk0+Zk_conj0 + cos(t)*diff1 + sin(t)*diff0)*0.5;
setOutput(result);
}`,
} as unknown,
[cur],
"float32",
) as unknown;
(b.disposeIntermediateTensorInfo as (t: unknown) => void)(cur);
return real as tf.TensorInfo;
};
tf.registerKernel({ kernelName: "STFT", backendName: "webgl", kernelFunc });
}
// ── Init ───────────────────────────────────────────────────────────────────
async function init() {
try {
await tf.setBackend("webgl");
registerStftKernel();
tf.serialization.registerClass(MelSpecLayerSimple);
const labelsText = await fetch(LABELS_PATH).then((r) => r.text());
labels = labelsText
.split("\n")
.filter(Boolean)
.map((line) => {
const idx = line.indexOf("_");
return {
scientificName: idx >= 0 ? line.slice(0, idx) : line,
commonName: idx >= 0 ? line.slice(idx + 1) : line,
};
});
model = await tf.loadLayersModel(MODEL_PATH);
console.log(
"BirdNET model inputs:",
model.inputs.map((t) => t.shape),
"outputs:",
model.outputs.map((t) => t.shape),
);
tf.tidy(() => {
(model as tf.LayersModel).predict(tf.zeros([1, WINDOW_SAMPLES]));
});
const out: WorkerOutMessage = { type: "ready" };
self.postMessage(out);
} catch (err) {
const out: WorkerOutMessage = {
type: "error",
message: String(err),
};
self.postMessage(out);
}
}
// ── Analyze ────────────────────────────────────────────────────────────────
async function analyze(samples: Float32Array) {
if (!model) return;
try {
const audioTensor = tf.tensor2d(samples, [1, WINDOW_SAMPLES]);
const resTensor = model.predict(audioTensor) as tf.Tensor;
const rawPreds = (await resTensor.array()) as number[][];
resTensor.dispose();
audioTensor.dispose();
const frame = rawPreds[0];
const sumsExp = frame.map((p) => Math.exp(ALPHA * p));
const pooled = sumsExp.map((s) => Math.log(s) / ALPHA);
const predictions: Prediction[] = pooled
.map((confidence, i) => ({
confidence,
commonName: labels[i]?.commonName ?? `Species ${i}`,
scientificName: labels[i]?.scientificName ?? "",
}))
.filter((p) => p.confidence > 0.1)
.sort((a, b) => b.confidence - a.confidence)
.slice(0, 10);
const out: WorkerOutMessage = { type: "results", predictions };
self.postMessage(out);
} catch (err) {
const out: WorkerOutMessage = { type: "error", message: String(err) };
self.postMessage(out);
}
}
self.addEventListener("message", (e: MessageEvent<WorkerInMessage>) => {
const msg = e.data;
if (msg.type === "init") {
init();
} else if (msg.type === "analyze") {
analyze(msg.samples);
}
});