-
Notifications
You must be signed in to change notification settings - Fork 5
/
binaural-modeled.umd.js
1382 lines (1196 loc) · 115 KB
/
binaural-modeled.umd.js
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
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.BinauralModeled = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
module.exports = require('./dist/binaural-modeled');
},{"./dist/binaural-modeled":2}],2:[function(require,module,exports){
/**
* @fileOverview
*
* @author Arnau Julià <[email protected]>
* @version 0.1.0
*/
'use strict';
var _createClass = require('babel-runtime/helpers/create-class')['default'];
var _classCallCheck = require('babel-runtime/helpers/class-call-check')['default'];
var _interopRequireDefault = require('babel-runtime/helpers/interop-require-default')['default'];
Object.defineProperty(exports, '__esModule', {
value: true
});
var _kdt = require('kdt');
var _kdt2 = _interopRequireDefault(_kdt);
var _biquadFilter = require('biquad-filter');
var _biquadFilter2 = _interopRequireDefault(_biquadFilter);
var _fractionalDelay = require('fractional-delay');
var _fractionalDelay2 = _interopRequireDefault(_fractionalDelay);
/**
* @class BinauralModeled
*/
var BinauralModeled = (function () {
/**
* Constructor
*/
function BinauralModeled(options) {
_classCallCheck(this, BinauralModeled);
this.audioContext = options.audioContext;
// Private properties
this.hrtfDataset = undefined;
this.hrtfDatasetLength = undefined;
this.nextPosition = [];
this.changeWhenFinishCrossfading = false;
this.position = [];
this.crossfadeDuration = 20 / 1000;
this.bufferSize = 1024;
this.tree = -1;
this.input = this.audioContext.createGain();
this.state = "A"; // States in ["A", "B", "A2B", "B2A"]
this.target = undefined;
this.pendingPosition = undefined;
this.convolverA = new ProcessingAudioGraph({
audioContext: this.audioContext
});
this.convolverA.gain.value = 1;
this.input.connect(this.convolverA.input);
this.convolverB = new ProcessingAudioGraph({
audioContext: this.audioContext
});
this.convolverB.gain.value = 0;
this.input.connect(this.convolverB.input);
this.sampleRate = this.audioContext.sampleRate;
}
/**
* AudioGraph sub audio graph object as an ECMAScript5 properties object.
*/
/**
* Connects the binauralModeledNode to the Web Audio graph
* @public
* @param node Destination node
*/
_createClass(BinauralModeled, [{
key: 'connect',
value: function connect(node) {
// this.mainAudioGraph.connect(node);
// this.secondaryAudioGraph.connect(node);
this.convolverA.connect(node);
this.convolverB.connect(node);
return this;
}
/**
* Disconnect the binauralModeledNode from the Web Audio graph
* @public
* @param node Destination node
*/
}, {
key: 'disconnect',
value: function disconnect(node) {
// this.mainAudioGraph.disconnect(node);
// this.secondaryAudioGraph.disconnect(node);
this.convolverA.disconnect(node);
this.convolverB.disconnect(node);
return this;
}
/**
* Set HRTF Dataset to be used with the virtual source.
* @public
* @param hrtfDataset Array of Objects containing the azimuth, distance, elevation, url and buffer for each point
*/
}, {
key: 'distance',
/**
* Calculate the distance between two points in a 3-D space.
* @private
* @param a Object containing three properties: x, y, z
* @param b Object containing three properties: x, y, z
*/
value: function distance(a, b) {
// No need to compute square root here for distance comparison, this is more eficient.
return Math.pow(a.x - b.x, 2) + Math.pow(a.y - b.y, 2) + Math.pow(a.z - b.z, 2);
}
/**
* Set position of the virtual source
* @public
* @param azimuth Azimuth in degrees (°): from 0 to -180 for source on your left, and from 0 to 180 for source on your right
* @param elevation Elevation in degrees (°): from 0 to 90 for source above your head, 0 for source in front of your head, and from 0 to -90 for source below your head)
* @param distance Distance in meters
*/
}, {
key: 'setPosition',
value: function setPosition(azimuth, elevation, distance) {
// Calculate the nearest position for the input azimuth, elevation and distance
var nearestPosition = this.getRealCoordinates(azimuth, elevation, distance);
if (nearestPosition.azimuth !== this.position.azimuth || nearestPosition.elevation !== this.position.elevation || nearestPosition.distance !== this.position.distance) {
switch (this.state) {
case "A":
this.state = "A2B";
this.pendingPosition = undefined;
this._crossfadeTo("B", nearestPosition);
break;
case "B":
this.state = "B2A";
this.pendingPosition = undefined;
this._crossfadeTo("A", nearestPosition);
break;
case "A2B":
this.pendingPosition = nearestPosition;
break;
case "B2A":
this.pendingPosition = nearestPosition;
break;
}
}
}
}, {
key: '_crossfadeTo',
value: function _crossfadeTo(target, position) {
// Set the new target position
this.position = position;
this.target = target;
var hrtf = this.getHRTF(this.position.azimuth, this.position.elevation, this.position.distance);
var now = this.audioContext.currentTime;
var next = now + this.crossfadeDuration;
switch (this.target) {
case "A":
this.convolverA.setCoefficients(hrtf.iir_coeffs_left, hrtf.iir_coeffs_right);
this.convolverA.setDelay(hrtf.itd / 1000);
this.convolverB.gain.linearRampToValueAtTime(0, next);
this.convolverA.gain.linearRampToValueAtTime(1, next);
break;
case "B":
this.convolverB.setCoefficients(hrtf.iir_coeffs_left, hrtf.iir_coeffs_right);
this.convolverB.setDelay(hrtf.itd / 1000);
this.convolverA.gain.linearRampToValueAtTime(0, next);
this.convolverB.gain.linearRampToValueAtTime(1, next);
break;
}
// Trigger event when linearRamp is reached
function endRamp(tg) {
if (tg.audioContext.currentTime > next) {
window.clearInterval(intervalID);
// Target state is reached
tg.state = tg.target;
tg.target = undefined;
// Trigger if there is a pending position
if (tg.pendingPosition) {
tg.setPosition(tg.pendingPosition.azimuth, tg.pendingPosition.elevation, tg.pendingPosition.distance);
}
}
}
var intervalID = window.setInterval(endRamp, 10, this);
}
/**
* Get the current position of the virtual source.
* @public
*/
}, {
key: 'getPosition',
value: function getPosition() {
return this.position;
}
/**
* Pause playing.
* @public
*/
}, {
key: 'setCrossfadeDuration',
value: function setCrossfadeDuration(msRamp) {
//save in seconds
this.crossfadeDuration = msRamp / 1000;
}
/**
* Seek buffer position (in sec).
* @public
*/
}, {
key: 'getCrossfadeDuration',
value: function getCrossfadeDuration() {
//return in ms
return this.crossfadeDuration * 1000;
}
/**
* Get the HRTF file for an especific position
* @private
* @param azimuth Azimuth in degrees (°): from 0 to -180 for source on your left, and from 0 to 180 for source on your right
* @param elevation Elevation in degrees (°): from 0 to 90 for source above your head, 0 for source in front of your head, and from 0 to -90 for source below your head)
* @param distance Distance in meters
*/
}, {
key: 'getHRTF',
value: function getHRTF(azimuth, elevation, distance) {
var nearest = this.getNearestPoint(azimuth, elevation, distance);
var hrtf = [];
hrtf.iir_coeffs_left = nearest.iir_coeffs_left;
hrtf.iir_coeffs_right = nearest.iir_coeffs_right;
hrtf.itd = nearest.itd;
// Return hrtf data of nearest position for the input values
return hrtf;
}
/**
* Transform the spherical to cartesian coordinates.
* @private
* @param azimuth Azimuth in radians
* @param elevation Elevation in radians
* @param distance Distance in meters
*/
}, {
key: 'sphericalToCartesian',
value: function sphericalToCartesian(azimuth, elevation, distance) {
return {
x: distance * Math.sin(azimuth),
y: distance * Math.cos(azimuth),
z: distance * Math.sin(elevation)
};
}
/**
* Get the nearest position for an input position.
* @private
* @param azimuth Azimuth in degrees (°): from 0 to -180 for source on your left, and from 0 to 180 for source on your right
* @param elevation Elevation in degrees (°): from 0 to 90 for source above your head, 0 for source in front of your head, and from 0 to -90 for source below your head)
* @param distance Distance in meters
*/
}, {
key: 'getRealCoordinates',
value: function getRealCoordinates(azimuth, elevation, distance) {
var nearest = this.getNearestPoint(azimuth, elevation, distance);
// Return azimuth, elevation and distance of nearest position for the input values
return {
azimuth: nearest.azimuth,
elevation: nearest.elevation,
distance: nearest.distance
};
}
/**
* Get the nearest position for an input position.
* @private
* @param azimuth Azimuth in degrees (°): from 0 to -180 for source on your left, and from 0 to 180 for source on your right
* @param elevation Elevation in degrees (°): from 0 to 90 for source above your head, 0 for source in front of your head, and from 0 to -90 for source below your head)
* @param distance Distance in meters
*/
}, {
key: 'getNearestPoint',
value: function getNearestPoint(azimuth, elevation, distance) {
// Degrees to radians for the azimuth and elevation
var azimuthRadians = azimuth * Math.PI / 180;
var elevationRadians = elevation * Math.PI / 180;
// Convert spherical coordinates to cartesian
var cartesianCoord = this.sphericalToCartesian(azimuthRadians, elevationRadians, distance);
// Get the nearest HRTF file for the desired position
var nearest = this.tree.nearest(cartesianCoord, 1)[0];
return nearest[0];
}
}, {
key: 'HRTFDataset',
set: function set(hrtfDataset) {
this.hrtfDataset = hrtfDataset;
this.hrtfDatasetLength = this.hrtfDataset.length;
for (var i = 0; i < this.hrtfDatasetLength; i++) {
var hrtf = this.hrtfDataset[i];
// Azimuth and elevation to radians
var azimuthRadians = hrtf.azimuth * Math.PI / 180;
var elevationRadians = hrtf.elevation * Math.PI / 180;
var catesianCoord = this.sphericalToCartesian(azimuthRadians, elevationRadians, hrtf.distance);
hrtf.x = catesianCoord.x;
hrtf.y = catesianCoord.y;
hrtf.z = catesianCoord.z;
}
this.tree = _kdt2['default'].createKdTree(this.hrtfDataset, this.distance, ['x', 'y', 'z']);
// Put default values
var hrtfNextPosition = this.getHRTF(0, 0, 1);
this.convolverB.setCoefficients(hrtfNextPosition.iir_coeffs_left, hrtfNextPosition.iir_coeffs_right);
this.convolverB.setDelay(hrtfNextPosition.itd / 1000);
this.convolverA.setCoefficients(hrtfNextPosition.iir_coeffs_left, hrtfNextPosition.iir_coeffs_right);
this.convolverA.setDelay(hrtfNextPosition.itd / 1000);
},
get: function get() {
return this.hrtfDataset;
}
}]);
return BinauralModeled;
})();
exports['default'] = BinauralModeled;
var ProcessingAudioGraph = (function () {
function ProcessingAudioGraph(options) {
_classCallCheck(this, ProcessingAudioGraph);
this.audioContext = options.audioContext;
// Private properties
this.bufferSize = 1024;
// Creations
this.input = this.audioContext.createGain();
this.gainNode = this.audioContext.createGain();
this.biquadFilterLeft = new _biquadFilter2['default']();
this.biquadFilterRight = new _biquadFilter2['default']();
this.fractionalDelayLeft = new _fractionalDelay2['default'](44100);
this.fractionalDelayRight = new _fractionalDelay2['default'](44100);
this.processorNode = this.audioContext.createScriptProcessor(this.bufferSize);
// Connections
this.input.connect(this.processorNode);
this.processorNode.connect(this.gainNode);
// Start processorNode
this.processorNodeFunction();
}
_createClass(ProcessingAudioGraph, [{
key: 'setCoefficients',
/**
* Set coefficients biquad filter
* @public
* @param value AudioBuffer Object.
*/
value: function setCoefficients(leftCoefficients, rightCoefficients) {
this.biquadFilterLeft.setCoefficients(leftCoefficients);
this.biquadFilterRight.setCoefficients(rightCoefficients);
}
/**
* Set buffer and bufferDuration.
* @public
* @chainable
*/
}, {
key: 'setDelay',
value: function setDelay(delay) {
var delayLeft = 1 / 1000 + delay / 2;
var delayRight = 1 / 1000 - delay / 2;
this.fractionalDelayLeft.setDelay(delayLeft);
this.fractionalDelayRight.setDelay(delayRight);
}
}, {
key: 'processorNodeFunction',
value: function processorNodeFunction() {
var that = this;
this.processorNode.onaudioprocess = function (e) {
// Get the inputBuffer
var inputArray = e.inputBuffer.getChannelData(0);
// Get the outputBuffers
var leftOutputArray = e.outputBuffer.getChannelData(0);
var rightOutputArray = e.outputBuffer.getChannelData(1);
// Delay
var mediumArrayLeft = new Float32Array(that.fractionalDelayLeft.process(inputArray));
var mediumArrayRight = new Float32Array(that.fractionalDelayRight.process(inputArray));
// BiquadFilter
that.biquadFilterLeft.process(mediumArrayLeft, leftOutputArray);
that.biquadFilterRight.process(mediumArrayRight, rightOutputArray);
};
}
/**
* Connect the convolverAudioGraph to a node
* @public
* @chainable
* @param node Destination node
*/
}, {
key: 'connect',
value: function connect(node) {
this.gainNode.connect(node);
return this;
}
/**
* Disconnect the convolverAudioGraph to a node
* @public
* @chainable
* @param node Destination node
*/
}, {
key: 'disconnect',
value: function disconnect(node) {
this.gainNode.disconnect(node);
return this;
}
}, {
key: 'gain',
get: function get() {
return this.gainNode.gain;
}
}]);
return ProcessingAudioGraph;
})();
module.exports = exports['default'];
},{"babel-runtime/helpers/class-call-check":4,"babel-runtime/helpers/create-class":5,"babel-runtime/helpers/interop-require-default":6,"biquad-filter":10,"fractional-delay":18,"kdt":9}],3:[function(require,module,exports){
module.exports = { "default": require("core-js/library/fn/object/define-property"), __esModule: true };
},{"core-js/library/fn/object/define-property":7}],4:[function(require,module,exports){
"use strict";
exports["default"] = function (instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
exports.__esModule = true;
},{}],5:[function(require,module,exports){
"use strict";
var _Object$defineProperty = require("babel-runtime/core-js/object/define-property")["default"];
exports["default"] = (function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
_Object$defineProperty(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
})();
exports.__esModule = true;
},{"babel-runtime/core-js/object/define-property":3}],6:[function(require,module,exports){
"use strict";
exports["default"] = function (obj) {
return obj && obj.__esModule ? obj : {
"default": obj
};
};
exports.__esModule = true;
},{}],7:[function(require,module,exports){
var $ = require('../../modules/$');
module.exports = function defineProperty(it, key, desc){
return $.setDesc(it, key, desc);
};
},{"../../modules/$":8}],8:[function(require,module,exports){
var $Object = Object;
module.exports = {
create: $Object.create,
getProto: $Object.getPrototypeOf,
isEnum: {}.propertyIsEnumerable,
getDesc: $Object.getOwnPropertyDescriptor,
setDesc: $Object.defineProperty,
setDescs: $Object.defineProperties,
getKeys: $Object.keys,
getNames: $Object.getOwnPropertyNames,
getSymbols: $Object.getOwnPropertySymbols,
each: [].forEach
};
},{}],9:[function(require,module,exports){
/**
* AUTHOR OF INITIAL JS LIBRARY
* k-d Tree JavaScript - V 1.0
*
* https://github.com/ubilabs/kd-tree-javascript
*
* @author Mircea Pricop <[email protected]>, 2012
* @author Martin Kleppe <[email protected]>, 2012
* @author Ubilabs http://ubilabs.net, 2012
* @license MIT License <http://www.opensource.org/licenses/mit-license.php>
*/
function Node(obj, dimension, parent) {
this.obj = obj;
this.left = null;
this.right = null;
this.parent = parent;
this.dimension = dimension;
}
function KdTree(points, metric, dimensions) {
var self = this;
function buildTree(points, depth, parent) {
var dim = depth % dimensions.length,
median,
node;
if (points.length === 0) {
return null;
}
if (points.length === 1) {
return new Node(points[0], dim, parent);
}
points.sort(function (a, b) {
return a[dimensions[dim]] - b[dimensions[dim]];
});
median = Math.floor(points.length / 2);
node = new Node(points[median], dim, parent);
node.left = buildTree(points.slice(0, median), depth + 1, node);
node.right = buildTree(points.slice(median + 1), depth + 1, node);
return node;
}
this.root = buildTree(points, 0, null);
this.insert = function (point) {
function innerSearch(node, parent) {
if (node === null) {
return parent;
}
var dimension = dimensions[node.dimension];
if (point[dimension] < node.obj[dimension]) {
return innerSearch(node.left, node);
} else {
return innerSearch(node.right, node);
}
}
var insertPosition = innerSearch(this.root, null),
newNode,
dimension;
if (insertPosition === null) {
this.root = new Node(point, 0, null);
return;
}
newNode = new Node(point, (insertPosition.dimension + 1) % dimensions.length, insertPosition);
dimension = dimensions[insertPosition.dimension];
if (point[dimension] < insertPosition.obj[dimension]) {
insertPosition.left = newNode;
} else {
insertPosition.right = newNode;
}
};
this.remove = function (point) {
var node;
function nodeSearch(node) {
if (node === null) {
return null;
}
if (node.obj === point) {
return node;
}
var dimension = dimensions[node.dimension];
if (point[dimension] < node.obj[dimension]) {
return nodeSearch(node.left, node);
} else {
return nodeSearch(node.right, node);
}
}
function removeNode(node) {
var nextNode,
nextObj,
pDimension;
function findMax(node, dim) {
var dimension,
own,
left,
right,
max;
if (node === null) {
return null;
}
dimension = dimensions[dim];
if (node.dimension === dim) {
if (node.right !== null) {
return findMax(node.right, dim);
}
return node;
}
own = node.obj[dimension];
left = findMax(node.left, dim);
right = findMax(node.right, dim);
max = node;
if (left !== null && left.obj[dimension] > own) {
max = left;
}
if (right !== null && right.obj[dimension] > max.obj[dimension]) {
max = right;
}
return max;
}
function findMin(node, dim) {
var dimension,
own,
left,
right,
min;
if (node === null) {
return null;
}
dimension = dimensions[dim];
if (node.dimension === dim) {
if (node.left !== null) {
return findMin(node.left, dim);
}
return node;
}
own = node.obj[dimension];
left = findMin(node.left, dim);
right = findMin(node.right, dim);
min = node;
if (left !== null && left.obj[dimension] < own) {
min = left;
}
if (right !== null && right.obj[dimension] < min.obj[dimension]) {
min = right;
}
return min;
}
if (node.left === null && node.right === null) {
if (node.parent === null) {
self.root = null;
return;
}
pDimension = dimensions[node.parent.dimension];
if (node.obj[pDimension] < node.parent.obj[pDimension]) {
node.parent.left = null;
} else {
node.parent.right = null;
}
return;
}
if (node.left !== null) {
nextNode = findMax(node.left, node.dimension);
} else {
nextNode = findMin(node.right, node.dimension);
}
nextObj = nextNode.obj;
removeNode(nextNode);
node.obj = nextObj;
}
node = nodeSearch(self.root);
if (node === null) { return; }
removeNode(node);
};
this.nearest = function (point, maxNodes, maxDistance) {
var i,
result,
bestNodes;
bestNodes = new BinaryHeap(
function (e) { return -e[1]; }
);
function nearestSearch(node) {
var bestChild,
dimension = dimensions[node.dimension],
ownDistance = metric(point, node.obj),
linearPoint = {},
linearDistance,
otherChild,
i;
function saveNode(node, distance) {
bestNodes.push([node, distance]);
if (bestNodes.size() > maxNodes) {
bestNodes.pop();
}
}
for (i = 0; i < dimensions.length; i += 1) {
if (i === node.dimension) {
linearPoint[dimensions[i]] = point[dimensions[i]];
} else {
linearPoint[dimensions[i]] = node.obj[dimensions[i]];
}
}
linearDistance = metric(linearPoint, node.obj);
if (node.right === null && node.left === null) {
if (bestNodes.size() < maxNodes || ownDistance < bestNodes.peek()[1]) {
saveNode(node, ownDistance);
}
return;
}
if (node.right === null) {
bestChild = node.left;
} else if (node.left === null) {
bestChild = node.right;
} else {
if (point[dimension] < node.obj[dimension]) {
bestChild = node.left;
} else {
bestChild = node.right;
}
}
nearestSearch(bestChild);
if (bestNodes.size() < maxNodes || ownDistance < bestNodes.peek()[1]) {
saveNode(node, ownDistance);
}
if (bestNodes.size() < maxNodes || Math.abs(linearDistance) < bestNodes.peek()[1]) {
if (bestChild === node.left) {
otherChild = node.right;
} else {
otherChild = node.left;
}
if (otherChild !== null) {
nearestSearch(otherChild);
}
}
}
if (maxDistance) {
for (i = 0; i < maxNodes; i += 1) {
bestNodes.push([null, maxDistance]);
}
}
nearestSearch(self.root);
result = [];
for (i = 0; i < maxNodes; i += 1) {
if (bestNodes.content[i][0]) {
result.push([bestNodes.content[i][0].obj, bestNodes.content[i][1]]);
}
}
return result;
};
this.balanceFactor = function () {
function height(node) {
if (node === null) {
return 0;
}
return Math.max(height(node.left), height(node.right)) + 1;
}
function count(node) {
if (node === null) {
return 0;
}
return count(node.left) + count(node.right) + 1;
}
return height(self.root) / (Math.log(count(self.root)) / Math.log(2));
};
}
// Binary heap implementation from:
// http://eloquentjavascript.net/appendix2.html
function BinaryHeap(scoreFunction){
this.content = [];
this.scoreFunction = scoreFunction;
}
BinaryHeap.prototype = {
push: function(element) {
// Add the new element to the end of the array.
this.content.push(element);
// Allow it to bubble up.
this.bubbleUp(this.content.length - 1);
},
pop: function() {
// Store the first element so we can return it later.
var result = this.content[0];
// Get the element at the end of the array.
var end = this.content.pop();
// If there are any elements left, put the end element at the
// start, and let it sink down.
if (this.content.length > 0) {
this.content[0] = end;
this.sinkDown(0);
}
return result;
},
peek: function() {
return this.content[0];
},
remove: function(node) {
var len = this.content.length;
// To remove a value, we must search through the array to find
// it.
for (var i = 0; i < len; i++) {
if (this.content[i] == node) {
// When it is found, the process seen in 'pop' is repeated
// to fill up the hole.
var end = this.content.pop();
if (i != len - 1) {
this.content[i] = end;
if (this.scoreFunction(end) < this.scoreFunction(node))
this.bubbleUp(i);
else
this.sinkDown(i);
}
return;
}
}
throw new Error("Node not found.");
},
size: function() {
return this.content.length;
},
bubbleUp: function(n) {
// Fetch the element that has to be moved.
var element = this.content[n];
// When at 0, an element can not go up any further.
while (n > 0) {
// Compute the parent element's index, and fetch it.
var parentN = Math.floor((n + 1) / 2) - 1,
parent = this.content[parentN];
// Swap the elements if the parent is greater.
if (this.scoreFunction(element) < this.scoreFunction(parent)) {
this.content[parentN] = element;
this.content[n] = parent;
// Update 'n' to continue at the new position.
n = parentN;
}
// Found a parent that is less, no need to move it further.
else {
break;
}
}
},
sinkDown: function(n) {
// Look up the target element and its score.
var length = this.content.length,
element = this.content[n],
elemScore = this.scoreFunction(element);
while(true) {
// Compute the indices of the child elements.
var child2N = (n + 1) * 2, child1N = child2N - 1;
// This is used to store the new position of the element,
// if any.
var swap = null;
// If the first child exists (is inside the array)...
if (child1N < length) {
// Look it up and compute its score.
var child1 = this.content[child1N],
child1Score = this.scoreFunction(child1);
// If the score is less than our element's, we need to swap.
if (child1Score < elemScore)
swap = child1N;
}
// Do the same checks for the other child.
if (child2N < length) {
var child2 = this.content[child2N],
child2Score = this.scoreFunction(child2);
if (child2Score < (swap == null ? elemScore : child1Score)){
swap = child2N;
}
}
// If the element needs to be moved, swap it, and continue.
if (swap != null) {
this.content[n] = this.content[swap];
this.content[swap] = element;
n = swap;
}
// Otherwise, we are done.
else {
break;
}
}
}
};
module.exports = {
createKdTree: function (points, metric, dimensions) {
return new KdTree(points, metric, dimensions)
}
}
},{}],10:[function(require,module,exports){
module.exports = require('./dist/biquad-filter');
},{"./dist/biquad-filter":11}],11:[function(require,module,exports){
/**
* @fileoverview Biquad Filter library
* @author Arnau.Julia <[email protected]>
* @version 0.1.0
*/
/**
* @class BiquadFilter
* @public
*/
"use strict";
var _createClass = require("babel-runtime/helpers/create-class")["default"];
var _classCallCheck = require("babel-runtime/helpers/class-call-check")["default"];
Object.defineProperty(exports, "__esModule", {
value: true
});
var BiquadFilter = (function () {
function BiquadFilter() {