forked from emscripten-core/emscripten
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlibrary_openal.js
4889 lines (4479 loc) · 152 KB
/
library_openal.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
/**
* @license
* Copyright 2013 The Emscripten Authors
* SPDX-License-Identifier: MIT
*/
//'use strict';
var LibraryOpenAL = {
// ************************************************************************
// ** INTERNALS
// ************************************************************************
$AL__deps: ['$Browser'],
$AL: {
// ------------------------------------------------------
// -- Constants
// ------------------------------------------------------
QUEUE_INTERVAL: 25,
QUEUE_LOOKAHEAD: 100.0 / 1000.0,
DEVICE_NAME: 'Emscripten OpenAL',
CAPTURE_DEVICE_NAME: 'Emscripten OpenAL capture',
ALC_EXTENSIONS: {
// TODO: 'ALC_EXT_EFX': true,
'ALC_SOFT_pause_device': true,
'ALC_SOFT_HRTF': true
},
AL_EXTENSIONS: {
'AL_EXT_float32': true,
'AL_SOFT_loop_points': true,
'AL_SOFT_source_length': true,
'AL_EXT_source_distance_model': true,
'AL_SOFT_source_spatialize': true
},
// ------------------------------------------------------
// -- ALC Fields
// ------------------------------------------------------
_alcErr: 0,
get alcErr() {
return this._alcErr;
},
set alcErr(val) {
// Errors should not be overwritten by later errors until they are cleared by a query.
if (this._alcErr === 0 /* ALC_NO_ERROR */ || val === 0 /* ALC_NO_ERROR */) {
this._alcErr = val;
}
},
deviceRefCounts: {},
alcStringCache: {},
paused: false,
// ------------------------------------------------------
// -- AL Fields
// ------------------------------------------------------
stringCache: {},
contexts: {},
currentCtx: null,
buffers: {
// The zero buffer is legal to use, so create a placeholder for it
'0': {
id: 0,
refCount: 0,
audioBuf: null,
frequency: 0,
bytesPerSample: 2,
channels: 1,
length: 0
}
},
paramArray: [], // Used to prevent allocating a new array for each param call
_nextId: 1,
newId: function() {
return AL.freeIds.length > 0 ? AL.freeIds.pop() : AL._nextId++;
},
freeIds: [],
// ------------------------------------------------------
// -- Mixing Logic
// ------------------------------------------------------
scheduleContextAudio: function(ctx) {
// If we are animating using the requestAnimationFrame method, then the main loop does not run when in the background.
// To give a perfect glitch-free audio stop when switching from foreground to background, we need to avoid updating
// audio altogether when in the background, so detect that case and kill audio buffer streaming if so.
if (Browser.mainLoop.timingMode === 1 /* EM_TIMING_RAF */ && document['visibilityState'] != 'visible') {
return;
}
for (var i in ctx.sources) {
AL.scheduleSourceAudio(ctx.sources[i]);
}
},
// This function is the core scheduler that queues web-audio buffers for output.
// src.bufQueue represents the abstract OpenAL buffer queue, which is taversed to schedule
// corresponding web-audio buffers. These buffers are stored in src.audioQueue, which
// represents the queue of buffers scheduled for physical playback. These two queues are
// distinct because of the differing semantics of OpenAL and web audio. Some changes
// to OpenAL parameters, such as pitch, may require the web audio queue to be flushed and rescheduled.
scheduleSourceAudio: function(src, lookahead) {
// See comment on scheduleContextAudio above.
if (Browser.mainLoop.timingMode === 1 /*EM_TIMING_RAF*/ && document['visibilityState'] != 'visible') {
return;
}
if (src.state !== 0x1012 /* AL_PLAYING */) {
return;
}
var currentTime = AL.updateSourceTime(src);
var startTime = src.bufStartTime;
var startOffset = src.bufOffset;
var bufCursor = src.bufsProcessed;
// Advance past any audio that is already scheduled
for (var i = 0; i < src.audioQueue.length; i++) {
var audioSrc = src.audioQueue[i];
startTime = audioSrc._startTime + audioSrc._duration;
startOffset = 0.0;
bufCursor += audioSrc._skipCount + 1;
}
if (!lookahead) {
lookahead = AL.QUEUE_LOOKAHEAD;
}
var lookaheadTime = currentTime + lookahead;
var skipCount = 0;
while (startTime < lookaheadTime) {
if (bufCursor >= src.bufQueue.length) {
if (src.looping) {
bufCursor %= src.bufQueue.length;
} else {
break;
}
}
var buf = src.bufQueue[bufCursor % src.bufQueue.length];
// If the buffer contains no data, skip it
if (buf.length === 0) {
skipCount++;
// If we've gone through the whole queue and everything is 0 length, just give up
if (skipCount === src.bufQueue.length) {
break;
}
} else {
var audioSrc = src.context.audioCtx.createBufferSource();
audioSrc.buffer = buf.audioBuf;
audioSrc.playbackRate.value = src.playbackRate;
if (buf.audioBuf._loopStart || buf.audioBuf._loopEnd) {
audioSrc.loopStart = buf.audioBuf._loopStart;
audioSrc.loopEnd = buf.audioBuf._loopEnd;
}
var duration = 0.0;
// If the source is a looping static buffer, use native looping for gapless playback
if (src.type === 0x1028 /* AL_STATIC */ && src.looping) {
duration = Number.POSITIVE_INFINITY;
audioSrc.loop = true;
if (buf.audioBuf._loopStart) {
audioSrc.loopStart = buf.audioBuf._loopStart;
}
if (buf.audioBuf._loopEnd) {
audioSrc.loopEnd = buf.audioBuf._loopEnd;
}
} else {
duration = (buf.audioBuf.duration - startOffset) / src.playbackRate;
}
audioSrc._startOffset = startOffset;
audioSrc._duration = duration;
audioSrc._skipCount = skipCount;
skipCount = 0;
audioSrc.connect(src.gain);
if (typeof audioSrc.start != 'undefined') {
// Sample the current time as late as possible to mitigate drift
startTime = Math.max(startTime, src.context.audioCtx.currentTime);
audioSrc.start(startTime, startOffset);
} else if (typeof audioSrc.noteOn != 'undefined') {
startTime = Math.max(startTime, src.context.audioCtx.currentTime);
audioSrc.noteOn(startTime);
#if OPENAL_DEBUG
if (offset > 0.0) {
warnOnce('The current browser does not support AudioBufferSourceNode.start(when, offset); method, so cannot play back audio with an offset '+startOffset+' secs! Audio glitches will occur!');
}
#endif
}
#if OPENAL_DEBUG
else {
warnOnce('Unable to start AudioBufferSourceNode playback! Not supported by the browser?');
}
out('scheduleSourceAudio() queuing buffer ' + buf.id + ' for source ' + src.id + ' at ' + startTime + ' (offset by ' + startOffset + ')');
#endif
audioSrc._startTime = startTime;
src.audioQueue.push(audioSrc);
startTime += duration;
}
startOffset = 0.0;
bufCursor++;
}
},
// Advance the state of a source forward to the current time
updateSourceTime: function(src) {
var currentTime = src.context.audioCtx.currentTime;
if (src.state !== 0x1012 /* AL_PLAYING */) {
return currentTime;
}
// if the start time is unset, determine it based on the current offset.
// This will be the case when a source is resumed after being paused, and
// allows us to pretend that the source actually started playing some time
// in the past such that it would just now have reached the stored offset.
if (!isFinite(src.bufStartTime)) {
src.bufStartTime = currentTime - src.bufOffset / src.playbackRate;
src.bufOffset = 0.0;
}
var nextStartTime = 0.0;
while (src.audioQueue.length) {
var audioSrc = src.audioQueue[0];
src.bufsProcessed += audioSrc._skipCount;
nextStartTime = audioSrc._startTime + audioSrc._duration; // n.b. audioSrc._duration already factors in playbackRate, so no divide by src.playbackRate on it.
if (currentTime < nextStartTime) {
break;
}
src.audioQueue.shift();
src.bufStartTime = nextStartTime;
src.bufOffset = 0.0;
src.bufsProcessed++;
}
if (src.bufsProcessed >= src.bufQueue.length && !src.looping) {
// The source has played its entire queue and is non-looping, so just mark it as stopped.
AL.setSourceState(src, 0x1014 /* AL_STOPPED */);
} else if (src.type === 0x1028 /* AL_STATIC */ && src.looping) {
// If the source is a looping static buffer, determine the buffer offset based on the loop points
var buf = src.bufQueue[0];
if (buf.length === 0) {
src.bufOffset = 0.0;
} else {
var delta = (currentTime - src.bufStartTime) * src.playbackRate;
var loopStart = buf.audioBuf._loopStart || 0.0;
var loopEnd = buf.audioBuf._loopEnd || buf.audioBuf.duration;
if (loopEnd <= loopStart) {
loopEnd = buf.audioBuf.duration;
}
if (delta < loopEnd) {
src.bufOffset = delta;
} else {
src.bufOffset = loopStart + (delta - loopStart) % (loopEnd - loopStart);
}
}
} else if (src.audioQueue[0]) {
// The source is still actively playing, so we just need to calculate where we are in the current buffer
// so it can be remembered if the source gets paused.
src.bufOffset = (currentTime - src.audioQueue[0]._startTime) * src.playbackRate;
} else {
// The source hasn't finished yet, but there is no scheduled audio left for it. This can be because
// the source has just been started/resumed, or due to an underrun caused by a long blocking operation.
// We need to determine what state we would be in by this point in time so that when we next schedule
// audio playback, it will be just as if no underrun occurred.
if (src.type !== 0x1028 /* AL_STATIC */ && src.looping) {
// if the source is a looping buffer queue, let's first calculate the queue duration, so we can
// quickly fast forward past any full loops of the queue and only worry about the remainder.
var srcDuration = AL.sourceDuration(src) / src.playbackRate;
if (srcDuration > 0.0) {
src.bufStartTime += Math.floor((currentTime - src.bufStartTime) / srcDuration) * srcDuration;
}
}
// Since we've already skipped any full-queue loops if there were any, we just need to find
// out where in the queue the remaining time puts us, which won't require stepping through the
// entire queue more than once.
for (var i = 0; i < src.bufQueue.length; i++) {
if (src.bufsProcessed >= src.bufQueue.length) {
if (src.looping) {
src.bufsProcessed %= src.bufQueue.length;
} else {
AL.setSourceState(src, 0x1014 /* AL_STOPPED */);
break;
}
}
var buf = src.bufQueue[src.bufsProcessed];
if (buf.length > 0) {
nextStartTime = src.bufStartTime + buf.audioBuf.duration / src.playbackRate;
if (currentTime < nextStartTime) {
src.bufOffset = (currentTime - src.bufStartTime) * src.playbackRate;
break;
}
src.bufStartTime = nextStartTime;
}
src.bufOffset = 0.0;
src.bufsProcessed++;
}
}
return currentTime;
},
cancelPendingSourceAudio: function(src) {
AL.updateSourceTime(src);
for (var i = 1; i < src.audioQueue.length; i++) {
var audioSrc = src.audioQueue[i];
audioSrc.stop();
}
if (src.audioQueue.length > 1) {
src.audioQueue.length = 1;
}
},
stopSourceAudio: function(src) {
for (var i = 0; i < src.audioQueue.length; i++) {
src.audioQueue[i].stop();
}
src.audioQueue.length = 0;
},
setSourceState: function(src, state) {
if (state === 0x1012 /* AL_PLAYING */) {
if (src.state === 0x1012 /* AL_PLAYING */ || src.state == 0x1014 /* AL_STOPPED */) {
src.bufsProcessed = 0;
src.bufOffset = 0.0;
#if OPENAL_DEBUG
out('setSourceState() resetting and playing source ' + src.id);
#endif
} else {
#if OPENAL_DEBUG
out('setSourceState() playing source ' + src.id + ' at ' + src.bufOffset);
#endif
}
AL.stopSourceAudio(src);
src.state = 0x1012 /* AL_PLAYING */;
src.bufStartTime = Number.NEGATIVE_INFINITY;
AL.scheduleSourceAudio(src);
} else if (state === 0x1013 /* AL_PAUSED */) {
if (src.state === 0x1012 /* AL_PLAYING */) {
// Store off the current offset to restore with on resume.
AL.updateSourceTime(src);
AL.stopSourceAudio(src);
src.state = 0x1013 /* AL_PAUSED */;
#if OPENAL_DEBUG
out('setSourceState() pausing source ' + src.id + ' at ' + src.bufOffset);
#endif
}
} else if (state === 0x1014 /* AL_STOPPED */) {
if (src.state !== 0x1011 /* AL_INITIAL */) {
src.state = 0x1014 /* AL_STOPPED */;
src.bufsProcessed = src.bufQueue.length;
src.bufStartTime = Number.NEGATIVE_INFINITY;
src.bufOffset = 0.0;
AL.stopSourceAudio(src);
#if OPENAL_DEBUG
out('setSourceState() stopping source ' + src.id);
#endif
}
} else if (state === 0x1011 /* AL_INITIAL */) {
if (src.state !== 0x1011 /* AL_INITIAL */) {
src.state = 0x1011 /* AL_INITIAL */;
src.bufsProcessed = 0;
src.bufStartTime = Number.NEGATIVE_INFINITY;
src.bufOffset = 0.0;
AL.stopSourceAudio(src);
#if OPENAL_DEBUG
out('setSourceState() initializing source ' + src.id);
#endif
}
}
},
initSourcePanner: function(src) {
if (src.type === 0x1030 /* AL_UNDETERMINED */) {
return;
}
// Find the first non-zero buffer in the queue to determine the proper format
var templateBuf = AL.buffers[0];
for (var i = 0; i < src.bufQueue.length; i++) {
if (src.bufQueue[i].id !== 0) {
templateBuf = src.bufQueue[i];
break;
}
}
// Create a panner if AL_SOURCE_SPATIALIZE_SOFT is set to true, or alternatively if it's set to auto and the source is mono
if (src.spatialize === 1 /* AL_TRUE */ || (src.spatialize === 2 /* AL_AUTO_SOFT */ && templateBuf.channels === 1)) {
if (src.panner) {
return;
}
src.panner = src.context.audioCtx.createPanner();
AL.updateSourceGlobal(src);
AL.updateSourceSpace(src);
src.panner.connect(src.context.gain);
src.gain.disconnect();
src.gain.connect(src.panner);
} else {
if (!src.panner) {
return;
}
src.panner.disconnect();
src.gain.disconnect();
src.gain.connect(src.context.gain);
src.panner = null;
}
},
updateContextGlobal: function(ctx) {
for (var i in ctx.sources) {
AL.updateSourceGlobal(ctx.sources[i]);
}
},
updateSourceGlobal: function(src) {
var panner = src.panner;
if (!panner) {
return;
}
panner.refDistance = src.refDistance;
panner.maxDistance = src.maxDistance;
panner.rolloffFactor = src.rolloffFactor;
panner.panningModel = src.context.hrtf ? 'HRTF' : 'equalpower';
// Use the source's distance model if AL_SOURCE_DISTANCE_MODEL is enabled
var distanceModel = src.context.sourceDistanceModel ? src.distanceModel : src.context.distanceModel;
switch (distanceModel) {
case 0 /* AL_NONE */:
panner.distanceModel = 'inverse';
panner.refDistance = 3.40282e38 /* FLT_MAX */;
break;
case 0xd001 /* AL_INVERSE_DISTANCE */:
case 0xd002 /* AL_INVERSE_DISTANCE_CLAMPED */:
panner.distanceModel = 'inverse';
break;
case 0xd003 /* AL_LINEAR_DISTANCE */:
case 0xd004 /* AL_LINEAR_DISTANCE_CLAMPED */:
panner.distanceModel = 'linear';
break;
case 0xd005 /* AL_EXPONENT_DISTANCE */:
case 0xd006 /* AL_EXPONENT_DISTANCE_CLAMPED */:
panner.distanceModel = 'exponential';
break;
}
},
updateListenerSpace: function(ctx) {
var listener = ctx.audioCtx.listener;
if (listener.positionX) {
listener.positionX.value = ctx.listener.position[0];
listener.positionY.value = ctx.listener.position[1];
listener.positionZ.value = ctx.listener.position[2];
} else {
#if OPENAL_DEBUG
warnOnce('Listener position attributes are not present, falling back to setPosition()');
#endif
listener.setPosition(ctx.listener.position[0], ctx.listener.position[1], ctx.listener.position[2]);
}
if (listener.forwardX) {
listener.forwardX.value = ctx.listener.direction[0];
listener.forwardY.value = ctx.listener.direction[1];
listener.forwardZ.value = ctx.listener.direction[2];
listener.upX.value = ctx.listener.up[0];
listener.upY.value = ctx.listener.up[1];
listener.upZ.value = ctx.listener.up[2];
} else {
#if OPENAL_DEBUG
warnOnce('Listener orientation attributes are not present, falling back to setOrientation()');
#endif
listener.setOrientation(
ctx.listener.direction[0], ctx.listener.direction[1], ctx.listener.direction[2],
ctx.listener.up[0], ctx.listener.up[1], ctx.listener.up[2]);
}
// Update sources that are relative to the listener
for (var i in ctx.sources) {
AL.updateSourceSpace(ctx.sources[i]);
}
},
updateSourceSpace: function(src) {
if (!src.panner) {
return;
}
var panner = src.panner;
var posX = src.position[0];
var posY = src.position[1];
var posZ = src.position[2];
var dirX = src.direction[0];
var dirY = src.direction[1];
var dirZ = src.direction[2];
var listener = src.context.listener;
var lPosX = listener.position[0];
var lPosY = listener.position[1];
var lPosZ = listener.position[2];
// WebAudio does spatialization in world-space coordinates, meaning both the buffer sources and
// the listener position are in the same absolute coordinate system relative to a fixed origin.
// By default, OpenAL works this way as well, but it also provides a "listener relative" mode, where
// a buffer source's coordinate are interpreted not in absolute world space, but as being relative
// to the listener object itself, so as the listener moves the source appears to move with it
// with no update required. Since web audio does not support this mode, we must transform the source
// coordinates from listener-relative space to absolute world space.
//
// We do this via affine transformation matrices applied to the source position and source direction.
// A change-of-basis converts from listener-space displacements to world-space displacements,
// which must be done for both the source position and direction. Lastly, the source position must be
// added to the listener position to get the final source position, since the source position represents
// a displacement from the listener.
if (src.relative) {
// Negate the listener direction since forward is -Z.
var lBackX = -listener.direction[0];
var lBackY = -listener.direction[1];
var lBackZ = -listener.direction[2];
var lUpX = listener.up[0];
var lUpY = listener.up[1];
var lUpZ = listener.up[2];
var inverseMagnitude = function(x, y, z) {
var length = Math.sqrt(x * x + y * y + z * z);
if (length < Number.EPSILON) {
return 0.0;
}
return 1.0 / length;
};
// Normalize the Back vector
var invMag = inverseMagnitude(lBackX, lBackY, lBackZ);
lBackX *= invMag;
lBackY *= invMag;
lBackZ *= invMag;
// ...and the Up vector
invMag = inverseMagnitude(lUpX, lUpY, lUpZ);
lUpX *= invMag;
lUpY *= invMag;
lUpZ *= invMag;
// Calculate the Right vector as the cross product of the Up and Back vectors
var lRightX = (lUpY * lBackZ - lUpZ * lBackY);
var lRightY = (lUpZ * lBackX - lUpX * lBackZ);
var lRightZ = (lUpX * lBackY - lUpY * lBackX);
// Back and Up might not be exactly perpendicular, so the cross product also needs normalization
invMag = inverseMagnitude(lRightX, lRightY, lRightZ);
lRightX *= invMag;
lRightY *= invMag;
lRightZ *= invMag;
// Recompute Up from the now orthonormal Right and Back vectors so we have a fully orthonormal basis
lUpX = (lBackY * lRightZ - lBackZ * lRightY);
lUpY = (lBackZ * lRightX - lBackX * lRightZ);
lUpZ = (lBackX * lRightY - lBackY * lRightX);
var oldX = dirX;
var oldY = dirY;
var oldZ = dirZ;
// Use our 3 vectors to apply a change-of-basis matrix to the source direction
dirX = oldX * lRightX + oldY * lUpX + oldZ * lBackX;
dirY = oldX * lRightY + oldY * lUpY + oldZ * lBackY;
dirZ = oldX * lRightZ + oldY * lUpZ + oldZ * lBackZ;
oldX = posX;
oldY = posY;
oldZ = posZ;
// ...and to the source position
posX = oldX * lRightX + oldY * lUpX + oldZ * lBackX;
posY = oldX * lRightY + oldY * lUpY + oldZ * lBackY;
posZ = oldX * lRightZ + oldY * lUpZ + oldZ * lBackZ;
// The change-of-basis corrects the orientation, but the origin is still the listener.
// Translate the source position by the listener position to finish.
posX += lPosX;
posY += lPosY;
posZ += lPosZ;
}
if (panner.positionX) {
// Assigning to panner.positionX/Y/Z unnecessarily seems to cause performance issues
// See https://github.com/emscripten-core/emscripten/issues/15847
if (posX != panner.positionX.value) panner.positionX.value = posX;
if (posY != panner.positionY.value) panner.positionY.value = posY;
if (posZ != panner.positionZ.value) panner.positionZ.value = posZ;
} else {
#if OPENAL_DEBUG
warnOnce('Panner position attributes are not present, falling back to setPosition()');
#endif
panner.setPosition(posX, posY, posZ);
}
if (panner.orientationX) {
// Assigning to panner.orientation/Y/Z unnecessarily seems to cause performance issues
// See https://github.com/emscripten-core/emscripten/issues/15847
if (dirX != panner.orientationX.value) panner.orientationX.value = dirX;
if (dirY != panner.orientationY.value) panner.orientationY.value = dirY;
if (dirZ != panner.orientationZ.value) panner.orientationZ.value = dirZ;
} else {
#if OPENAL_DEBUG
warnOnce('Panner orientation attributes are not present, falling back to setOrientation()');
#endif
panner.setOrientation(dirX, dirY, dirZ);
}
var oldShift = src.dopplerShift;
var velX = src.velocity[0];
var velY = src.velocity[1];
var velZ = src.velocity[2];
var lVelX = listener.velocity[0];
var lVelY = listener.velocity[1];
var lVelZ = listener.velocity[2];
if (posX === lPosX && posY === lPosY && posZ === lPosZ
|| velX === lVelX && velY === lVelY && velZ === lVelZ)
{
src.dopplerShift = 1.0;
} else {
// Doppler algorithm from 1.1 spec
var speedOfSound = src.context.speedOfSound;
var dopplerFactor = src.context.dopplerFactor;
var slX = lPosX - posX;
var slY = lPosY - posY;
var slZ = lPosZ - posZ;
var magSl = Math.sqrt(slX * slX + slY * slY + slZ * slZ);
var vls = (slX * lVelX + slY * lVelY + slZ * lVelZ) / magSl;
var vss = (slX * velX + slY * velY + slZ * velZ) / magSl;
vls = Math.min(vls, speedOfSound / dopplerFactor);
vss = Math.min(vss, speedOfSound / dopplerFactor);
src.dopplerShift = (speedOfSound - dopplerFactor * vls) / (speedOfSound - dopplerFactor * vss);
}
if (src.dopplerShift !== oldShift) {
AL.updateSourceRate(src);
}
},
updateSourceRate: function(src) {
if (src.state === 0x1012 /* AL_PLAYING */) {
// clear scheduled buffers
AL.cancelPendingSourceAudio(src);
var audioSrc = src.audioQueue[0];
if (!audioSrc) {
return; // It is possible that AL.scheduleContextAudio() has not yet fed the next buffer, if so, skip.
}
var duration;
if (src.type === 0x1028 /* AL_STATIC */ && src.looping) {
duration = Number.POSITIVE_INFINITY;
} else {
// audioSrc._duration is expressed after factoring in playbackRate, so when changing playback rate, need
// to recompute/rescale the rate to the new playback speed.
duration = (audioSrc.buffer.duration - audioSrc._startOffset) / src.playbackRate;
}
audioSrc._duration = duration;
audioSrc.playbackRate.value = src.playbackRate;
// reschedule buffers with the new playbackRate
AL.scheduleSourceAudio(src);
}
},
sourceDuration: function(src) {
var length = 0.0;
for (var i = 0; i < src.bufQueue.length; i++) {
var audioBuf = src.bufQueue[i].audioBuf;
length += audioBuf ? audioBuf.duration : 0.0;
}
return length;
},
sourceTell: function(src) {
AL.updateSourceTime(src);
var offset = 0.0;
for (var i = 0; i < src.bufsProcessed; i++) {
if (src.bufQueue[i].audioBuf) {
offset += src.bufQueue[i].audioBuf.duration;
}
}
offset += src.bufOffset;
return offset;
},
sourceSeek: function(src, offset) {
var playing = src.state == 0x1012 /* AL_PLAYING */;
if (playing) {
AL.setSourceState(src, 0x1011 /* AL_INITIAL */);
}
if (src.bufQueue[src.bufsProcessed].audioBuf !== null) {
src.bufsProcessed = 0;
while (offset > src.bufQueue[src.bufsProcessed].audioBuf.duration) {
offset -= src.bufQueue[src.bufsProcessed].audiobuf.duration;
src.bufsProcessed++;
}
src.bufOffset = offset;
}
if (playing) {
AL.setSourceState(src, 0x1012 /* AL_PLAYING */);
}
},
// ------------------------------------------------------
// -- Accessor Helpers
// ------------------------------------------------------
getGlobalParam: function(funcname, param) {
if (!AL.currentCtx) {
#if OPENAL_DEBUG
err(funcname + '() called without a valid context');
#endif
return null;
}
switch (param) {
case 0xC000 /* AL_DOPPLER_FACTOR */:
return AL.currentCtx.dopplerFactor;
case 0xC003 /* AL_SPEED_OF_SOUND */:
return AL.currentCtx.speedOfSound;
case 0xD000 /* AL_DISTANCE_MODEL */:
return AL.currentCtx.distanceModel;
default:
#if OPENAL_DEBUG
err(funcname + '() param 0x' + param.toString(16) + ' is unknown or not implemented');
#endif
AL.currentCtx.err = 0xA002 /* AL_INVALID_ENUM */;
return null;
}
},
setGlobalParam: function(funcname, param, value) {
if (!AL.currentCtx) {
#if OPENAL_DEBUG
err(funcname + '() called without a valid context');
#endif
return;
}
switch (param) {
case 0xC000 /* AL_DOPPLER_FACTOR */:
if (!Number.isFinite(value) || value < 0.0) { // Strictly negative values are disallowed
#if OPENAL_DEBUG
err(funcname + '() value ' + value + ' is out of range');
#endif
AL.currentCtx.err = 0xA003 /* AL_INVALID_VALUE */;
return;
}
AL.currentCtx.dopplerFactor = value;
AL.updateListenerSpace(AL.currentCtx);
break;
case 0xC003 /* AL_SPEED_OF_SOUND */:
if (!Number.isFinite(value) || value <= 0.0) { // Negative or zero values are disallowed
#if OPENAL_DEBUG
err(funcname + '() value ' + value + ' is out of range');
#endif
AL.currentCtx.err = 0xA003 /* AL_INVALID_VALUE */;
return;
}
AL.currentCtx.speedOfSound = value;
AL.updateListenerSpace(AL.currentCtx);
break;
case 0xD000 /* AL_DISTANCE_MODEL */:
switch (value) {
case 0 /* AL_NONE */:
case 0xd001 /* AL_INVERSE_DISTANCE */:
case 0xd002 /* AL_INVERSE_DISTANCE_CLAMPED */:
case 0xd003 /* AL_LINEAR_DISTANCE */:
case 0xd004 /* AL_LINEAR_DISTANCE_CLAMPED */:
case 0xd005 /* AL_EXPONENT_DISTANCE */:
case 0xd006 /* AL_EXPONENT_DISTANCE_CLAMPED */:
AL.currentCtx.distanceModel = value;
AL.updateContextGlobal(AL.currentCtx);
break;
default:
#if OPENAL_DEBUG
err(funcname + '() value ' + value + ' is out of range');
#endif
AL.currentCtx.err = 0xA003 /* AL_INVALID_VALUE */;
return;
}
break;
default:
#if OPENAL_DEBUG
err(funcname + '() param 0x' + param.toString(16) + ' is unknown or not implemented');
#endif
AL.currentCtx.err = 0xA002 /* AL_INVALID_ENUM */;
return;
}
},
getListenerParam: function(funcname, param) {
if (!AL.currentCtx) {
#if OPENAL_DEBUG
err(funcname + '() called without a valid context');
#endif
return null;
}
switch (param) {
case 0x1004 /* AL_POSITION */:
return AL.currentCtx.listener.position;
case 0x1006 /* AL_VELOCITY */:
return AL.currentCtx.listener.velocity;
case 0x100F /* AL_ORIENTATION */:
return AL.currentCtx.listener.direction.concat(AL.currentCtx.listener.up);
case 0x100A /* AL_GAIN */:
return AL.currentCtx.gain.gain.value;
default:
#if OPENAL_DEBUG
err(funcname + '() param 0x' + param.toString(16) + ' is unknown or not implemented');
#endif
AL.currentCtx.err = 0xA002 /* AL_INVALID_ENUM */;
return null;
}
},
setListenerParam: function(funcname, param, value) {
if (!AL.currentCtx) {
#if OPENAL_DEBUG
err(funcname + '() called without a valid context');
#endif
return;
}
if (value === null) {
#if OPENAL_DEBUG
err(funcname + '(): param 0x' + param.toString(16) + ' has wrong signature');
#endif
AL.currentCtx.err = 0xA002 /* AL_INVALID_ENUM */;
return;
}
var listener = AL.currentCtx.listener;
switch (param) {
case 0x1004 /* AL_POSITION */:
if (!Number.isFinite(value[0]) || !Number.isFinite(value[1]) || !Number.isFinite(value[2])) {
#if OPENAL_DEBUG
err(funcname + '() param AL_POSITION value ' + value + ' is out of range');
#endif
AL.currentCtx.err = 0xA003 /* AL_INVALID_VALUE */;
return;
}
listener.position[0] = value[0];
listener.position[1] = value[1];
listener.position[2] = value[2];
AL.updateListenerSpace(AL.currentCtx);
break;
case 0x1006 /* AL_VELOCITY */:
if (!Number.isFinite(value[0]) || !Number.isFinite(value[1]) || !Number.isFinite(value[2])) {
#if OPENAL_DEBUG
err(funcname + '() param AL_VELOCITY value ' + value + ' is out of range');
#endif
AL.currentCtx.err = 0xA003 /* AL_INVALID_VALUE */;
return;
}
listener.velocity[0] = value[0];
listener.velocity[1] = value[1];
listener.velocity[2] = value[2];
AL.updateListenerSpace(AL.currentCtx);
break;
case 0x100A /* AL_GAIN */:
if (!Number.isFinite(value) || value < 0.0) {
#if OPENAL_DEBUG
err(funcname + '() param AL_GAIN value ' + value + ' is out of range');
#endif
AL.currentCtx.err = 0xA003 /* AL_INVALID_VALUE */;
return;
}
AL.currentCtx.gain.gain.value = value;
break;
case 0x100F /* AL_ORIENTATION */:
if (!Number.isFinite(value[0]) || !Number.isFinite(value[1]) || !Number.isFinite(value[2])
|| !Number.isFinite(value[3]) || !Number.isFinite(value[4]) || !Number.isFinite(value[5])
) {
#if OPENAL_DEBUG
err(funcname + '() param AL_ORIENTATION value ' + value + ' is out of range');
#endif
AL.currentCtx.err = 0xA003 /* AL_INVALID_VALUE */;
return;
}
listener.direction[0] = value[0];
listener.direction[1] = value[1];
listener.direction[2] = value[2];
listener.up[0] = value[3];
listener.up[1] = value[4];
listener.up[2] = value[5];
AL.updateListenerSpace(AL.currentCtx);
break;
default:
#if OPENAL_DEBUG
err(funcname + '() param 0x' + param.toString(16) + ' is unknown or not implemented');
#endif
AL.currentCtx.err = 0xA002 /* AL_INVALID_ENUM */;
return;
}
},
getBufferParam: function(funcname, bufferId, param) {
if (!AL.currentCtx) {
#if OPENAL_DEBUG
err(funcname + '() called without a valid context');
#endif
return;
}
var buf = AL.buffers[bufferId];
if (!buf || bufferId === 0) {
#if OPENAL_DEBUG
err(funcname + '() called with an invalid buffer');
#endif
AL.currentCtx.err = 0xA001 /* AL_INVALID_NAME */;
return;
}
switch (param) {
case 0x2001 /* AL_FREQUENCY */:
return buf.frequency;
case 0x2002 /* AL_BITS */:
return buf.bytesPerSample * 8;
case 0x2003 /* AL_CHANNELS */:
return buf.channels;
case 0x2004 /* AL_SIZE */:
return buf.length * buf.bytesPerSample * buf.channels;
case 0x2015 /* AL_LOOP_POINTS_SOFT */:
if (buf.length === 0) {
return [0, 0];
}
return [
(buf.audioBuf._loopStart || 0.0) * buf.frequency,
(buf.audioBuf._loopEnd || buf.length) * buf.frequency
];
default:
#if OPENAL_DEBUG
err(funcname + '() param 0x' + param.toString(16) + ' is unknown or not implemented');
#endif
AL.currentCtx.err = 0xA002 /* AL_INVALID_ENUM */;
return null;
}
},
setBufferParam: function(funcname, bufferId, param, value) {
if (!AL.currentCtx) {
#if OPENAL_DEBUG
err(funcname + '() called without a valid context');
#endif
return;
}
var buf = AL.buffers[bufferId];
if (!buf || bufferId === 0) {
#if OPENAL_DEBUG
err(funcname + '() called with an invalid buffer');
#endif
AL.currentCtx.err = 0xA001 /* AL_INVALID_NAME */;
return;
}
if (value === null) {