forked from KhronosGroup/Vulkan-Tutorial
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathaudio_system.cpp
More file actions
1556 lines (1278 loc) · 58.2 KB
/
audio_system.cpp
File metadata and controls
1556 lines (1278 loc) · 58.2 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
#include "audio_system.h"
#include <cassert>
#include <cmath>
#include <cstring>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <thread>
#include <chrono>
#include <queue>
#include <mutex>
#include <utility>
#include <unordered_map>
#include <algorithm>
// OpenAL headers
#ifdef __APPLE__
#include <OpenAL/al.h>
#include <OpenAL/alc.h>
#else
#include <AL/al.h>
#include <AL/alc.h>
#endif
#include "renderer.h"
#include "engine.h"
// OpenAL error checking utility
static void CheckOpenALError(const std::string& operation) {
ALenum error = alGetError();
if (error != AL_NO_ERROR) {
std::cerr << "OpenAL Error in " << operation << ": ";
switch (error) {
case AL_INVALID_NAME:
std::cerr << "AL_INVALID_NAME";
break;
case AL_INVALID_ENUM:
std::cerr << "AL_INVALID_ENUM";
break;
case AL_INVALID_VALUE:
std::cerr << "AL_INVALID_VALUE";
break;
case AL_INVALID_OPERATION:
std::cerr << "AL_INVALID_OPERATION";
break;
case AL_OUT_OF_MEMORY:
std::cerr << "AL_OUT_OF_MEMORY";
break;
default:
std::cerr << "Unknown error " << error;
break;
}
std::cerr << std::endl;
}
}
// Concrete implementation of AudioSource
class ConcreteAudioSource : public AudioSource {
public:
explicit ConcreteAudioSource(std::string name) : name(std::move(name)) {}
~ConcreteAudioSource() override = default;
void Play() override {
playing = true;
playbackPosition = 0;
delayTimer = std::chrono::milliseconds(0);
inDelayPhase = false;
sampleAccumulator = 0.0;
}
void Pause() override {
playing = false;
}
void Stop() override {
playing = false;
playbackPosition = 0;
delayTimer = std::chrono::milliseconds(0);
inDelayPhase = false;
sampleAccumulator = 0.0;
}
void SetVolume(float volume) override {
this->volume = volume;
}
void SetLoop(bool loop) override {
this->loop = loop;
}
void SetPosition(float x, float y, float z) override {
position[0] = x;
position[1] = y;
position[2] = z;
}
void SetVelocity(float x, float y, float z) override {
velocity[0] = x;
velocity[1] = y;
velocity[2] = z;
}
[[nodiscard]] bool IsPlaying() const override {
return playing;
}
// Additional methods for delay functionality
void SetAudioLength(uint32_t lengthInSamples) {
audioLengthSamples = lengthInSamples;
}
void UpdatePlayback(std::chrono::milliseconds deltaTime, uint32_t samplesProcessed) {
if (!playing) return;
if (inDelayPhase) {
// We're in the delay phase between playthroughs
delayTimer += deltaTime;
if (delayTimer >= delayDuration) {
// Delay finished, restart playback
inDelayPhase = false;
playbackPosition = 0;
delayTimer = std::chrono::milliseconds(0);
}
} else {
// Normal playback, update position
playbackPosition += samplesProcessed;
// Check if we've reached the end of the audio
if (audioLengthSamples > 0 && playbackPosition >= audioLengthSamples) {
if (loop) {
// Start the delay phase before looping
inDelayPhase = true;
delayTimer = std::chrono::milliseconds(0);
} else {
// Stop playing if not looping
playing = false;
playbackPosition = 0;
}
}
}
}
[[nodiscard]] bool ShouldProcessAudio() const {
return playing && !inDelayPhase;
}
[[nodiscard]] uint32_t GetPlaybackPosition() const {
return playbackPosition;
}
[[nodiscard]] const std::string& GetName() const {
return name;
}
[[nodiscard]] const float* GetPosition() const {
return position;
}
[[nodiscard]] double GetSampleAccumulator() const {
return sampleAccumulator;
}
void SetSampleAccumulator(double value) {
sampleAccumulator = value;
}
private:
std::string name;
bool playing = false;
bool loop = false;
float volume = 1.0f;
float position[3] = {0.0f, 0.0f, 0.0f};
float velocity[3] = {0.0f, 0.0f, 0.0f};
// Delay and timing functionality
uint32_t playbackPosition = 0; // Current position in samples
uint32_t audioLengthSamples = 0; // Total length of audio in samples
std::chrono::milliseconds delayTimer = std::chrono::milliseconds(0); // Timer for delay between loops
bool inDelayPhase = false; // Whether we're currently in the delay phase
static constexpr std::chrono::milliseconds delayDuration = std::chrono::milliseconds(1500); // 1.5-second delay between loops
double sampleAccumulator = 0.0; // Per-source sample accumulator for proper timing
};
// OpenAL audio output device implementation
class OpenALAudioOutputDevice : public AudioOutputDevice {
public:
OpenALAudioOutputDevice() = default;
~OpenALAudioOutputDevice() override {
OpenALAudioOutputDevice::Stop();
Cleanup();
}
bool Initialize(uint32_t sampleRate, uint32_t channels, uint32_t bufferSize) override {
this->sampleRate = sampleRate;
this->channels = channels;
this->bufferSize = bufferSize;
// Initialize OpenAL
device = alcOpenDevice(nullptr); // Use default device
if (!device) {
std::cerr << "Failed to open OpenAL device" << std::endl;
return false;
}
context = alcCreateContext(device, nullptr);
if (!context) {
std::cerr << "Failed to create OpenAL context" << std::endl;
alcCloseDevice(device);
device = nullptr;
return false;
}
if (!alcMakeContextCurrent(context)) {
std::cerr << "Failed to make OpenAL context current" << std::endl;
alcDestroyContext(context);
alcCloseDevice(device);
context = nullptr;
device = nullptr;
return false;
}
// Generate OpenAL source
alGenSources(1, &source);
CheckOpenALError("alGenSources");
// Generate OpenAL buffers for streaming
alGenBuffers(NUM_BUFFERS, buffers);
CheckOpenALError("alGenBuffers");
// Set source properties
alSourcef(source, AL_PITCH, 1.0f);
alSourcef(source, AL_GAIN, 1.0f);
alSource3f(source, AL_POSITION, 0.0f, 0.0f, 0.0f);
alSource3f(source, AL_VELOCITY, 0.0f, 0.0f, 0.0f);
alSourcei(source, AL_LOOPING, AL_FALSE);
CheckOpenALError("Source setup");
// Initialize audio buffer
audioBuffer.resize(bufferSize * channels);
// Initialize buffer tracking
queuedBufferCount = 0;
while (!availableBuffers.empty()) {
availableBuffers.pop();
}
initialized = true;
return true;
}
bool Start() override {
if (!initialized) {
std::cerr << "OpenAL audio output device not initialized" << std::endl;
return false;
}
if (playing) {
return true; // Already playing
}
playing = true;
// Start an audio playback thread
audioThread = std::thread(&OpenALAudioOutputDevice::AudioThreadFunction, this);
return true;
}
bool Stop() override {
if (!playing) {
return true; // Already stopped
}
playing = false;
// Wait for the audio thread to finish
if (audioThread.joinable()) {
audioThread.join();
}
// Stop OpenAL source
if (initialized && source != 0) {
alSourceStop(source);
CheckOpenALError("alSourceStop");
}
return true;
}
bool WriteAudio(const float* data, uint32_t sampleCount) override {
if (!initialized || !playing) {
return false;
}
std::lock_guard<std::mutex> lock(bufferMutex);
// Add audio data to the queue
for (uint32_t i = 0; i < sampleCount * channels; i++) {
audioQueue.push(data[i]);
}
return true;
}
[[nodiscard]] bool IsPlaying() const override {
return playing;
}
[[nodiscard]] uint32_t GetPosition() const override {
return playbackPosition;
}
private:
static constexpr int NUM_BUFFERS = 8;
uint32_t sampleRate = 44100;
uint32_t channels = 2;
uint32_t bufferSize = 1024;
bool initialized = false;
bool playing = false;
uint32_t playbackPosition = 0;
// OpenAL objects
ALCdevice* device = nullptr;
ALCcontext* context = nullptr;
ALuint source = 0;
ALuint buffers[NUM_BUFFERS]{};
int currentBuffer = 0;
std::vector<float> audioBuffer;
std::queue<float> audioQueue;
std::mutex bufferMutex;
std::thread audioThread;
// Buffer management for OpenAL streaming
std::queue<ALuint> availableBuffers;
int queuedBufferCount = 0;
void Cleanup() {
if (initialized) {
// Clean up OpenAL resources
if (source != 0) {
alDeleteSources(1, &source);
source = 0;
}
alDeleteBuffers(NUM_BUFFERS, buffers);
if (context) {
alcMakeContextCurrent(nullptr);
alcDestroyContext(context);
context = nullptr;
}
if (device) {
alcCloseDevice(device);
device = nullptr;
}
// Reset buffer tracking
queuedBufferCount = 0;
while (!availableBuffers.empty()) {
availableBuffers.pop();
}
initialized = false;
}
}
void AudioThreadFunction() {
// Calculate sleep time for audio buffer updates (in milliseconds)
const auto sleepTime = std::chrono::milliseconds(
static_cast<int>((bufferSize * 1000) / sampleRate / 8) // Eighth buffer time for responsiveness
);
while (playing) {
ProcessAudioBuffer();
std::this_thread::sleep_for(sleepTime);
}
}
void ProcessAudioBuffer() {
std::lock_guard<std::mutex> lock(bufferMutex);
// Fill audio buffer from queue in whole stereo frames to preserve channel alignment
uint32_t samplesProcessed = 0;
const uint32_t framesAvailable = static_cast<uint32_t>(audioQueue.size() / channels);
if (framesAvailable == 0) {
// Not enough data for a whole frame yet
return;
}
const uint32_t framesToSend = std::min(framesAvailable, bufferSize);
const uint32_t samplesToSend = framesToSend * channels;
for (uint32_t i = 0; i < samplesToSend; i++) {
audioBuffer[i] = audioQueue.front();
audioQueue.pop();
}
samplesProcessed = samplesToSend;
if (samplesProcessed > 0) {
// Convert float samples to 16-bit PCM for OpenAL
std::vector<int16_t> pcmBuffer(samplesProcessed);
for (uint32_t i = 0; i < samplesProcessed; i++) {
// Clamp and convert to 16-bit PCM
float sample = std::clamp(audioBuffer[i], -1.0f, 1.0f);
pcmBuffer[i] = static_cast<int16_t>(sample * 32767.0f);
}
// Check for processed buffers and unqueue them
ALint processed = 0;
alGetSourcei(source, AL_BUFFERS_PROCESSED, &processed);
CheckOpenALError("alGetSourcei AL_BUFFERS_PROCESSED");
// Unqueue processed buffers and add them to available buffers
while (processed > 0) {
ALuint buffer;
alSourceUnqueueBuffers(source, 1, &buffer);
CheckOpenALError("alSourceUnqueueBuffers");
// Add the unqueued buffer to available buffers
availableBuffers.push(buffer);
processed--;
}
// Only proceed if we have an available buffer
ALuint buffer = 0;
if (!availableBuffers.empty()) {
buffer = availableBuffers.front();
availableBuffers.pop();
} else if (queuedBufferCount < NUM_BUFFERS) {
// Use a buffer that hasn't been queued yet
buffer = buffers[queuedBufferCount];
} else {
// No available buffers, skip this frame
return;
}
// Validate buffer parameters
if (pcmBuffer.empty()) {
// Re-add buffer to available list if we can't use it
if (queuedBufferCount >= NUM_BUFFERS) {
availableBuffers.push(buffer);
}
return;
}
// Determine format based on channels
ALenum format = (channels == 1) ? AL_FORMAT_MONO16 : AL_FORMAT_STEREO16;
// Upload audio data to OpenAL buffer
alBufferData(buffer, format, pcmBuffer.data(),
static_cast<ALsizei>(samplesProcessed * sizeof(int16_t)), static_cast<ALsizei>(sampleRate));
CheckOpenALError("alBufferData");
// Queue the buffer
alSourceQueueBuffers(source, 1, &buffer);
CheckOpenALError("alSourceQueueBuffers");
// Track that we've queued this buffer
if (queuedBufferCount < NUM_BUFFERS) {
queuedBufferCount++;
}
// Start playing if not already playing
ALint sourceState;
alGetSourcei(source, AL_SOURCE_STATE, &sourceState);
CheckOpenALError("alGetSourcei AL_SOURCE_STATE");
if (sourceState != AL_PLAYING) {
alSourcePlay(source);
CheckOpenALError("alSourcePlay");
}
playbackPosition += samplesProcessed / channels;
}
}
};
AudioSystem::~AudioSystem() {
// Stop the audio thread first
stopAudioThread();
// Stop and clean up audio output device
if (outputDevice) {
outputDevice->Stop();
outputDevice.reset();
}
// Destructor implementation
sources.clear();
audioData.clear();
// Clean up HRTF buffers
cleanupHRTFBuffers();
}
void AudioSystem::GenerateSineWavePing(float* buffer, uint32_t sampleCount, uint32_t playbackPosition) {
constexpr float sampleRate = 44100.0f;
const float frequency = 800.0f; // 800Hz ping
constexpr float pingDuration = 0.75f; // 0.75 second ping duration
constexpr auto pingSamples = static_cast<uint32_t>(pingDuration * sampleRate);
constexpr float silenceDuration = 1.0f; // 1 second silence after ping
constexpr auto silenceSamples = static_cast<uint32_t>(silenceDuration * sampleRate);
constexpr uint32_t totalCycleSamples = pingSamples + silenceSamples;
const uint32_t attackSamples = static_cast<uint32_t>(0.001f * sampleRate); // ~1ms attack
const uint32_t releaseSamples = static_cast<uint32_t>(0.001f * sampleRate); // ~1ms release
constexpr float amplitude = 0.6f;
for (uint32_t i = 0; i < sampleCount; i++) {
uint32_t globalPosition = playbackPosition + i;
uint32_t cyclePosition = globalPosition % totalCycleSamples;
if (cyclePosition < pingSamples) {
float t = static_cast<float>(cyclePosition) / sampleRate;
// Minimal envelope for click prevention only
float envelope = 1.0f;
if (cyclePosition < attackSamples) {
envelope = static_cast<float>(cyclePosition) / static_cast<float>(std::max(1u, attackSamples));
} else if (cyclePosition > pingSamples - releaseSamples) {
uint32_t relPos = pingSamples - cyclePosition;
envelope = static_cast<float>(relPos) / static_cast<float>(std::max(1u, releaseSamples));
}
float sineWave = sinf(2.0f * static_cast<float>(M_PI) * frequency * t);
buffer[i] = amplitude * envelope * sineWave;
} else {
// Silence phase
buffer[i] = 0.0f;
}
}
}
bool AudioSystem::Initialize(Engine* engine, Renderer* renderer) {
// Store the engine reference for accessing active camera
this->engine = engine;
if (renderer) {
// Validate renderer if provided
if (!renderer->IsInitialized()) {
std::cerr << "AudioSystem::Initialize: Renderer is not initialized" << std::endl;
return false;
}
// Store the renderer for compute shader support
this->renderer = renderer;
} else {
this->renderer = nullptr;
}
// Generate default HRTF data for spatial audio processing
LoadHRTFData(""); // Pass empty filename to force generation of default HRTF data
// Enable HRTF processing by default for 3D spatial audio
EnableHRTF(true);
// Set default listener properties
SetListenerPosition(0.0f, 0.0f, 0.0f);
SetListenerOrientation(0.0f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f);
SetListenerVelocity(0.0f, 0.0f, 0.0f);
SetMasterVolume(1.0f);
// Initialize audio output device
outputDevice = std::make_unique<OpenALAudioOutputDevice>();
if (!outputDevice->Initialize(44100, 2, 1024)) {
std::cerr << "Failed to initialize audio output device" << std::endl;
return false;
}
// Start audio output
if (!outputDevice->Start()) {
std::cerr << "Failed to start audio output device" << std::endl;
return false;
}
// Start the background audio processing thread
startAudioThread();
initialized = true;
return true;
}
void AudioSystem::Update(std::chrono::milliseconds deltaTime) {
if (!initialized) {
return;
}
// Synchronize HRTF listener position and orientation with active camera
if (engine) {
const CameraComponent* activeCamera = engine->GetActiveCamera();
if (activeCamera) {
// Get camera position
glm::vec3 cameraPos = activeCamera->GetPosition();
SetListenerPosition(cameraPos.x, cameraPos.y, cameraPos.z);
// Calculate camera forward and up vectors for orientation
// The camera looks at its target, so forward = normalize(target - position)
glm::vec3 target = activeCamera->GetTarget();
glm::vec3 up = activeCamera->GetUp();
glm::vec3 forward = glm::normalize(target - cameraPos);
SetListenerOrientation(forward.x, forward.y, forward.z, up.x, up.y, up.z);
}
}
// Update audio sources and process spatial audio
for (auto& source : sources) {
if (!source->IsPlaying()) {
continue;
}
// Cast to ConcreteAudioSource to access timing methods
auto* concreteSource = dynamic_cast<ConcreteAudioSource*>(source.get());
// Update playback timing and delay logic
concreteSource->UpdatePlayback(deltaTime, 0);
// Only process audio if not in the delay phase
if (!concreteSource->ShouldProcessAudio()) {
continue;
}
// Process audio with HRTF spatial processing (works with or without renderer)
if (hrtfEnabled && !hrtfData.empty()) {
// Get source position for spatial processing
const float* sourcePosition = concreteSource->GetPosition();
// Accumulate samples based on real time and process in fixed-size chunks to avoid tiny buffers
double acc = concreteSource->GetSampleAccumulator();
acc += (static_cast<double>(deltaTime.count()) * 44100.0) / 1000.0; // ms -> samples
constexpr uint32_t kChunk = 33075;
uint32_t available = static_cast<uint32_t>(acc);
if (available < kChunk) {
// Not enough for a full chunk; keep accumulating
concreteSource->SetSampleAccumulator(acc);
continue;
}
// Process as many full chunks as available this frame
while (available >= kChunk) {
std::vector<float> inputBuffer(kChunk, 0.0f);
std::vector<float> outputBuffer(kChunk * 2, 0.0f);
uint32_t actualSamplesProcessed = 0;
// Generate audio signal from loaded audio data or debug ping
auto audioIt = audioData.find(concreteSource->GetName());
if (audioIt != audioData.end() && !audioIt->second.empty()) {
// Use actual loaded audio data with proper position tracking
const auto& data = audioIt->second;
uint32_t playbackPos = concreteSource->GetPlaybackPosition();
for (uint32_t i = 0; i < kChunk; i++) {
uint32_t dataIndex = (playbackPos + i) * 4; // 4 bytes per sample (16-bit stereo)
if (dataIndex + 1 < data.size()) {
// Convert from 16-bit PCM to float
int16_t sample = *reinterpret_cast<const int16_t*>(&data[dataIndex]);
inputBuffer[i] = static_cast<float>(sample) / 32768.0f;
actualSamplesProcessed++;
} else {
// Reached end of audio data
inputBuffer[i] = 0.0f;
}
}
} else {
// Generate sine wave ping for debugging
GenerateSineWavePing(inputBuffer.data(), kChunk, concreteSource->GetPlaybackPosition());
actualSamplesProcessed = kChunk;
}
// Build extended input [history | current] to preserve convolution continuity across chunks
uint32_t histLen = (hrtfSize > 0) ? (hrtfSize - 1) : 0;
static std::unordered_map<ConcreteAudioSource*, std::vector<float>> hrtfHistories;
auto &hist = hrtfHistories[concreteSource];
if (hist.size() != histLen) {
hist.assign(histLen, 0.0f);
}
std::vector<float> extendedInput(histLen + kChunk, 0.0f);
if (histLen > 0) {
std::memcpy(extendedInput.data(), hist.data(), histLen * sizeof(float));
}
std::memcpy(extendedInput.data() + histLen, inputBuffer.data(), kChunk * sizeof(float));
// Submit for GPU HRTF processing via the background thread (trim will occur in processAudioTask)
submitAudioTask(extendedInput.data(), static_cast<uint32_t>(extendedInput.size()), sourcePosition, actualSamplesProcessed, histLen);
// Update history with the tail of current input
if (histLen > 0) {
std::memcpy(hist.data(), inputBuffer.data() + (kChunk - histLen), histLen * sizeof(float));
}
// Update playback timing with actual samples processed
concreteSource->UpdatePlayback(std::chrono::milliseconds(0), actualSamplesProcessed);
// Consume one chunk from the accumulator
acc -= static_cast<double>(kChunk);
available -= kChunk;
}
// Store fractional remainder for next frame
concreteSource->SetSampleAccumulator(acc);
}
}
// Apply master volume changes to all active sources
for (auto& source : sources) {
if (source->IsPlaying()) {
// Master volume is applied during HRTF processing and individual source volume control
// Volume scaling is handled in the ProcessHRTF function
}
}
// Clean up finished audio sources
std::erase_if(sources,
[](const std::unique_ptr<AudioSource>& source) {
// Keep all sources active for continuous playback
// Audio sources can be stopped/started via their Play/Stop methods
return false;
});
// Update timing for audio processing with low-latency chunks
static std::chrono::milliseconds accumulatedTime = std::chrono::milliseconds(0);
accumulatedTime += deltaTime;
// Process audio in 20ms chunks for optimal latency
constexpr std::chrono::milliseconds audioChunkTime = std::chrono::milliseconds(20); // 20ms chunks for real-time audio
if (accumulatedTime >= audioChunkTime) {
// Trigger audio buffer updates for smooth playback
// The HRTF processing ensures spatial audio is updated continuously
accumulatedTime = std::chrono::milliseconds(0);
// Update listener properties if they have changed
// This ensures spatial audio positioning stays current with camera movement
}
}
bool AudioSystem::LoadAudio(const std::string& filename, const std::string& name) {
// Open the WAV file
std::ifstream file(filename, std::ios::binary);
if (!file.is_open()) {
std::cerr << "Failed to open audio file: " << filename << std::endl;
return false;
}
// Read WAV header
struct WAVHeader {
char riff[4]; // "RIFF"
uint32_t fileSize; // File size - 8
char wave[4]; // "WAVE"
char fmt[4]; // "fmt "
uint32_t fmtSize; // Format chunk size
uint16_t audioFormat; // Audio format (1 = PCM)
uint16_t numChannels; // Number of channels
uint32_t sampleRate; // Sample rate
uint32_t byteRate; // Byte rate
uint16_t blockAlign; // Block align
uint16_t bitsPerSample; // Bits per sample
char data[4]; // "data"
uint32_t dataSize; // Data size
};
WAVHeader header{};
file.read(reinterpret_cast<char*>(&header), sizeof(WAVHeader));
// Validate WAV header
if (std::strncmp(header.riff, "RIFF", 4) != 0 ||
std::strncmp(header.wave, "WAVE", 4) != 0 ||
std::strncmp(header.fmt, "fmt ", 4) != 0 ||
std::strncmp(header.data, "data", 4) != 0) {
std::cerr << "Invalid WAV file format: " << filename << std::endl;
file.close();
return false;
}
// Only support PCM format for now
if (header.audioFormat != 1) {
std::cerr << "Unsupported audio format (only PCM supported): " << filename << std::endl;
file.close();
return false;
}
// Read audio data
std::vector<uint8_t> data(header.dataSize);
file.read(reinterpret_cast<char*>(data.data()), header.dataSize);
file.close();
if (file.gcount() != static_cast<std::streamsize>(header.dataSize)) {
std::cerr << "Failed to read complete audio data from: " << filename << std::endl;
return false;
}
// Store the audio data
audioData[name] = std::move(data);
return true;
}
AudioSource* AudioSystem::CreateAudioSource(const std::string& name) {
// Check if the audio data exists
auto it = audioData.find(name);
if (it == audioData.end()) {
std::cerr << "AudioSystem::CreateAudioSource: Audio data not found: " << name << std::endl;
return nullptr;
}
// Create a new audio source
auto source = std::make_unique<ConcreteAudioSource>(name);
// Calculate audio length in samples for timing
const auto& data = it->second;
if (!data.empty()) {
// Assuming 16-bit stereo audio at 44.1kHz (standard WAV format)
// The audio data reading uses dataIndex = (playbackPos + i) * 4
// So we need to calculate length based on how many individual samples we can read
// Each 4 bytes represents one stereo sample pair, so total individual samples = data.size() / 4
uint32_t totalSamples = static_cast<uint32_t>(data.size()) / 4;
// Set the audio length for proper timing
source->SetAudioLength(totalSamples);
}
// Store the source
sources.push_back(std::move(source));
return sources.back().get();
}
AudioSource* AudioSystem::CreateDebugPingSource(const std::string& name) {
// Create a new audio source for debugging
auto source = std::make_unique<ConcreteAudioSource>(name);
// Set up debug ping parameters
// The ping will cycle every 1.5 seconds (0.5s ping + 1.0s silence)
constexpr float sampleRate = 44100.0f;
constexpr float pingDuration = 0.5f;
constexpr float silenceDuration = 1.0f;
constexpr auto totalCycleSamples = static_cast<uint32_t>((pingDuration + silenceDuration) * sampleRate);
// For generated ping, let the generator control the 0.5s ping + 1.0s silence cycle.
// Disable source-level length/delay to avoid double-silence and audible resets.
source->SetAudioLength(0);
// Store the source
sources.push_back(std::move(source));
return sources.back().get();
}
void AudioSystem::SetListenerPosition(const float x, const float y, const float z) {
listenerPosition[0] = x;
listenerPosition[1] = y;
listenerPosition[2] = z;
}
void AudioSystem::SetListenerOrientation(const float forwardX, const float forwardY, const float forwardZ,
const float upX, const float upY, const float upZ) {
listenerOrientation[0] = forwardX;
listenerOrientation[1] = forwardY;
listenerOrientation[2] = forwardZ;
listenerOrientation[3] = upX;
listenerOrientation[4] = upY;
listenerOrientation[5] = upZ;
}
void AudioSystem::SetListenerVelocity(const float x, const float y, const float z) {
listenerVelocity[0] = x;
listenerVelocity[1] = y;
listenerVelocity[2] = z;
}
void AudioSystem::SetMasterVolume(const float volume) {
masterVolume = volume;
}
void AudioSystem::EnableHRTF(const bool enable) {
hrtfEnabled = enable;
}
bool AudioSystem::IsHRTFEnabled() const {
return hrtfEnabled;
}
void AudioSystem::SetHRTFCPUOnly(const bool cpuOnly) {
(void)cpuOnly;
// Enforce GPU-only HRTF processing: ignore CPU-only requests
hrtfCPUOnly = false;
}
bool AudioSystem::IsHRTFCPUOnly() const {
return hrtfCPUOnly;
}
bool AudioSystem::LoadHRTFData(const std::string& filename) {
// HRTF parameters
constexpr uint32_t hrtfSampleCount = 256; // Number of samples per impulse response
constexpr uint32_t positionCount = 36 * 13; // 36 azimuths (10-degree steps) * 13 elevations (15-degree steps)
constexpr uint32_t channelCount = 2; // Stereo (left and right ears)
const float sampleRate = 44100.0f; // Sample rate for HRTF data
const float speedOfSound = 343.0f; // Speed of sound in m/s
const float headRadius = 0.0875f; // Average head radius in meters
// Try to load from a file first (only if the filename is provided)
if (!filename.empty()) {
if (std::ifstream file(filename, std::ios::binary); file.is_open()) {
// Read the file header to determine a format
char header[4];
file.read(header, 4);
if (std::strncmp(header, "HRTF", 4) == 0) {
// Custom HRTF format
uint32_t fileHrtfSize, filePositionCount, fileChannelCount;
file.read(reinterpret_cast<char*>(&fileHrtfSize), sizeof(uint32_t));
file.read(reinterpret_cast<char*>(&filePositionCount), sizeof(uint32_t));
file.read(reinterpret_cast<char*>(&fileChannelCount), sizeof(uint32_t));
if (fileChannelCount == channelCount) {
hrtfData.resize(fileHrtfSize * filePositionCount * fileChannelCount);
file.read(reinterpret_cast<char*>(hrtfData.data()), static_cast<std::streamsize>(hrtfData.size() * sizeof(float)));
hrtfSize = fileHrtfSize;
numHrtfPositions = filePositionCount;
file.close();
return true;
}
}
file.close();
}
}
// Generate realistic HRTF data based on acoustic modeling
// Resize the HRTF data vector
hrtfData.resize(hrtfSampleCount * positionCount * channelCount);
// Generate HRTF impulse responses for each position
for (uint32_t pos = 0; pos < positionCount; pos++) {
// Calculate azimuth and elevation for this position
uint32_t azimuthIndex = pos % 36;
uint32_t elevationIndex = pos / 36;
float azimuth = (static_cast<float>(azimuthIndex) * 10.0f - 180.0f) * static_cast<float>(M_PI) / 180.0f;
float elevation = (static_cast<float>(elevationIndex) * 15.0f - 90.0f) * static_cast<float>(M_PI) / 180.0f;
// Convert to Cartesian coordinates
float x = std::cos(elevation) * std::sin(azimuth);
float y = std::sin(elevation);
float z = std::cos(elevation) * std::cos(azimuth);
for (uint32_t channel = 0; channel < channelCount; channel++) {
// Calculate ear position (left ear: -0.1m, right ear: +0.1m on x-axis)
float earX = (channel == 0) ? -0.1f : 0.1f;
// Calculate distance from source to ear
float dx = x - earX;
float dy = y;
float dz = z;
float distance = std::sqrt(dx * dx + dy * dy + dz * dz);
// Calculate time delay (ITD - Interaural Time Difference)
float timeDelay = distance / speedOfSound;
auto sampleDelay = static_cast<uint32_t>(timeDelay * sampleRate);
// Calculate head shadow effect (ILD - Interaural Level Difference)
float shadowFactor = 1.0f;
if (channel == 0 && azimuth > 0) { // Left ear, source on right
shadowFactor = 0.3f + 0.7f * std::exp(-azimuth * 2.0f);
} else if (channel == 1 && azimuth < 0) { // Right ear, source on left
shadowFactor = 0.3f + 0.7f * std::exp(azimuth * 2.0f);
}
// Generate impulse response
uint32_t samplesGenerated = 0;
for (uint32_t i = 0; i < hrtfSampleCount; i++) {
float value = 0.0f;
// Direct path impulse
if (i >= sampleDelay && i < sampleDelay + 10) {
float t = static_cast<float>(i - sampleDelay) / sampleRate;
value = shadowFactor * std::exp(-t * 1000.0f) * std::cos(2.0f * static_cast<float>(M_PI) * 1000.0f * t);
}
// Apply distance attenuation
value /= std::max(1.0f, distance);
uint32_t index = pos * hrtfSampleCount * channelCount + channel * hrtfSampleCount + i;
hrtfData[index] = value;
}
}
}
// Store HRTF parameters
hrtfSize = hrtfSampleCount;
numHrtfPositions = positionCount;
return true;
}