-
-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathmojoal.c
More file actions
5111 lines (4437 loc) · 187 KB
/
mojoal.c
File metadata and controls
5111 lines (4437 loc) · 187 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
/**
* MojoAL; a simple drop-in OpenAL implementation.
*
* Please see the file LICENSE.txt in the source's root directory.
*
* This file written by Ryan C. Gordon.
*/
#include <float.h> // needed for FLT_MAX
// Unless compiling statically into another app, we want the public API
// to export on Windows. Define these before including al.h, so we override
// its attempt to mark these as `dllimport`.
#if defined(_WIN32) && !defined(AL_LIBTYPE_STATIC)
#define AL_API __declspec(dllexport)
#define ALC_API __declspec(dllexport)
#endif
// This is for debugging and/or pulling the fire alarm.
#ifndef MOJOAL_FORCE_SCALAR_FALLBACK
# define MOJOAL_FORCE_SCALAR_FALLBACK 0
#endif
#if MOJOAL_FORCE_SCALAR_FALLBACK
# define SDL_DISABLE_SSE
# define SDL_DISABLE_NEON
#endif
#include "al.h"
#include "alc.h"
#include <SDL3/SDL.h>
#include <SDL3/SDL_intrin.h>
#if defined(SDL_SSE_INTRINSICS) // if you are on x86 or x86-64, we assume you have SSE1 by now.
#define NEED_SCALAR_FALLBACK 0
#elif defined(SDL_NEON_INTRINSICS) && (defined(__ARM_ARCH) && (__ARM_ARCH >= 8)) // ARMv8 always has NEON.
#define NEED_SCALAR_FALLBACK 0
#elif defined(SDL_NEON_INTRINSICS) && (defined(__APPLE__) && defined(__ARM_ARCH) && (__ARM_ARCH >= 7)) // All ARMv7 chips from Apple have NEON.
#define NEED_SCALAR_FALLBACK 0
#elif defined(SDL_NEON_INTRINSICS) && (defined(__WINDOWS__) || defined(__WINRT__)) && defined(_M_ARM) // all WinRT-level Microsoft devices have NEON
#define NEED_SCALAR_FALLBACK 0
#else
#define NEED_SCALAR_FALLBACK 1
#endif
#define OPENAL_VERSION_MAJOR 1
#define OPENAL_VERSION_MINOR 1
#define OPENAL_VERSION_STRING2_FINAL(major, minor) #major "." #minor
#define OPENAL_VERSION_STRING2(major, minor) OPENAL_VERSION_STRING2_FINAL(major, minor)
#define OPENAL_VERSION_STRING3_FINAL(major, minor, micro) #major "." #minor "." #micro
#define OPENAL_VERSION_STRING3(major, minor, micro) OPENAL_VERSION_STRING3_FINAL(major, minor, micro)
#define MOJOAL_VERSION_MAJOR 2
#define MOJOAL_VERSION_MINOR 9
#define MOJOAL_VERSION_MICRO 9
#define OPENAL_VERSION_STRING OPENAL_VERSION_STRING2(OPENAL_VERSION_MAJOR, OPENAL_VERSION_MINOR) " MOJOAL " OPENAL_VERSION_STRING3(MOJOAL_VERSION_MAJOR, MOJOAL_VERSION_MINOR, MOJOAL_VERSION_MICRO)
#define OPENAL_VENDOR_STRING "Ryan C. Gordon"
#define OPENAL_RENDERER_STRING "MojoAL"
#define DEFAULT_PLAYBACK_DEVICE "Default OpenAL playback device"
#define DEFAULT_CAPTURE_DEVICE "Default OpenAL capture device"
// Number of buffers to allocate at once when we need a new block during alGenBuffers().
#ifndef OPENAL_BUFFER_BLOCK_SIZE
#define OPENAL_BUFFER_BLOCK_SIZE 256
#endif
// Number of sources to allocate at once when we need a new block during alGenSources().
#ifndef OPENAL_SOURCE_BLOCK_SIZE
#define OPENAL_SOURCE_BLOCK_SIZE 64
#endif
// AL_EXT_FLOAT32 support...
#ifndef AL_FORMAT_MONO_FLOAT32
#define AL_FORMAT_MONO_FLOAT32 0x10010
#endif
#ifndef AL_FORMAT_STEREO_FLOAT32
#define AL_FORMAT_STEREO_FLOAT32 0x10011
#endif
// AL_EXT_32bit_formats support...
// (this doesn't cover the AL_EXT_MCFORMATS items at the moment, per spec).
#ifndef AL_FORMAT_MONO_I32
#define AL_FORMAT_MONO_I32 0x19DB
#endif
#ifndef AL_FORMAT_STEREO_I32
#define AL_FORMAT_STEREO_I32 0x19DC
#endif
// ALC_EXT_DISCONNECTED support...
#ifndef ALC_CONNECTED
#define ALC_CONNECTED 0x313
#endif
// AL_EXT_source_distance_model support...
#ifndef AL_SOURCE_DISTANCE_MODEL
#define AL_SOURCE_DISTANCE_MODEL 0x200
#endif
// AL_SOFT_callback_buffer support...
#ifndef AL_BUFFER_CALLBACK_FUNCTION_SOFT
#define AL_BUFFER_CALLBACK_FUNCTION_SOFT 0x19A0
#endif
#ifndef AL_BUFFER_CALLBACK_USER_PARAM_SOFT
#define AL_BUFFER_CALLBACK_USER_PARAM_SOFT 0x19A1
#endif
typedef ALsizei (AL_APIENTRY *ALBUFFERCALLBACKTYPESOFT)(ALvoid *userptr, ALvoid *sampledata, ALsizei numbytes);
AL_API void AL_APIENTRY alBufferCallbackSOFT(ALuint buffer, ALenum format, ALsizei freq, ALBUFFERCALLBACKTYPESOFT callback, ALvoid *userptr);
AL_API void AL_APIENTRY alGetBufferPtrSOFT(ALuint buffer, ALenum param, ALvoid **ptr);
AL_API void AL_APIENTRY alGetBuffer3PtrSOFT(ALuint buffer, ALenum param, ALvoid **ptr0, ALvoid **ptr1, ALvoid **ptr2);
AL_API void AL_APIENTRY alGetBufferPtrvSOFT(ALuint buffer, ALenum param, ALvoid **ptr);
/*
The locking strategy for this OpenAL implementation:
- The initial work on this implementation attempted to be completely
lock free, and it lead to fragile, overly-clever, and complicated code.
Attempt #2 is making more reasonable tradeoffs.
- All API entry points are protected by a global mutex, which means that
calls into the API are serialized, but we expect this to not be a
serious problem; most AL calls are likely to come from a single thread
and uncontested mutexes generally aren't very expensive. This mutex
is not shared with the mixer thread, so there is never a point where
an innocent "fast" call into the AL will block because of the bad luck
of a high mixing load and the wrong moment.
- As of the migration to SDL3, each OpenAL context is backed by an
SDL_AudioStream bound to the audio device, so the "mixer lock" is no longer
global lock that blocks all contexts during mixing, but rather blocks a
single context at a time as it mixes. For most purposes, this doesn't
change much, as most apps probably only have a single context. References
to the "mixer thread" mean the thread that mixes all contexts, but each
context is locked separately as this thread progresses.
- In rare cases we'll lock the mixer thread for a brief time; when a playing
source is accessible to the mixer, it is flagged as such. The mixer locks
each source separately as it mixes it (each source has an SDL_AudioStream
and the mixer holds its lock), and if we need to touch a source
that is flagged as accessible, we'll grab that lock to make sure there isn't
a conflict. Not all source changes need to do this. The likelihood of
hitting this case is extremely small, and the lock hold time is pretty
short. Things that might do this, only on currently-playing sources:
alDeleteSources, alSourceStop, alSourceRewind. alSourcePlay and
alSourcePause never need to lock.
- Devices are expected to live for the entire life of your OpenAL
experience, so closing one while another thread is using it is your own
fault. Don't do that. Devices are allocated pointers, and the AL doesn't
know if you've deleted it, making the pointer invalid. Device open and
close are not meant to be "fast" calls.
- Generating an object (source, buffer, etc) might need to allocate
memory, which can always take longer than you would expect. We allocate in
blocks, so not every call will allocate more memory. Generating an object
does not lock the mixer thread.
- Deleting a buffer does not lock the mixer thread (in-use buffers can
not be deleted per API spec). Deleting a source will lock the mixer briefly
if the source is still visible to the mixer. We don't believe this will be
a serious issue in normal use cases. Deleted objects' memory is marked for
reuse, but no memory is free'd by deleting sources or buffers until the
context or device, respectively, are destroyed. A deleted source that's
still visible to the mixer will not be available for reallocation until
the mixer runs another iteration, where it will mark it as no longer
visible. If you call alGenSources() during this time, a different source
will be allocated.
- alBufferData needs to allocate memory to copy new audio data. Often,
you can avoid doing these things in time-critical code. You can't set
a buffer's data when it's attached to a source (either with AL_BUFFER
or buffer queueing), so there's never a chance of contention with the
mixer thread here.
- Buffers and sources are allocated in blocks of OPENAL_BUFFER_BLOCK_SIZE
(or OPENAL_SOURCE_BLOCK_SIZE). These blocks are never deallocated as long
as the device (for buffers) or context (for sources) lives, so they don't
need a lock to access as the pointers are immutable once they're wired in.
We don't keep a ALuint name index array, but rather an array of block
pointers, which lets us find the right offset in the correct block without
iteration. The mixer thread never references the blocks directly, as they
get buffer and source pointers to objects within those blocks. Sources keep
a pointer to their specifically-bound buffer, and the mixer keeps a list of
pointers to playing sources. Since the API is serialized and the mixer
doesn't touch them, we don't need to tapdance to add new blocks.
- Buffer data is owned by the AL, and it's illegal to delete a buffer or
alBufferData() its contents while attached to a source with either
AL_BUFFER or alSourceQueueBuffers(). We keep an atomic refcount for each
buffer, and you can't change its state or delete it when its refcount is
> 0, so there isn't a race with the mixer. Refcounts only change when
changing a source's AL_BUFFER or altering its buffer queue, both of which
are protected by the api lock. The mixer thread doesn't touch the
refcount, as a buffer moving from AL_PENDING to AL_PROCESSED is still
attached to a source.
- alSource(Stop|Pause|Rewind)v with > 1 source used will always lock the
mixer thread to guarantee that all sources change in sync (!!! FIXME?).
The non-v version of these functions do not lock the mixer thread.
alSourcePlayv never locks the mixer thread (it atomically appends to a
linked list of sources to be played, which the mixer will pick up all
at once).
- alSourceQueueBuffers will build a linked list of buffers, then atomically
move this list into position for the mixer to obtain it. The mixer will
process this list without the need to be atomic (as it owns it once it
atomically claims it from from the just_queued field where
alSourceQueueBuffers staged it). As buffers are processed, the mixer moves
them atomically to a linked list that other threads can pick up for
alSourceUnqueueBuffers.
- Setting a source's offset (AL_SEC_OFFSET, AL_SAMPLE_OFFSET, AL_BYTE_OFFSET)
will lock the source to adjust several things.
- Capture just locks the SDL audio device for everything, since it's a very
lightweight load and a much simplified API; good enough. The capture device
thread just dumps excessive audio from the audiostream if too much is
queueing up, so this never takes long, and is good enough.
- Probably other things. These notes might get updates later.
*/
#if 1
#define FIXME(x)
#else
#define FIXME(x) { \
static ALboolean seen = AL_FALSE; \
if (!seen) { \
seen = AL_TRUE; \
SDL_Log("MOJOAL FIXME: %s (%s@%s:%d)", x, __FUNCTION__, __FILE__, __LINE__); \
} \
}
#endif
#if defined(SDL_SSE_INTRINSICS) // we assume you always have this on x86/x86-64 chips. SSE1 is 20+ years old!
#define has_sse AL_TRUE
#endif
#if defined(SDL_NEON_INTRINSICS)
#if NEED_SCALAR_FALLBACK
static ALboolean has_neon = AL_FALSE;
#else
#define has_neon AL_TRUE
#endif
#endif
#define IS_SIMD_ALIGNED(x) ( (((size_t) (x)) % 16) == 0 )
static SDL_Mutex *api_lock = NULL;
static int init_api_lock(void)
{
if (!api_lock) {
api_lock = SDL_CreateMutex();
if (!api_lock) {
return 0;
}
}
return 1;
}
static void grab_api_lock(void)
{
if (!api_lock) {
if (!init_api_lock()) {
return;
}
}
SDL_LockMutex(api_lock);
}
static void ungrab_api_lock(void)
{
if (!api_lock) {
init_api_lock();
return;
}
SDL_UnlockMutex(api_lock);
}
#define ENTRYPOINT(rettype,fn,params,args) \
rettype AL_APIENTRY fn params { rettype retval; grab_api_lock(); retval = _##fn args ; ungrab_api_lock(); return retval; }
#define ENTRYPOINTVOID(fn,params,args) \
void fn AL_APIENTRY params { grab_api_lock(); _##fn args ; ungrab_api_lock(); }
static size_t simd_alignment = 0;
static void *malloc_simd_aligned(const size_t len)
{
SDL_assert(simd_alignment > 0);
return SDL_aligned_alloc(simd_alignment, len);
}
static void free_simd_aligned(void *ptr)
{
SDL_aligned_free(ptr);
}
// VBAP code originally from https://github.com/drbafflegab/vbap/ ... CC0 license (public domain).
#define VBAP2D_MAX_RESOLUTION 3600
#define VBAP2D_MAX_SPEAKER_COUNT 8 // original code had 64, assumed you'd use less, but we're hardcoding our current maximum.
#define VBAP2D_RESOLUTION 36 // 10 degrees per division
static SDL_INLINE float VBAP2D_division_to_angle(int const division)
{
return (float)division * (2.0f * SDL_PI_F) / (float)VBAP2D_RESOLUTION;
}
static SDL_INLINE int VBAP2D_angle_to_span(float const angle)
{
return (int)SDL_floorf(angle * (float)VBAP2D_RESOLUTION / (2.0f * SDL_PI_F));
}
static SDL_INLINE bool VBAP2D_contains(int division, int last_division, int next_division)
{
if (last_division < next_division) {
return last_division <= division && division < next_division;
} else {
const bool cond_a = 0 <= division && division < next_division;
const bool cond_b = last_division <= division && division < VBAP2D_RESOLUTION;
return cond_a || cond_b;
}
}
static SDL_INLINE void VBAP2D_unpack_speaker_pair(int speaker_pair, int speaker_count, int *speakers)
{
speakers[0] = (speaker_pair == 0 ? speaker_count : speaker_pair) - 1;
speakers[1] = speaker_pair;
}
typedef struct VBAP2D_SpeakerPosition
{
const Uint8 division; // this is in degrees--positive to the left--divided by the resolution. RESOLUTION MUST BE < 256 TO FIT IN UINT8!
const Uint8 sdl_channel; // the channel in SDL's layout (in stereo: {left=0, right=1}...etc).
} VBAP2D_SpeakerPosition;
typedef struct VBAP2D_SpeakerLayout
{
const VBAP2D_SpeakerPosition *positions;
const int lfe_channel;
} VBAP2D_SpeakerLayout;
// these have to go from smallest to largest angle, I think...
#define P(angle) ( (Uint8) ((angle / 360.0) * VBAP2D_RESOLUTION ) )
static const VBAP2D_SpeakerPosition VBAP2D_SpeakerPositions_quad[] = { { P(45), 1 }, { P(135), 0 }, { P(225), 2 }, { P(315), 3 } };
static const VBAP2D_SpeakerPosition VBAP2D_SpeakerPositions_4_1[] = { { P(45), 1 }, { P(135), 0 }, { P(225), 3 }, { P(315), 4 } };
static const VBAP2D_SpeakerPosition VBAP2D_SpeakerPositions_5_1[] = { { P(60), 1 }, { P(90), 2 }, { P(120), 0 }, { P(240), 4 }, { P(300), 5 } };
static const VBAP2D_SpeakerPosition VBAP2D_SpeakerPositions_6_1[] = { { P(60), 1 }, { P(90), 2 }, { P(120), 0 }, { P(190), 5 }, { P(270), 4 }, { P(350), 6 } };
static const VBAP2D_SpeakerPosition VBAP2D_SpeakerPositions_7_1[] = { { P(0), 7 }, { P(60), 1 }, { P(90), 2 }, { P(120), 0 }, { P(200), 6 }, { P(240), 4 }, { P(300), 5 } };
static const VBAP2D_SpeakerLayout VBAP2D_SpeakerLayouts[VBAP2D_MAX_SPEAKER_COUNT-3] = { // -3 to skip mono/stereo/2.1
{ VBAP2D_SpeakerPositions_quad, -1 },
{ VBAP2D_SpeakerPositions_4_1, 2 },
{ VBAP2D_SpeakerPositions_5_1, 3 },
{ VBAP2D_SpeakerPositions_6_1, 3 },
{ VBAP2D_SpeakerPositions_7_1, 3 }
};
#undef P
typedef struct VBAP2D_Bucket { Uint8 speaker_pair; } VBAP2D_Bucket;
typedef struct VBAP2D_Matrix { float a00, a01, a10, a11; } VBAP2D_Matrix;
typedef struct VBAP2D
{
int speaker_count;
VBAP2D_Bucket buckets[VBAP2D_RESOLUTION];
VBAP2D_Matrix matrices[VBAP2D_MAX_SPEAKER_COUNT-1]; // the upper ones all have an LFE channel, which we don't track here, so minus one.
} VBAP2D;
static void VBAP2D_Init(VBAP2D *vbap2d, int speaker_count)
{
SDL_assert(speaker_count > 0);
SDL_assert(speaker_count <= VBAP2D_MAX_SPEAKER_COUNT);
SDL_assert(VBAP2D_RESOLUTION <= VBAP2D_MAX_RESOLUTION);
if (speaker_count < 4) {
return; // no VBAP for mono, stereo, or 2.1.
}
const VBAP2D_SpeakerLayout *speaker_layout = &VBAP2D_SpeakerLayouts[speaker_count - 4]; // offset to zero, skip mono/stereo/2.1
const VBAP2D_SpeakerPosition *speaker_positions = speaker_layout->positions;
vbap2d->speaker_count = speaker_count;
if (speaker_layout->lfe_channel >= 0) {
speaker_count--; // for our purposes, collapse out the subwoofer channel
}
VBAP2D_Bucket *buckets = vbap2d->buckets;
for (int division = 0, speaker_pair = 0; division < VBAP2D_RESOLUTION; division++) {
int speakers[2];
VBAP2D_unpack_speaker_pair(speaker_pair, speaker_count, speakers);
const int last_division = speaker_positions[speakers[0]].division;
const int next_division = speaker_positions[speakers[1]].division;
if (!VBAP2D_contains(division, last_division, next_division)) {
speaker_pair = (speaker_pair + 1) % speaker_count;
}
buckets[division].speaker_pair = speaker_pair;
}
VBAP2D_Matrix *matrices = vbap2d->matrices;
for (int speaker_pair = 0; speaker_pair < speaker_count; speaker_pair++) {
int speakers[2];
VBAP2D_unpack_speaker_pair(speaker_pair, speaker_count, speakers);
const int last_division = speaker_positions[speakers[0]].division;
const int next_division = speaker_positions[speakers[1]].division;
const float last_angle = VBAP2D_division_to_angle(last_division);
const float next_angle = VBAP2D_division_to_angle(next_division);
const float a00 = SDL_cosf(last_angle), a01 = SDL_cosf(next_angle);
const float a10 = SDL_sinf(last_angle), a11 = SDL_sinf(next_angle);
const float det = 1.0f / (a00 * a11 - a01 * a10);
matrices[speaker_pair].a00 = +a11 * det;
matrices[speaker_pair].a01 = -a01 * det;
matrices[speaker_pair].a10 = -a10 * det;
matrices[speaker_pair].a11 = +a00 * det;
}
}
static void VBAP2D_CalculateGains(const VBAP2D *vbap2d, float source_angle, float *gains, int *speakers)
{
int speaker_count = vbap2d->speaker_count;
SDL_assert(speaker_count >= 4);
const VBAP2D_SpeakerLayout *speaker_layout = &VBAP2D_SpeakerLayouts[speaker_count - 4]; // offset to zero, skip mono/stereo/2.1
if (speaker_layout->lfe_channel >= 0) {
speaker_count--; // for our purposes, collapse out the subwoofer channel
}
// shift so angle 0 is due east instead of due north, and normalize it to the 0 to 2pi range.
source_angle += SDL_PI_F / 2.0f;
while (source_angle < 0.0f) {
source_angle += 2.0f * SDL_PI_F;
}
while (source_angle > (2.0f * SDL_PI_F)) {
source_angle -= 2.0f * SDL_PI_F;
}
const float source_x = SDL_cosf(source_angle);
const float source_y = SDL_sinf(source_angle);
const int span = VBAP2D_angle_to_span(source_angle);
const int speaker_pair = vbap2d->buckets[span].speaker_pair;
int vbap_speakers[2];
VBAP2D_unpack_speaker_pair(speaker_pair, speaker_count, vbap_speakers);
const VBAP2D_Matrix *matrix = &vbap2d->matrices[speaker_pair];
const float gain_a = source_x * matrix->a00 + source_y * matrix->a01;
const float gain_b = source_x * matrix->a10 + source_y * matrix->a11;
const float scale = 1.0f / SDL_sqrtf(gain_a * gain_a + gain_b * gain_b);
const float gain_a_normalized = gain_a * scale;
const float gain_b_normalized = gain_b * scale;
speakers[0] = speaker_layout->positions[vbap_speakers[0]].sdl_channel;
speakers[1] = speaker_layout->positions[vbap_speakers[1]].sdl_channel;
gains[0] = gain_a_normalized;
gains[1] = gain_b_normalized;
}
// end VBAP code.
typedef struct ALbuffer
{
ALboolean allocated;
ALuint name;
SDL_AudioSpec spec;
ALsizei len; // length of data in bytes.
const void *data;
ALBUFFERCALLBACKTYPESOFT callback; // AL_SOFT_callback_buffer extension. `data` must be NULL if this is used!
void *callback_userptr; // AL_SOFT_callback_buffer extension.
SDL_AtomicInt refcount; // if zero, can be deleted or alBufferData'd
} ALbuffer;
// !!! FIXME: buffers and sources use almost identical code for blocks
typedef struct BufferBlock
{
ALbuffer buffers[OPENAL_BUFFER_BLOCK_SIZE]; // allocate these in blocks so we can step through faster.
ALuint used;
ALuint tmp; // only touch under api_lock, assume it'll be gone later.
} BufferBlock;
typedef struct BufferQueueItem
{
ALbuffer *buffer;
void *next; // void* because we'll atomicgetptr it.
} BufferQueueItem;
typedef struct BufferQueue
{
void *just_queued; // void* because we'll atomicgetptr it.
BufferQueueItem *head;
BufferQueueItem *tail;
SDL_AtomicInt num_items; // counts just_queued+head/tail
} BufferQueue;
typedef struct ALsource ALsource;
struct SDL_ALIGNED(16) ALsource // aligned to 16 bytes for SIMD support
{
// keep these first to help guarantee that its elements are aligned for SIMD
ALfloat position[4];
ALfloat velocity[4];
ALfloat direction[4];
int speakers[2]; // speakers we will play through (at max, currently, it's never more than 2 of them).
ALfloat panning[2];
SDL_AtomicInt mixer_accessible;
SDL_AtomicInt state; // initial, playing, paused, stopped
ALuint name;
ALboolean allocated;
ALenum type; // undetermined, static, streaming
ALboolean recalc;
ALboolean source_relative;
ALboolean looping;
ALfloat gain;
ALfloat min_gain;
ALfloat max_gain;
ALfloat reference_distance;
ALfloat max_distance;
ALfloat rolloff_factor;
ALfloat pitch;
ALfloat cone_inner_angle;
ALfloat cone_outer_angle;
ALfloat cone_outer_gain;
ALenum distance_model;
ALbuffer *buffer;
SDL_AudioStream *stream; // for conversion, resampling, pitch, etc. ALL DATA GOES THROUGH HERE NOW.
SDL_AtomicInt total_queued_buffers; // everything queued, playing and processed. AL_BUFFERS_QUEUED value.
BufferQueue buffer_queue;
BufferQueue buffer_queue_processed;
ALsizei offset; // offset in bytes for converted stream!
ALboolean offset_latched; // AL_SEC_OFFSET, etc, say set values apply to next alSourcePlay if not currently playing!
ALint queue_channels;
ALsizei queue_frequency;
ALsource *playlist_next; // linked list that contains currently-playing sources! Only touched by mixer thread!
ALboolean callback_exhausted; // AL_SOFT_callback_buffer extension.
};
// !!! FIXME: buffers and sources use almost identical code for blocks
typedef struct SourceBlock
{
ALsource sources[OPENAL_SOURCE_BLOCK_SIZE]; // allocate these in blocks so we can step through faster.
ALuint used;
ALuint tmp; // only touch under api_lock, assume it'll be gone later.
} SourceBlock;
typedef struct SourcePlayTodo
{
ALsource *source;
struct SourcePlayTodo *next;
} SourcePlayTodo;
struct ALCdevice_struct
{
SDL_AudioDeviceID device_id; // physical device ID (or default).
char *name;
ALCenum error;
SDL_AtomicInt connected;
ALCboolean iscapture;
float *mix_buffer;
ALCsizei mix_buffer_len;
float *get_buffer;
ALCsizei get_buffer_len;
union {
struct {
ALCcontext *contexts;
BufferBlock **buffer_blocks; // buffers are shared between contexts on the same device.
ALCsizei num_buffer_blocks;
BufferQueueItem *buffer_queue_pool; // mixer thread doesn't touch this.
void *source_todo_pool; // void* because we'll atomicgetptr it.
} playback;
struct {
SDL_AudioStream *stream;
SDL_AudioSpec spec;
ALCsizei framesize;
ALCsizei max_samples;
} capture;
};
};
struct ALCcontext_struct
{
// keep these first to help guarantee that its elements are aligned for SIMD
struct SDL_ALIGNED(16) {
ALfloat position[4];
ALfloat velocity[4];
ALfloat orientation[8];
ALfloat gain;
} listener;
SourceBlock **source_blocks;
ALsizei num_source_blocks;
ALCdevice *device;
SDL_AudioStream *stream;
SDL_AudioDeviceID device_id; // logical device id.
VBAP2D vbap2d;
SDL_AudioSpec spec;
ALCsizei framesize;
SDL_AtomicInt processing;
ALenum error;
ALCint *attributes;
ALCsizei attributes_count;
ALCboolean recalc;
ALCboolean source_distance_model;
ALenum distance_model;
ALfloat doppler_factor;
ALfloat doppler_velocity;
ALfloat speed_of_sound;
void *playlist_todo; // void* so we can AtomicCASPtr it. Transmits new play commands from api thread to mixer thread
ALsource *playlist; // linked list of currently-playing sources. Mixer thread only!
ALsource *playlist_tail; // end of playlist so we know if last item is being readded. Mixer thread only!
ALCcontext *prev; // contexts are in a double-linked list
ALCcontext *next;
};
// forward declarations
static float source_get_offset(ALsource *src, ALenum param);
static void source_set_offset(ALsource *src, ALenum param, ALfloat value);
static void lock_source(ALsource *src)
{
SDL_LockAudioStream(src->stream);
}
static void unlock_source(ALsource *src)
{
SDL_UnlockAudioStream(src->stream);
}
// the just_queued list is backwards. Add it to the queue in the correct order.
static void queue_new_buffer_items_recursive(BufferQueue *queue, BufferQueueItem *items)
{
if (items == NULL) {
return;
}
queue_new_buffer_items_recursive(queue, (BufferQueueItem*)items->next);
items->next = NULL;
if (queue->tail) {
queue->tail->next = items;
} else {
queue->head = items;
}
queue->tail = items;
}
static void obtain_newly_queued_buffers(BufferQueue *queue)
{
BufferQueueItem *items;
do {
items = (BufferQueueItem *) SDL_GetAtomicPointer(&queue->just_queued);
} while (!SDL_CompareAndSwapAtomicPointer(&queue->just_queued, items, NULL));
// Now that we own this pointer, we can just do whatever we want with it.
// Nothing touches the head/tail fields other than the mixer thread, so we
// move it there. Not even atomically! :)
SDL_assert((queue->tail != NULL) == (queue->head != NULL));
queue_new_buffer_items_recursive(queue, items);
}
// You probably need to hold a lock before you call this (currently).
static void source_mark_all_buffers_processed(ALsource *src)
{
obtain_newly_queued_buffers(&src->buffer_queue);
while (src->buffer_queue.head) {
void *ptr;
BufferQueueItem *item = src->buffer_queue.head;
src->buffer_queue.head = (BufferQueueItem*)item->next;
SDL_AddAtomicInt(&src->buffer_queue.num_items, -1);
// Move it to the processed queue for alSourceUnqueueBuffers() to pick up.
do {
ptr = SDL_GetAtomicPointer(&src->buffer_queue_processed.just_queued);
SDL_SetAtomicPointer(&item->next, ptr);
} while (!SDL_CompareAndSwapAtomicPointer(&src->buffer_queue_processed.just_queued, ptr, item));
SDL_AddAtomicInt(&src->buffer_queue_processed.num_items, 1);
}
src->buffer_queue.tail = NULL;
}
/* several things might be touching an ALbuffer's data: source streams that NoCopy'd it, alBufferData() replacing it, etc.
we overallocate the data, and stick a refcount before the aligned data, one SIMD alignment before it. When everything
touching it drops its reference, it's safe to free it. */
static void SDLCALL albuffer_in_audiostream_complete(void *userdata, const void *buf, int buflen)
{
SDL_AtomicInt *refcount = (SDL_AtomicInt *) userdata;
if (SDL_AtomicDecRef(refcount)) {
SDL_aligned_free((void *) refcount);
}
}
static void put_albuffer_to_audiostream(ALCcontext *ctx, ALbuffer *buffer, int offset, SDL_AudioStream *stream)
{
if (buffer) {
const SDL_AudioSpec output_spec = { SDL_AUDIO_F32, buffer->spec.channels, ctx->spec.freq };
SDL_SetAudioStreamFormat(stream, &buffer->spec, &output_spec);
if (!buffer->callback) {
SDL_AtomicInt *refcount = (SDL_AtomicInt *) (((Uint8 *) buffer->data) - simd_alignment);
SDL_AtomicIncRef(refcount);
SDL_PutAudioStreamDataNoCopy(stream, ((const Uint8 *) buffer->data) + offset, buffer->len - offset, albuffer_in_audiostream_complete, refcount);
}
}
}
static void source_release_buffer_queue(ALCcontext *ctx, ALsource *src)
{
// move any buffer queue items to the device's available pool for reuse.
obtain_newly_queued_buffers(&src->buffer_queue);
if (src->buffer_queue.tail != NULL) {
BufferQueueItem *i;
for (i = src->buffer_queue.head; i; i = (BufferQueueItem*)i->next) {
(void) SDL_AtomicDecRef(&i->buffer->refcount);
}
src->buffer_queue.tail->next = ctx->device->playback.buffer_queue_pool;
ctx->device->playback.buffer_queue_pool = src->buffer_queue.head;
}
src->buffer_queue.head = src->buffer_queue.tail = NULL;
SDL_SetAtomicInt(&src->buffer_queue.num_items, 0);
obtain_newly_queued_buffers(&src->buffer_queue_processed);
if (src->buffer_queue_processed.tail != NULL) {
BufferQueueItem *i;
for (i = src->buffer_queue_processed.head; i; i = (BufferQueueItem*)i->next) {
(void) SDL_AtomicDecRef(&i->buffer->refcount);
}
src->buffer_queue_processed.tail->next = ctx->device->playback.buffer_queue_pool;
ctx->device->playback.buffer_queue_pool = src->buffer_queue_processed.head;
}
src->buffer_queue_processed.head = src->buffer_queue_processed.tail = NULL;
SDL_SetAtomicInt(&src->buffer_queue_processed.num_items, 0);
}
// Spatialization ...
// All the 3D math here is way overcommented because I HAVE NO IDEA WHAT I'M
// DOING and had to research the hell out of what are probably pretty simple
// concepts. Pay attention in math class, kids.
//
// The scalar versions have explanitory comments and links. The SIMD versions don't.
//
// The work starts in calculate_channel_gains(). Everything between here and there
// is math support code.
/* Get the sin(angle) and cos(angle) at the same time. Ideally, with one
instruction, like what is offered on the x86.
angle is in radians, not degrees. */
static void calculate_sincos(const ALfloat angle, ALfloat *_sin, ALfloat *_cos)
{
*_sin = SDL_sinf(angle);
*_cos = SDL_cosf(angle);
}
static ALfloat calculate_distance_attenuation(const ALCcontext *ctx, const ALsource *src, ALfloat distance)
{
// AL SPEC: "With all the distance models, if the formula can not be
// evaluated then the source will not be attenuated. For example, if a
// linear model is being used with AL_REFERENCE_DISTANCE equal to
// AL_MAX_DISTANCE, then the gain equation will have a divide-by-zero
// error in it. In this case, there is no attenuation for that source."
FIXME("check divisions by zero");
const ALenum distance_model = ctx->source_distance_model ? src->distance_model : ctx->distance_model;
switch (ctx->distance_model) {
case AL_INVERSE_DISTANCE_CLAMPED:
distance = SDL_min(SDL_max(distance, src->reference_distance), src->max_distance);
SDL_FALLTHROUGH;
case AL_INVERSE_DISTANCE:
// AL SPEC: "gain = AL_REFERENCE_DISTANCE / (AL_REFERENCE_DISTANCE + AL_ROLLOFF_FACTOR * (distance - AL_REFERENCE_DISTANCE))"
return src->reference_distance / (src->reference_distance + src->rolloff_factor * (distance - src->reference_distance));
case AL_LINEAR_DISTANCE_CLAMPED:
distance = SDL_max(distance, src->reference_distance);
SDL_FALLTHROUGH;
case AL_LINEAR_DISTANCE:
// AL SPEC: "distance = min(distance, AL_MAX_DISTANCE) // avoid negative gain
// gain = (1 - AL_ROLLOFF_FACTOR * (distance - AL_REFERENCE_DISTANCE) / (AL_MAX_DISTANCE - AL_REFERENCE_DISTANCE))"
return 1.0f - src->rolloff_factor * (SDL_min(distance, src->max_distance) - src->reference_distance) / (src->max_distance - src->reference_distance);
case AL_EXPONENT_DISTANCE_CLAMPED:
distance = SDL_min(SDL_max(distance, src->reference_distance), src->max_distance);
SDL_FALLTHROUGH;
case AL_EXPONENT_DISTANCE:
// AL SPEC: "gain = (distance / AL_REFERENCE_DISTANCE) ^ (- AL_ROLLOFF_FACTOR)"
return SDL_powf(distance / src->reference_distance, -src->rolloff_factor);
default: break;
}
SDL_assert(!"Unexpected distance model");
return 1.0f;
}
#if NEED_SCALAR_FALLBACK
// XYZZY!! https://en.wikipedia.org/wiki/Cross_product#Mnemonic
//
// Calculates cross product. https://en.wikipedia.org/wiki/Cross_product
// Basically takes two vectors and gives you a vector that's perpendicular
// to both.
static void xyzzy_scalar(ALfloat *v, const ALfloat *a, const ALfloat *b)
{
v[0] = (a[1] * b[2]) - (a[2] * b[1]);
v[1] = (a[2] * b[0]) - (a[0] * b[2]);
v[2] = (a[0] * b[1]) - (a[1] * b[0]);
}
// calculate dot product (multiply each element of two vectors, sum them)
static ALfloat dotproduct_scalar(const ALfloat *a, const ALfloat *b)
{
return (a[0] * b[0]) + (a[1] * b[1]) + (a[2] * b[2]);
}
// calculate distance ("magnitude") in 3D space:
// https://math.stackexchange.com/questions/42640/calculate-distance-in-3d-space
// assumes vector starts at (0,0,0).
static ALfloat magnitude_scalar(const ALfloat *v)
{
// technically, the inital part on this is just a dot product of itself.
return SDL_sqrtf((v[0] * v[0]) + (v[1] * v[1]) + (v[2] * v[2]));
}
static void calculate_distance_attenuation_and_angle_scalar(const ALCcontext *ctx, const ALsource *src, ALfloat *_gain, ALfloat *_radians)
{
const ALfloat *at = &ctx->listener.orientation[0];
const ALfloat *up = &ctx->listener.orientation[4];
// If !source_relative, position is in world space, otherwise, it's in relation to the Listener's position.
// So a source-relative source that's at ( 0, 0, 0 ) will be treated as being on top of the listener,
// no matter where the listener moves. If not source relative, it'll get quieter as the listener moves away.
ALfloat position[3];
if (!src->source_relative) {
position[0] = src->position[0] - ctx->listener.position[0];
position[1] = src->position[1] - ctx->listener.position[1];
position[2] = src->position[2] - ctx->listener.position[2];
} else {
position[0] = src->position[0];
position[1] = src->position[1];
position[2] = src->position[2];
}
// Remove upwards component so it lies completely within the horizontal plane.
const ALfloat a = dotproduct_scalar(position, up);
ALfloat V[3];
V[0] = position[0] - (a * up[0]);
V[1] = position[1] - (a * up[1]);
V[2] = position[2] - (a * up[2]);
// Calculate angle
const ALfloat mags = magnitude_scalar(at) * magnitude_scalar(V);
ALfloat radians;
if (mags == 0.0f) {
radians = 0.0f;
} else {
ALfloat cosangle = dotproduct_scalar(at, V) / mags;
cosangle = SDL_clamp(cosangle, -1.0f, 1.0f);
radians = SDL_acosf(cosangle);
}
ALfloat R[3];
xyzzy_scalar(R, at, up); // Get "right" vector
*_radians = (dotproduct_scalar(R, V) < 0.0f) ? -radians : radians; // make it negative to the left, positive to the right.
*_gain = calculate_distance_attenuation(ctx, src, magnitude_scalar(position));
}
#endif
#if defined(SDL_SSE_INTRINSICS)
static __m128 SDL_TARGETING("sse") xyzzy_sse(const __m128 a, const __m128 b)
{
// http://fastcpp.blogspot.com/2011/04/vector-cross-product-using-sse-code.html
// this is the "three shuffle" version in the comments, plus the variables swapped around for handedness in the later comment.
const __m128 v = _mm_sub_ps(
_mm_mul_ps(a, _mm_shuffle_ps(b, b, _MM_SHUFFLE(3, 0, 2, 1))),
_mm_mul_ps(b, _mm_shuffle_ps(a, a, _MM_SHUFFLE(3, 0, 2, 1)))
);
return _mm_shuffle_ps(v, v, _MM_SHUFFLE(3, 0, 2, 1));
}
static ALfloat SDL_TARGETING("sse") dotproduct_sse(const __m128 a, const __m128 b)
{
const __m128 prod = _mm_mul_ps(a, b);
const __m128 sum1 = _mm_add_ps(prod, _mm_shuffle_ps(prod, prod, _MM_SHUFFLE(1, 0, 3, 2)));
const __m128 sum2 = _mm_add_ps(sum1, _mm_shuffle_ps(sum1, sum1, _MM_SHUFFLE(2, 2, 0, 0)));
FIXME("this can use _mm_hadd_ps in SSE3, or _mm_dp_ps in SSE4.1");
return _mm_cvtss_f32(_mm_shuffle_ps(sum2, sum2, _MM_SHUFFLE(3, 3, 3, 3)));
}
static ALfloat SDL_TARGETING("sse") magnitude_sse(const __m128 v)
{
return SDL_sqrtf(dotproduct_sse(v, v));
}
static void SDL_TARGETING("sse") calculate_distance_attenuation_and_angle_sse(const ALCcontext *ctx, const ALsource *src, ALfloat *_gain, ALfloat *_radians)
{
// (the math is explained in the scalar version.)
const __m128 position_sse = !src->source_relative ? _mm_sub_ps(_mm_load_ps(src->position), _mm_load_ps(ctx->listener.position)) : _mm_load_ps(src->position);
const __m128 at_sse = _mm_load_ps(&ctx->listener.orientation[0]);
const __m128 up_sse = _mm_load_ps(&ctx->listener.orientation[4]);
const ALfloat a = dotproduct_sse(position_sse, up_sse);
const __m128 V_sse = _mm_sub_ps(position_sse, _mm_mul_ps(_mm_set1_ps(a), up_sse));
const ALfloat mags = magnitude_sse(at_sse) * magnitude_sse(V_sse);
ALfloat radians;
if (mags == 0.0f) {
radians = 0.0f;
} else {
ALfloat cosangle = dotproduct_sse(at_sse, V_sse) / mags;
cosangle = SDL_clamp(cosangle, -1.0f, 1.0f);
radians = SDL_acosf(cosangle);
}
const __m128 R_sse = xyzzy_sse(at_sse, up_sse);
*_radians = (dotproduct_sse(R_sse, V_sse) < 0.0f) ? -radians : radians;
*_gain = calculate_distance_attenuation(ctx, src, magnitude_sse(position_sse));
}
#endif
#if defined(SDL_NEON_INTRINSICS)
static float32x4_t SDL_TARGETING("neon") xyzzy_neon(const float32x4_t a, const float32x4_t b)
{
const float32x4_t shuf_a = { a[1], a[2], a[0], a[3] };
const float32x4_t shuf_b = { b[1], b[2], b[0], b[3] };
const float32x4_t v = vsubq_f32(vmulq_f32(a, shuf_b), vmulq_f32(b, shuf_a));
const float32x4_t retval = { v[1], v[2], v[0], v[3] };
FIXME("need a better permute");
return retval;
}
static ALfloat SDL_TARGETING("neon") dotproduct_neon(const float32x4_t a, const float32x4_t b)
{
const float32x4_t prod = vmulq_f32(a, b);
const float32x4_t sum1 = vaddq_f32(prod, vrev64q_f32(prod));
const float32x4_t sum2 = vaddq_f32(sum1, vcombine_f32(vget_high_f32(sum1), vget_low_f32(sum1)));
return sum2[3];
}
static ALfloat SDL_TARGETING("neon") magnitude_neon(const float32x4_t v)
{
return SDL_sqrtf(dotproduct_neon(v, v));
}
static void SDL_TARGETING("neon") calculate_distance_attenuation_and_angle_neon(const ALCcontext *ctx, const ALsource *src, ALfloat *_gain, ALfloat *_radians)
{
// (the math is explained in the scalar version.)
const float32x4_t position_neon = !src->source_relative ? vsubq_f32(vld1q_f32(src->position), vld1q_f32(ctx->listener.position)) : vld1q_f32(src->position);
const float32x4_t at_neon = vld1q_f32(&ctx->listener.orientation[0]);
const float32x4_t up_neon = vld1q_f32(&ctx->listener.orientation[4]);
const ALfloat a = dotproduct_neon(position_neon, up_neon);
const float32x4_t V_neon = vsubq_f32(position_neon, vmulq_f32(vdupq_n_f32(a), up_neon));
const ALfloat mags = magnitude_neon(at_neon) * magnitude_neon(V_neon);
ALfloat radians;
if (mags == 0.0f) {
radians = 0.0f;
} else {
ALfloat cosangle = dotproduct_neon(at_neon, V_neon) / mags;
cosangle = SDL_clamp(cosangle, -1.0f, 1.0f);
radians = SDL_acosf(cosangle);
}
const float32x4_t R_neon = xyzzy_neon(at_neon, up_neon);
*_radians = (dotproduct_neon(R_neon, V_neon) < 0.0f) ? -radians : radians;
*_gain = calculate_distance_attenuation(ctx, src, magnitude_neon(position_neon));
}
#endif
static void calculate_distance_attenuation_and_angle(const ALCcontext *ctx, const ALsource *src, float *_gain, float *_radians)
{
SDL_assert( IS_SIMD_ALIGNED(&src->position[0]) ); // source position must be aligned for SIMD access.