-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgaborator-addon.cpp
More file actions
1425 lines (1237 loc) · 58.6 KB
/
Copy pathgaborator-addon.cpp
File metadata and controls
1425 lines (1237 loc) · 58.6 KB
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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// addon.cpp
#include <napi.h>
#include <vector>
#include <complex>
#include <numeric>
#include <cmath>
#include <algorithm>
#include <string> // For std::string
#include <sstream> // For std::stringstream
#include <iomanip> // For std::fixed, std::setprecision
#include <iostream> // For std::cerr
#include <fstream> // For file logging
#include "gaborator/gaborator.h"
#define OVERLAP 0.7
#define MAX_TEXTURE_SIZE 4096
// Debug logging to file
static std::ofstream &getDebugLog()
{
static std::ofstream debugLog("/tmp/gaborator_debug.log", std::ios::out | std::ios::app);
return debugLog;
}
#define DEBUG_LOG getDebugLog()
// Look-ahead true-peak brickwall limiter. For each sample the gain needed to bring
// the channel-linked inter-sample peak down to the ceiling is computed, then the
// gain curve is shaped so it never exceeds the ceiling while staying smooth: it drops to each
// new low, holds there for the hold time, then recovers (release); a final
// backward pass ramps the gain down ahead of each peak (look-ahead attack) so
// transients are contained without an abrupt gain step. The hold keeps the gain
// constant across a full low-frequency cycle so bass is scaled cleanly instead of
// gaining harmonic distortion from within-cycle gain modulation. All channels
// share one gain curve to preserve the stereo image.
static void applyLookaheadLimiter(std::vector<std::vector<float>> &channels, double sampleRate,
float holdMs = 40.0f, float releaseMs = 200.0f,
std::vector<float> *outGain = nullptr)
{
if (channels.empty() || channels[0].empty())
return;
// True-peak ceiling at -2 dBTP. The limiter bounds the inter-sample
// (reconstructed) peak, not just the sample peak, so playback resampling or the
// DAC cannot clip overshoots hidden between samples. The headroom below 0 dBFS
// exceeds the -1 dBTP streaming standard because near-Nyquist content is the
// hardest case for finite-rate true-peak detection and the gain-envelope
// smoothing below shifts the peak reduction slightly; the margin covers both.
constexpr float limiterCeiling = 0.794f;
// True-peak detection follows ITU-R BS.1770: oversample with a polyphase
// windowed-sinc FIR and take the peak of the reconstructed signal. Both the
// oversampling factor and the FIR length must be generous or the detector
// under-reads near-Nyquist inter-sample peaks (by ~1 dB at 4x/short-FIR) and the
// limiter lets real peaks slip over 0 dBFS, which clips on playback.
constexpr int OS = 16; // oversampling factor for true-peak detection
constexpr int HT = 16; // half kernel width; the interpolation FIR has 2*HT taps per phase
constexpr float kPi = 3.14159265358979323846f;
const int channelCount = static_cast<int>(channels.size());
const size_t blockLen = channels[0].size();
std::vector<float> gainEnv(blockLen, 1.0f);
// Polyphase windowed-sinc kernels that reconstruct the signal at the fractional
// sample positions between each pair of samples.
float kernels[OS][2 * HT];
for (int ph = 0; ph < OS; ++ph)
{
const float d = static_cast<float>(ph) / OS;
for (int t = 0; t < 2 * HT; ++t)
{
const float xpos = static_cast<float>(t - HT + 1) - d;
const float sinc = std::abs(xpos) < 1e-6f ? 1.0f : std::sin(kPi * xpos) / (kPi * xpos);
const float win = 0.5f + 0.5f * std::cos(kPi * xpos / HT);
kernels[ph][t] = sinc * win;
}
}
for (size_t i = 0; i < blockLen; ++i)
{
float truePeak = 0.0f;
const bool interior = i >= static_cast<size_t>(HT) && i + HT < blockLen;
for (int ch = 0; ch < channelCount; ++ch)
{
const float here = std::abs(channels[ch][i]);
float chPeak = here;
const float next = (i + 1 < blockLen) ? std::abs(channels[ch][i + 1]) : 0.0f;
// Only reconstruct between samples that are loud enough to overshoot.
if (interior && std::max(here, next) > 0.25f)
{
for (int ph = 1; ph < OS; ++ph)
{
float acc = 0.0f;
for (int t = 0; t < 2 * HT; ++t)
acc += channels[ch][i + t - HT + 1] * kernels[ph][t];
chPeak = std::max(chPeak, std::abs(acc));
}
}
truePeak = std::max(truePeak, chPeak);
}
if (truePeak > limiterCeiling)
gainEnv[i] = limiterCeiling / truePeak;
}
const float releaseStep = 1.0f / std::max(1.0f, static_cast<float>(sampleRate) * releaseMs * 0.001f);
const int holdSamples = static_cast<int>(std::max(0.0f, static_cast<float>(sampleRate) * holdMs * 0.001f));
// Ballistics: take the gain instantly down to each new low (instant attack — no
// peak escapes), hold it there for holdMs so a whole low-frequency cycle is scaled
// by a constant gain (no bass distortion), then recover linearly over releaseMs.
float env = gainEnv[0];
int hold = 0;
for (size_t i = 0; i < blockLen; ++i)
{
const float required = gainEnv[i];
if (required <= env)
{
env = required;
hold = holdSamples;
}
else if (hold > 0)
{
--hold;
}
else
{
env = std::min(required, env + releaseStep);
}
gainEnv[i] = env;
}
// Look-ahead and smoothing in one step: three forward box blurs (running averages,
// O(n) each). The forward window biases the smoothing earlier in time, so the gain
// is already reduced before each peak (the look-ahead attack). The hold above keeps
// the gain floor flat across the blur window at every peak, so averaging can never
// raise it back up — peaks stay caught, no overshoot. Three passes make the gain
// curve smooth (no slope kinks), so multiplying the audio by it adds no clicks.
const int boxW = std::max(1, static_cast<int>(std::lround(static_cast<double>(sampleRate) * 0.0007)));
std::vector<float> tmp(blockLen);
for (int pass = 0; pass < 3; ++pass)
{
double sum = 0.0;
int count = 0;
for (int k = 0; k < boxW && static_cast<size_t>(k) < blockLen; ++k, ++count)
sum += gainEnv[k];
for (size_t i = 0; i < blockLen; ++i)
{
tmp[i] = static_cast<float>(sum / count);
sum -= gainEnv[i];
--count;
const size_t add = i + static_cast<size_t>(boxW);
if (add < blockLen)
{
sum += gainEnv[add];
++count;
}
}
gainEnv.swap(tmp);
}
for (size_t i = 0; i < blockLen; ++i)
for (int ch = 0; ch < channelCount; ++ch)
channels[ch][i] *= gainEnv[i];
// Hand back the final per-sample gain (1.0 = no reduction) for the meter.
if (outGain)
*outGain = std::move(gainEnv);
}
class AnalyzeWorker : public Napi::AsyncWorker
{
public:
AnalyzeWorker(Napi::Env env, const Napi::Array &planarInput, int channels, double sampleRate, const Napi::Object ¶msJs)
: Napi::AsyncWorker(env), deferred(Napi::Promise::Deferred::New(env)), channels(channels), sampleRate(sampleRate)
{
size_t length = planarInput.Get(0u).As<Napi::Float32Array>().ElementLength();
// Reference the channel buffers and read them by pointer on the worker
// thread rather than copying them into vectors on the main thread.
audioRefs.reserve(channels);
audioChannels.reserve(channels);
for (int ch = 0; ch < channels; ++ch)
{
Napi::Float32Array channelData = planarInput.Get(static_cast<uint32_t>(ch)).As<Napi::Float32Array>();
audioRefs.push_back(Napi::Reference<Napi::Float32Array>::New(channelData, 1));
audioChannels.push_back(channelData.Data());
}
numFrames = length;
bandsPerOctave = paramsJs.Get("bandsPerOctave").As<Napi::Number>().Int32Value();
fminHz = paramsJs.Get("minFreq").As<Napi::Number>().DoubleValue();
}
~AnalyzeWorker() {}
void Execute()
{
if (channels <= 0)
{
SetError("Number of channels must be positive.");
return;
}
double fminFrac = fminHz / sampleRate;
gaborator::log_fq_scale scale(bandsPerOctave, fminFrac);
gaborator::parameters params(scale, OVERLAP);
params.phase = gaborator::coef_phase::global;
gaborator::analyzer<float> analyzer(params);
int bandBegin = analyzer.bandpass_bands_begin();
numBands = analyzer.bandpass_bands_end() - bandBegin;
if (numBands < 0)
{
SetError("Gaborator analysis resulted in a negative number of bands.");
return;
}
bandOffsets.resize(numBands);
bandStepLog2s.resize(numBands);
bandLengths.resize(numBands);
bandFreqsHz.resize(numBands);
size_t totalComplexCoefficients = 0;
double coefficientDensity = 0.0;
for (int i = 0; i < numBands; ++i)
{
int gbno = bandBegin + i;
int stepLog2 = analyzer.band_step_log2(gbno);
coefficientDensity += 1.0 / (double)(1ULL << stepLog2);
double centerFreq = analyzer.bandpass_band_ff(gbno) * sampleRate;
size_t len = (numFrames > 0) ? ((numFrames - 1) >> stepLog2) + 1 : 0;
bandOffsets[i] = static_cast<uint32_t>(totalComplexCoefficients);
bandStepLog2s[i] = stepLog2;
bandLengths[i] = static_cast<uint32_t>(len);
bandFreqsHz[i] = centerFreq;
totalComplexCoefficients += len;
}
const int maxWidth = MAX_TEXTURE_SIZE;
const int maxHeight = MAX_TEXTURE_SIZE;
textureWidth = std::min((size_t)maxWidth, totalComplexCoefficients);
textureHeight = (totalComplexCoefficients > 0) ? (totalComplexCoefficients + textureWidth - 1) / textureWidth : 0;
if (textureHeight > maxHeight)
{
if (coefficientDensity > 1e-9)
{
size_t maxCoefficients = (size_t)maxWidth * maxHeight;
double maxFrames = (double)maxCoefficients / coefficientDensity;
double maxSeconds = maxFrames / sampleRate;
std::stringstream ss;
ss << "The maximum audio duration with these settings is " << std::fixed << std::setprecision(0) << maxSeconds << " seconds.";
SetError(ss.str().c_str());
}
else
{
SetError("The audio file is too long.");
}
return;
}
size_t floatsPerPixel = 4;
size_t dataFloatCount = (size_t)textureWidth * textureHeight * floatsPerPixel;
data.assign(dataFloatCount, 0.0f);
size_t floatsPerMapPixel = 2;
size_t paddedMapFloatCount = (size_t)textureWidth * textureHeight * floatsPerMapPixel;
inverseMap.assign(paddedMapFloatCount, 0.0f);
size_t maxPixelIndex = (size_t)textureWidth * textureHeight;
size_t floatsPerMetaPixel = 4;
size_t metadataFloatCount = (size_t)numBands * floatsPerMetaPixel;
metadata.resize(metadataFloatCount);
for (int i = 0; i < numBands; ++i)
{
metadata[i * floatsPerMetaPixel + 0] = static_cast<float>(bandOffsets[i]);
metadata[i * floatsPerMetaPixel + 1] = static_cast<float>(bandLengths[i]);
metadata[i * floatsPerMetaPixel + 2] = static_cast<float>(bandStepLog2s[i]);
metadata[i * floatsPerMetaPixel + 3] = bandFreqsHz[i];
}
for (int bandIdx = 0; bandIdx < numBands; ++bandIdx)
{
uint64_t timeStep = 1ULL << bandStepLog2s[bandIdx];
for (uint32_t i = 0; i < bandLengths[bandIdx]; ++i)
{
size_t linearPixelIndex = bandOffsets[bandIdx] + i;
inverseMap[linearPixelIndex * 2 + 0] = static_cast<float>(i * timeStep);
inverseMap[linearPixelIndex * 2 + 1] = static_cast<float>(bandIdx);
}
}
std::vector<gaborator::coefs<float>> allCoefs;
allCoefs.reserve(channels);
std::vector<std::vector<std::vector<float>>> previousPhases(channels);
for (int ch = 0; ch < channels; ++ch)
{
previousPhases[ch].resize(numBands);
for (int bandIdx = 0; bandIdx < numBands; ++bandIdx)
{
previousPhases[ch][bandIdx].resize(bandLengths[bandIdx], 0.0f);
}
}
for (int ch = 0; ch < channels; ++ch)
{
allCoefs.emplace_back(analyzer);
analyzer.analyze(audioChannels[ch], 0, static_cast<int64_t>(numFrames), allCoefs.back());
gaborator::process(
[&](int b, int64_t t, std::complex<float> &coef)
{
int bandIdx = b - bandBegin;
if (bandIdx < 0 || bandIdx >= numBands)
return;
int64_t tInBand = t >> bandStepLog2s[bandIdx];
if (tInBand < 0 || (size_t)tInBand >= bandLengths[bandIdx])
return;
size_t baseOffset = bandOffsets[bandIdx] + tInBand;
// Only write if within the clamped texture bounds
if (baseOffset >= maxPixelIndex)
return;
// Convert to magnitude and phase
float magnitude = std::abs(coef);
float phase = std::arg(coef);
// Accumulate total stored magnitude energy (sum of squares
// over every stored coefficient, all bands and channels) so
// the renderer can derive a single IR-normalization scalar.
magnitudeEnergy += (double)magnitude * (double)magnitude;
// Unwrap phase: accumulate phase changes
float unwrappedPhase = phase;
if (tInBand > 0)
{
float prevPhase = previousPhases[ch][bandIdx][tInBand - 1];
float phaseDiff = phase - std::fmod(prevPhase, 2.0f * M_PI);
// Normalize phase difference to [-pi, pi]
while (phaseDiff > M_PI)
phaseDiff -= 2.0f * M_PI;
while (phaseDiff < -M_PI)
phaseDiff += 2.0f * M_PI;
unwrappedPhase = prevPhase + phaseDiff;
}
previousPhases[ch][bandIdx][tInBand] = unwrappedPhase;
size_t writeOffset = baseOffset * floatsPerPixel;
data[writeOffset + ch * 2 + 0] = magnitude;
data[writeOffset + ch * 2 + 1] = unwrappedPhase;
},
bandBegin, analyzer.bandpass_bands_end(), 0, numFrames, allCoefs[ch]);
}
}
void OnOK()
{
Napi::Env env = Env();
Napi::HandleScope scope(env);
Napi::Object resultJs = Napi::Object::New(env);
Napi::Float32Array dataJs = Napi::Float32Array::New(env, data.size());
memcpy(dataJs.Data(), data.data(), data.size() * sizeof(float));
resultJs.Set("data", dataJs);
Napi::Float32Array inverseMapJs = Napi::Float32Array::New(env, inverseMap.size());
memcpy(inverseMapJs.Data(), inverseMap.data(), inverseMap.size() * sizeof(float));
resultJs.Set("inverseMap", inverseMapJs);
Napi::Float32Array metadataJs = Napi::Float32Array::New(env, metadata.size());
memcpy(metadataJs.Data(), metadata.data(), metadata.size() * sizeof(float));
resultJs.Set("metadata", metadataJs);
resultJs.Set("textureWidth", Napi::Number::New(env, textureWidth));
resultJs.Set("textureHeight", Napi::Number::New(env, textureHeight));
resultJs.Set("numFrames", Napi::Number::New(env, numFrames));
resultJs.Set("numChannels", Napi::Number::New(env, channels));
resultJs.Set("numBands", Napi::Number::New(env, numBands));
resultJs.Set("sampleRate", Napi::Number::New(env, sampleRate));
resultJs.Set("magnitudeEnergy", Napi::Number::New(env, magnitudeEnergy));
Napi::Uint32Array bandOffsetsJs = Napi::Uint32Array::New(env, bandOffsets.size());
memcpy(bandOffsetsJs.Data(), bandOffsets.data(), bandOffsets.size() * sizeof(uint32_t));
resultJs.Set("bandOffsets", bandOffsetsJs);
Napi::Int32Array bandStepLog2sJs = Napi::Int32Array::New(env, bandStepLog2s.size());
memcpy(bandStepLog2sJs.Data(), bandStepLog2s.data(), bandStepLog2s.size() * sizeof(int32_t));
resultJs.Set("bandStepLog2s", bandStepLog2sJs);
Napi::Float32Array bandFreqsHzJs = Napi::Float32Array::New(env, bandFreqsHz.size());
memcpy(bandFreqsHzJs.Data(), bandFreqsHz.data(), bandFreqsHz.size() * sizeof(float));
resultJs.Set("bandFreqsHz", bandFreqsHzJs);
Napi::Uint32Array bandLengthsJs = Napi::Uint32Array::New(env, bandLengths.size());
memcpy(bandLengthsJs.Data(), bandLengths.data(), bandLengths.size() * sizeof(uint32_t));
resultJs.Set("bandLengths", bandLengthsJs);
deferred.Resolve(resultJs);
}
void OnError(const Napi::Error &e)
{
deferred.Reject(e.Value());
}
Napi::Promise GetPromise() { return deferred.Promise(); }
private:
Napi::Promise::Deferred deferred;
std::vector<Napi::Reference<Napi::Float32Array>> audioRefs;
std::vector<const float *> audioChannels;
int channels;
double sampleRate;
int bandsPerOctave;
double fminHz;
// Results
std::vector<float> data;
std::vector<float> inverseMap;
std::vector<float> metadata;
int textureWidth;
int textureHeight;
size_t numFrames;
int numBands;
std::vector<uint32_t> bandOffsets;
std::vector<int32_t> bandStepLog2s;
std::vector<uint32_t> bandLengths;
std::vector<float> bandFreqsHz;
double magnitudeEnergy = 0.0;
};
Napi::Value AnalyzeAsync(const Napi::CallbackInfo &info)
{
Napi::Env env = info.Env();
if (info.Length() < 4 || !info[0].IsArray() || !info[1].IsNumber() || !info[2].IsNumber() || !info[3].IsObject())
{
Napi::TypeError::New(env, "Expected: channelArrays (Array of Float32Arrays), channels (Number), sampleRate (Number), params (Object)").ThrowAsJavaScriptException();
return env.Null();
}
Napi::Array planarInput = info[0].As<Napi::Array>();
int channels = info[1].As<Napi::Number>().Int32Value();
double sampleRate = info[2].As<Napi::Number>().DoubleValue();
Napi::Object paramsJs = info[3].As<Napi::Object>();
if (!paramsJs.Has("bandsPerOctave") || !paramsJs.Get("bandsPerOctave").IsNumber())
{
Napi::TypeError::New(env, "params.bandsPerOctave is missing or not a number").ThrowAsJavaScriptException();
return env.Null();
}
if (!paramsJs.Has("minFreq") || !paramsJs.Get("minFreq").IsNumber())
{
Napi::TypeError::New(env, "params.minFreq is missing or not a number").ThrowAsJavaScriptException();
return env.Null();
}
if (channels <= 0 || channels > 2)
{
Napi::TypeError::New(env, "Number of channels must be 1 or 2.").ThrowAsJavaScriptException();
return env.Null();
}
AnalyzeWorker *worker = new AnalyzeWorker(env, planarInput, channels, sampleRate, paramsJs);
worker->Queue();
return worker->GetPromise();
}
class SynthesizeWorker : public Napi::AsyncWorker
{
public:
SynthesizeWorker(Napi::Env env,
const Napi::Float32Array &inputDataJs,
const Napi::Object &analysisObj,
double sampleRate,
const Napi::Object ¶msJs,
bool applyLimiter,
const Napi::Array &existingAudioJs,
int64_t startFrame,
int64_t endFrame,
int64_t startBand,
int64_t endBand)
: Napi::AsyncWorker(env), deferred(Napi::Promise::Deferred::New(env)), sampleRate(sampleRate), applyLimiter(applyLimiter),
requestedStartFrame(startFrame), requestedEndFrame(endFrame), requestedStartBand(startBand), requestedEndBand(endBand)
{
// Hold the packed FBO buffer by reference and read it straight from its
// backing store on the worker thread. The reference keeps the JS array
// alive across the async boundary; the caller does not mutate it while
// synthesis is in flight, so the worker reads it without a copy.
inputDataRef = Napi::Reference<Napi::Float32Array>::New(inputDataJs, 1);
inputData = inputDataJs.Data();
inputDataLen = inputDataJs.ElementLength();
numFrames = analysisObj.Get("numFrames").As<Napi::Number>().Int64Value();
channels = analysisObj.Get("numChannels").As<Napi::Number>().Int32Value();
numBands = analysisObj.Get("numBands").As<Napi::Number>().Int32Value();
Napi::Uint32Array bandOffsetsJs = analysisObj.Get("bandOffsets").As<Napi::Uint32Array>();
bandOffsets.assign(bandOffsetsJs.Data(), bandOffsetsJs.Data() + bandOffsetsJs.ElementLength());
Napi::Uint32Array bandLengthsJs = analysisObj.Get("bandLengths").As<Napi::Uint32Array>();
bandLengths.assign(bandLengthsJs.Data(), bandLengthsJs.Data() + bandLengthsJs.ElementLength());
Napi::Int32Array bandStepLog2sJs = analysisObj.Get("bandStepLog2s").As<Napi::Int32Array>();
bandStepLog2s.assign(bandStepLog2sJs.Data(), bandStepLog2sJs.Data() + bandStepLog2sJs.ElementLength());
bandsPerOctave = paramsJs.Get("bandsPerOctave").As<Napi::Number>().Int32Value();
fminHz = paramsJs.Get("minFreq").As<Napi::Number>().DoubleValue();
// Reference the existing audio channels (for partial synthesis with
// crossfade) and read them by pointer on the worker thread, same as the
// packed buffer.
if (existingAudioJs.Length() > 0)
{
uint32_t len = existingAudioJs.Length();
existingAudio.reserve(len);
existingAudioLens.reserve(len);
existingAudioRefs.reserve(len);
for (uint32_t i = 0; i < len; i++)
{
Napi::Float32Array channelJs = existingAudioJs.Get(i).As<Napi::Float32Array>();
existingAudioRefs.push_back(Napi::Reference<Napi::Float32Array>::New(channelJs, 1));
existingAudio.push_back(channelJs.Data());
existingAudioLens.push_back(channelJs.ElementLength());
}
}
}
~SynthesizeWorker() {}
void Execute()
{
DEBUG_LOG << "[C++] Execute() started" << std::endl << std::flush;
DEBUG_LOG << "[C++] requestedStartFrame=" << requestedStartFrame << ", requestedEndFrame=" << requestedEndFrame << std::endl << std::flush;
DEBUG_LOG << "[C++] requestedStartBand=" << requestedStartBand << ", requestedEndBand=" << requestedEndBand << std::endl << std::flush;
DEBUG_LOG << "[C++] numFrames=" << numFrames << ", channels=" << channels << ", numBands=" << numBands << std::endl << std::flush;
DEBUG_LOG << "[C++] existingAudio.size()=" << existingAudio.size() << std::endl << std::flush;
double fminFrac = fminHz / sampleRate;
gaborator::log_fq_scale scale(bandsPerOctave, fminFrac);
gaborator::parameters params(scale, OVERLAP);
params.phase = gaborator::coef_phase::global;
gaborator::analyzer<float> analyzer(params);
DEBUG_LOG << "[C++] Analyzer created" << std::endl << std::flush;
int band_begin = analyzer.bandpass_bands_begin();
int band_end = analyzer.bandpass_bands_end();
DEBUG_LOG << "[C++] band_begin=" << band_begin << ", band_end=" << band_end << std::endl << std::flush;
// Check if we're doing partial synthesis (have existing audio and frame range specified)
bool isPartialSynthesis = !existingAudio.empty() && requestedStartFrame >= 0 && requestedEndFrame > requestedStartFrame;
// Calculate synthesis support based on the bands that were modified
int64_t synthesisSupportSamples;
if (isPartialSynthesis && requestedStartBand >= 0 && requestedEndBand > requestedStartBand)
{
// Use band-specific support for only the modified bands
double maxSupport = 0.0;
int actualStartBand = std::max(0, static_cast<int>(requestedStartBand));
int actualEndBand = std::min(numBands, static_cast<int>(requestedEndBand));
for (int b = actualStartBand; b < actualEndBand; b++)
{
double support = analyzer.band_synthesis_support(b + band_begin);
maxSupport = std::max(maxSupport, support);
}
synthesisSupportSamples = static_cast<int64_t>(std::ceil(maxSupport));
DEBUG_LOG << "[C++] Band-specific support for bands " << actualStartBand << "-" << actualEndBand << ": " << synthesisSupportSamples << std::endl << std::flush;
}
else
{
// Use global maximum support
synthesisSupportSamples = static_cast<int64_t>(std::ceil(analyzer.synthesis_support()));
}
// Cap synthesis support at 0.1 seconds
int64_t maxSupportSamples = static_cast<int64_t>(sampleRate * 0.1);
synthesisSupportSamples = std::min(synthesisSupportSamples, maxSupportSamples);
DEBUG_LOG << "[C++] synthesisSupportSamples (capped at " << maxSupportSamples << "): " << synthesisSupportSamples << std::endl << std::flush;
// Crossfade duration: 10ms
int64_t crossfadeSamples = static_cast<int64_t>(sampleRate * 0.01);
DEBUG_LOG << "[C++] crossfadeSamples: " << crossfadeSamples << std::endl << std::flush;
int64_t synthStart, synthEnd;
size_t floatsPerPixel = 4;
if (isPartialSynthesis)
{
// Partial synthesis: synthesize just the dirty region with margin
synthStart = std::max(int64_t(0), requestedStartFrame - synthesisSupportSamples);
synthEnd = std::min(static_cast<int64_t>(numFrames), requestedEndFrame + synthesisSupportSamples);
}
else
{
// Full synthesis
synthStart = 0;
synthEnd = static_cast<int64_t>(numFrames);
}
DEBUG_LOG << "[C++] synthStart=" << synthStart << ", synthEnd=" << synthEnd << std::endl << std::flush;
// Calculate fill range - for partial synthesis, only fill the time range we need
// Add extra margin for the fill to ensure synthesis has all needed coefficients
int64_t fillStart = 0;
int64_t fillEnd = static_cast<int64_t>(numFrames);
if (isPartialSynthesis)
{
// Use a generous margin for fill (2x synthesis support) to ensure all needed coefficients
int64_t fillMargin = synthesisSupportSamples * 2;
fillStart = std::max(int64_t(0), synthStart - fillMargin);
fillEnd = std::min(static_cast<int64_t>(numFrames), synthEnd + fillMargin);
DEBUG_LOG << "[C++] Partial fill range: " << fillStart << " to " << fillEnd << " (vs full: 0 to " << numFrames << ")" << std::endl << std::flush;
}
// Fill and synthesize
std::vector<std::vector<float>> synthesizedBuffers(channels);
for (int ch = 0; ch < channels; ++ch)
{
DEBUG_LOG << "[C++] Processing channel " << ch << std::endl << std::flush;
gaborator::coefs<float> channelCoefs(analyzer);
// Fill coefficients for the required range
gaborator::fill(
[&](int b, int64_t t, std::complex<float> &coef)
{
int band_idx = b - band_begin;
if (band_idx < 0 || band_idx >= numBands)
{
coef = {0.0f, 0.0f};
return;
}
int64_t t_in_band = t >> bandStepLog2s[band_idx];
if (t_in_band < 0 || (size_t)t_in_band >= (size_t)bandLengths[band_idx])
{
coef = {0.0f, 0.0f};
return;
}
size_t base_offset = bandOffsets[band_idx] + t_in_band;
size_t readOffset = base_offset * floatsPerPixel;
size_t maxReadIndex = readOffset + ch * 2 + 1;
if (maxReadIndex >= inputDataLen)
{
coef = {0.0f, 0.0f};
return;
}
float magnitude = inputData[readOffset + ch * 2 + 0];
float unwrappedPhase = inputData[readOffset + ch * 2 + 1];
float real = magnitude * std::cos(unwrappedPhase);
float imag = magnitude * std::sin(unwrappedPhase);
coef.real(real);
coef.imag(imag);
},
band_begin, band_end, fillStart, fillEnd, channelCoefs);
// Synthesize the required range
size_t synthLength = static_cast<size_t>(synthEnd - synthStart);
synthesizedBuffers[ch].resize(synthLength);
analyzer.synthesize(channelCoefs, synthStart, synthEnd, synthesizedBuffers[ch].data());
DEBUG_LOG << "[C++] Channel " << ch << " - synthesized " << synthLength << " samples" << std::endl << std::flush;
}
// Prepare output
audioChannels.resize(channels);
if (isPartialSynthesis)
{
// Partial synthesis: crossfade-splice into existing audio
DEBUG_LOG << "[C++] Doing partial synthesis with crossfade splice" << std::endl << std::flush;
for (int ch = 0; ch < channels; ++ch)
{
// Start with copy of existing audio
audioChannels[ch].assign(existingAudio[ch], existingAudio[ch] + existingAudioLens[ch]);
// Apply crossfade at boundaries. Skip the fade at absolute file
// boundaries — there is no seam with surrounding audio there, so
// fading would leak the un-modified original samples through.
int64_t fadeInStart = synthStart;
int64_t fadeInEnd = (synthStart == 0)
? synthStart
: std::min(synthStart + crossfadeSamples, synthEnd);
int64_t fadeOutEnd = synthEnd;
int64_t fadeOutStart = (synthEnd == static_cast<int64_t>(numFrames))
? synthEnd
: std::max(synthEnd - crossfadeSamples, synthStart);
for (int64_t i = synthStart; i < synthEnd; ++i)
{
size_t synthIdx = static_cast<size_t>(i - synthStart);
float newSample = synthesizedBuffers[ch][synthIdx];
float oldSample = existingAudio[ch][i];
float blend = 1.0f; // Default: use new sample fully
// Fade-in at start
if (i >= fadeInStart && i < fadeInEnd && fadeInEnd > fadeInStart)
{
float fadeProgress = static_cast<float>(i - fadeInStart) / static_cast<float>(fadeInEnd - fadeInStart);
blend = fadeProgress;
}
// Fade-out at end
else if (i >= fadeOutStart && i < fadeOutEnd && fadeOutEnd > fadeOutStart)
{
float fadeProgress = static_cast<float>(i - fadeOutStart) / static_cast<float>(fadeOutEnd - fadeOutStart);
blend = 1.0f - fadeProgress;
}
// Crossfade blend
audioChannels[ch][i] = oldSample * (1.0f - blend) + newSample * blend;
}
DEBUG_LOG << "[C++] Channel " << ch << " - crossfade splice complete" << std::endl << std::flush;
}
}
else
{
// Full synthesis: just use synthesized buffers directly
for (int ch = 0; ch < channels; ++ch)
{
audioChannels[ch] = std::move(synthesizedBuffers[ch]);
}
}
// Limit the fully assembled buffer in one pass so the gain envelope is
// continuous across the whole file — limiting the dirty block alone would
// leave a gain discontinuity where it meets the surrounding audio. Existing
// audio is already at or below the ceiling, so it passes through unchanged.
// The flag lets the caller bypass the limiter.
std::vector<float> gainEnv;
if (applyLimiter)
applyLookaheadLimiter(audioChannels, sampleRate, 40.0f, 200.0f, &gainEnv);
// Downsample the applied gain into a compact per-file gain-reduction
// envelope (dB of reduction, >= 0) for the meter. Each point holds the
// worst reduction over a ~5 ms hop so brief dips stay visible, and the
// points span the whole buffer evenly so the renderer can index it by
// playback fraction.
gainReductionDb.clear();
maxGainReductionDb = 0.0f;
if (!gainEnv.empty())
{
const int hop = std::max(1, static_cast<int>(std::lround(sampleRate * 0.005)));
const size_t points = (gainEnv.size() + hop - 1) / hop;
gainReductionDb.resize(points);
float minGain = 1.0f;
for (size_t p = 0; p < points; ++p)
{
const size_t start = p * static_cast<size_t>(hop);
const size_t end = std::min(gainEnv.size(), start + static_cast<size_t>(hop));
float lo = 1.0f;
for (size_t i = start; i < end; ++i)
lo = std::min(lo, gainEnv[i]);
minGain = std::min(minGain, lo);
gainReductionDb[p] = lo < 1.0f ? -20.0f * std::log10(lo) : 0.0f;
}
maxGainReductionDb = minGain < 1.0f ? -20.0f * std::log10(minGain) : 0.0f;
}
// Compute peak of the complete, limited buffer.
peakValue = 0.0f;
for (const auto &channel_data : audioChannels)
{
for (float sample : channel_data)
{
peakValue = std::max(peakValue, std::abs(sample));
}
}
DEBUG_LOG << "[C++] Peak value: " << peakValue << std::endl << std::flush;
DEBUG_LOG << "[C++] Execute() complete" << std::endl << std::flush;
}
void OnOK()
{
Napi::Env env = Env();
Napi::HandleScope scope(env);
Napi::Object result = Napi::Object::New(env);
Napi::Array outputChannels = Napi::Array::New(env, channels);
for (int ch = 0; ch < channels; ++ch)
{
size_t outputLength = audioChannels[ch].size();
Napi::Float32Array channelBuffer = Napi::Float32Array::New(env, outputLength);
memcpy(channelBuffer.Data(), audioChannels[ch].data(), outputLength * sizeof(float));
outputChannels[ch] = channelBuffer;
}
result.Set("channels", outputChannels);
result.Set("peak", Napi::Number::New(env, peakValue));
Napi::Float32Array grBuffer = Napi::Float32Array::New(env, gainReductionDb.size());
if (!gainReductionDb.empty())
memcpy(grBuffer.Data(), gainReductionDb.data(), gainReductionDb.size() * sizeof(float));
result.Set("gainReductionDb", grBuffer);
result.Set("maxGainReductionDb", Napi::Number::New(env, maxGainReductionDb));
deferred.Resolve(result);
}
void OnError(const Napi::Error &e)
{
deferred.Reject(e.Value());
}
Napi::Promise GetPromise() { return deferred.Promise(); }
private:
Napi::Promise::Deferred deferred;
// Input data, referenced in place rather than copied. The References keep the
// JS backing buffers alive while Execute() reads them off the main thread.
Napi::Reference<Napi::Float32Array> inputDataRef;
const float *inputData = nullptr;
size_t inputDataLen = 0;
double sampleRate;
bool applyLimiter;
size_t numFrames;
int channels;
int numBands;
std::vector<uint32_t> bandOffsets;
std::vector<uint32_t> bandLengths;
std::vector<int32_t> bandStepLog2s;
int bandsPerOctave;
double fminHz;
int64_t requestedStartFrame;
int64_t requestedEndFrame;
int64_t requestedStartBand;
int64_t requestedEndBand;
std::vector<Napi::Reference<Napi::Float32Array>> existingAudioRefs;
std::vector<const float *> existingAudio;
std::vector<size_t> existingAudioLens;
// Results
std::vector<std::vector<float>> audioChannels;
float peakValue = 0.0f;
std::vector<float> gainReductionDb;
float maxGainReductionDb = 0.0f;
};
Napi::Value SynthesizeAsync(const Napi::CallbackInfo &info)
{
Napi::Env env = info.Env();
if (info.Length() < 6 || !info[0].IsTypedArray() || !info[1].IsObject() || !info[2].IsNumber() || !info[3].IsObject() || !info[4].IsBoolean() || !info[5].IsArray())
{
Napi::TypeError::New(env, "Expected: data (TypedArray), analysisObject (Object), sampleRate (Number), params (Object), applyLimiter (Boolean), existingAudio (Array), [startFrame], [endFrame], [startBand], [endBand]").ThrowAsJavaScriptException();
return env.Null();
}
Napi::Float32Array inputDataJs = info[0].As<Napi::Float32Array>();
Napi::Object analysisObj = info[1].As<Napi::Object>();
double sampleRate = info[2].As<Napi::Number>().DoubleValue();
Napi::Object paramsJs = info[3].As<Napi::Object>();
bool applyLimiter = info[4].As<Napi::Boolean>().Value();
Napi::Array existingAudioJs = info[5].As<Napi::Array>();
// Optional start/end frame and band for partial synthesis (-1 means full range)
int64_t startFrame = -1;
int64_t endFrame = -1;
int64_t startBand = -1;
int64_t endBand = -1;
if (info.Length() > 6 && info[6].IsNumber())
{
startFrame = info[6].As<Napi::Number>().Int64Value();
}
if (info.Length() > 7 && info[7].IsNumber())
{
endFrame = info[7].As<Napi::Number>().Int64Value();
}
if (info.Length() > 8 && info[8].IsNumber())
{
startBand = info[8].As<Napi::Number>().Int64Value();
}
if (info.Length() > 9 && info[9].IsNumber())
{
endBand = info[9].As<Napi::Number>().Int64Value();
}
if (!paramsJs.Has("bandsPerOctave") || !paramsJs.Get("bandsPerOctave").IsNumber())
{
Napi::TypeError::New(env, "params.bandsPerOctave is missing or not a number").ThrowAsJavaScriptException();
return env.Null();
}
if (!paramsJs.Has("minFreq") || !paramsJs.Get("minFreq").IsNumber())
{
Napi::TypeError::New(env, "params.minFreq is missing or not a number").ThrowAsJavaScriptException();
return env.Null();
}
SynthesizeWorker *worker = new SynthesizeWorker(env, inputDataJs, analysisObj, sampleRate, paramsJs, applyLimiter, existingAudioJs, startFrame, endFrame, startBand, endBand);
worker->Queue();
return worker->GetPromise();
}
// ─── HPSS helpers ────────────────────────────────────────────────────────────
// O(n) median via nth_element; modifies v in-place
static float medianInPlace(std::vector<float> &v)
{
if (v.empty())
return 0.0f;
size_t mid = v.size() / 2;
std::nth_element(v.begin(), v.begin() + mid, v.end());
if (v.size() % 2 == 1)
return v[mid];
float hi = v[mid];
std::nth_element(v.begin(), v.begin() + mid - 1, v.end());
return (v[mid - 1] + hi) * 0.5f;
}
// Sliding-window 1-D median filter along the time axis for a single band.
// Boundary condition: clamp (reflect-zero).
static std::vector<float> timeMedianFilter(const std::vector<float> &band, int kernel)
{
int L = (int)band.size();
int half = kernel / 2;
std::vector<float> result(L);
std::vector<float> window;
window.reserve(kernel);
for (int t = 0; t < L; ++t)
{
window.clear();
for (int dt = -half; dt <= half; ++dt)
{
int idx = std::max(0, std::min(L - 1, t + dt));
window.push_back(band[idx]);
}
result[t] = medianInPlace(window);
}
return result;
}
// Median filter across adjacent frequency bands at each time position.
// Adjacent bands are aligned by normalised time (0-1) and nearest-sample lookup.
static std::vector<std::vector<float>> freqMedianFilter(
const std::vector<std::vector<float>> &mags,
const std::vector<uint32_t> &bandLengths,
int numBands, int kernel)
{
int half = kernel / 2;
std::vector<std::vector<float>> P(numBands);
std::vector<float> window;
window.reserve(kernel);
for (int b = 0; b < numBands; ++b)
{
int L = (int)bandLengths[b];
P[b].resize(L);
for (int t = 0; t < L; ++t)
{
float normTime = (L > 1) ? (float)t / (float)(L - 1) : 0.0f;
window.clear();
for (int db = -half; db <= half; ++db)
{
int nb = b + db;
if (nb < 0 || nb >= numBands)
continue;
int nbL = (int)bandLengths[nb];
int nbT = (nbL > 1)
? std::min((int)std::round(normTime * (float)(nbL - 1)), nbL - 1)
: 0;
window.push_back(mags[nb][nbT]);
}
P[b][t] = medianInPlace(window);
}
}
return P;
}
// ─── HpssWorker ──────────────────────────────────────────────────────────────
class HpssWorker : public Napi::AsyncWorker
{
public:
HpssWorker(Napi::Env env,
Napi::Float32Array packedDataJs,
Napi::Object metaJs,
int kernelH, int kernelV)
: Napi::AsyncWorker(env),
deferred(Napi::Promise::Deferred::New(env)),
kernelH(kernelH), kernelV(kernelV)
{
packedData.assign(packedDataJs.Data(),
packedDataJs.Data() + packedDataJs.ElementLength());
numBands = metaJs.Get("numBands").As<Napi::Number>().Int32Value();
numChannels = metaJs.Get("numChannels").As<Napi::Number>().Int32Value();
Napi::Uint32Array bo = metaJs.Get("bandOffsets").As<Napi::Uint32Array>();
bandOffsets.assign(bo.Data(), bo.Data() + bo.ElementLength());
Napi::Uint32Array bl = metaJs.Get("bandLengths").As<Napi::Uint32Array>();
bandLengths.assign(bl.Data(), bl.Data() + bl.ElementLength());
}