-
Notifications
You must be signed in to change notification settings - Fork 3
/
SoundManager.cpp
221 lines (197 loc) · 6.34 KB
/
SoundManager.cpp
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
#include "SoundManager.h"
#include "imgui.h"
#include <iostream>
#include "MockingboardManager.h"
#define CHIPS_IMPL
#include "beeper.h"
// below because "The declaration of a static data member in its class definition is not a definition"
SoundManager* SoundManager::s_instance;
beeper_t beeper;
SoundManager::SoundManager(uint32_t sampleRate, uint32_t bufferSize)
: sampleRate(sampleRate), bufferSize(bufferSize), bIsPlaying(false) {
if (SDL_Init(SDL_INIT_AUDIO) < 0) {
std::cerr << "Failed to initialize SDL: " << SDL_GetError() << std::endl;
throw std::runtime_error("SDL_Init failed");
}
audioDevice = 0;
Initialize();
}
void SoundManager::Initialize()
{
if (audioDevice == 0)
{
SDL_zero(audioSpec);
audioSpec.freq = sampleRate;
audioSpec.format = AUDIO_F32SYS;
audioSpec.channels = 2;
audioSpec.samples = bufferSize;
audioSpec.callback = SoundManager::AudioCallback;
audioSpec.userdata = this;
audioDevice = SDL_OpenAudioDevice(NULL, 0, &audioSpec, NULL, 0);
}
else {
// std::cerr << "Stopping and clearing Speaker Audio" << std::endl;
SDL_PauseAudioDevice(audioDevice, 1);
SDL_ClearQueuedAudio(audioDevice);
}
if (audioDevice == 0) {
std::cerr << "Failed to open audio device: " << SDL_GetError() << std::endl;
SDL_Quit();
throw std::runtime_error("SDL_OpenAudioDevice failed");
}
bIsPlaying = false;
SetPAL(bIsPAL);
SDL_PauseAudioDevice(audioDevice, 0);
}
SoundManager::~SoundManager() {
SDL_PauseAudioDevice(audioDevice, 1);
SDL_CloseAudioDevice(audioDevice);
SDL_Quit();
}
void SoundManager::SetPAL(bool isPal) {
bIsPAL = isPal;
if (!bIsEnabled)
return;
bool _isPlaying = bIsPlaying;
if (_isPlaying)
SDL_PauseAudioDevice(audioDevice, 1);
beeper_desc_t bdesc = { bIsPAL ? (float)_A2_CPU_FREQUENCY_PAL : (float)_A2_CPU_FREQUENCY_NTSC, _AUDIO_SAMPLE_RATE,
SM_BASE_VOLUME_ADJUSTMENT };
beeper_init(&beeper, &bdesc);
if (_isPlaying)
BeginPlay();
}
void SoundManager::BeginPlay() {
if (!bIsEnabled)
return;
beeper_reset(&beeper);
curr_tick = 0;
curr_freq = 0.f;
beeper_samples_idx_read = SM_BEEPER_BUFFER_SIZE - SM_AUDIO_BUFLEN;
beeper_samples_idx_write = 0;
dcadj_pos = 0;
dcadj_sum = 0;
memset(beeper_samples, 0, sizeof(beeper_samples));
memset(dcadj_buf, 0, sizeof(dcadj_buf));
bIsPlaying = true;
MockingboardManager::GetInstance()->BeginPlay();
}
void SoundManager::StopPlay() {
// flush the last sounds
bool _enabledState = bIsEnabled;
bIsEnabled = false; // disable event handling until everything is flushed
MockingboardManager::GetInstance()->StopPlay();
SDL_Delay(100);
bIsPlaying = false;
bIsEnabled = _enabledState;
}
bool SoundManager::IsPlaying() {
return bIsPlaying;
}
float SoundManager::DCAdjustment(float freq)
{
dcadj_sum -= dcadj_buf[dcadj_pos];
dcadj_sum += freq;
dcadj_buf[dcadj_pos] = freq;
dcadj_pos = (dcadj_pos + 1) & (SM_BEEPER_DCADJ_BUFLEN - 1);
return (dcadj_sum / SM_BEEPER_DCADJ_BUFLEN);
}
void SoundManager::EventReceived(bool isC03x) {
if (!bIsEnabled)
return;
if (!bIsPlaying)
BeginPlay();
if (isC03x)
beeper_toggle(&beeper);
if (beeper_tick(&beeper))
{
if (((beeper_samples_idx_write + 1) % SM_BEEPER_BUFFER_SIZE) == beeper_samples_idx_read)
{
// drop the sample, reading is lagging
}
else {
beeper_samples_idx_write = (beeper_samples_idx_write + 1) % SM_BEEPER_BUFFER_SIZE;
beeper_samples[beeper_samples_idx_write] = beeper.sample;
}
}
}
void SoundManager::AudioCallback(void* userdata, uint8_t* stream, int len)
{
SoundManager* self = static_cast<SoundManager*>(userdata);
int samples = len / (sizeof(float) * 2); // Number of samples to fill
// Need to mix the speaker and the mockingboard Audio
auto mmMgr = MockingboardManager::GetInstance();
float mm_left = 0.f, mm_right = 0.f; // The left and right values from the Mockingboard mix
float beeper_sample = 0.f; // that's the beeper mono sample
for (int i = 0; i < samples; ++i) {
if (self->IsPlaying())
{
if (((self->beeper_samples_idx_read + 1) % SM_BEEPER_BUFFER_SIZE) == self->beeper_samples_idx_write)
{
// write is lagging, use the current sample
beeper_sample = self->beeper_samples[self->beeper_samples_idx_read];
}
else {
self->beeper_samples_idx_read = (self->beeper_samples_idx_read + 1) % SM_BEEPER_BUFFER_SIZE;
beeper_sample = self->beeper_samples[self->beeper_samples_idx_read];
}
}
if (mmMgr->IsPlaying())
mmMgr->GetSamples(mm_left, mm_right);
// Mix in the mono beeper and stereo Mockingboard streams
self->audioCallbackBuffer[2 * i] = 0.5 * self->beeper_volume * beeper_sample + 0.5 * mm_left;
self->audioCallbackBuffer[2 * i + 1] = 0.5 * self->beeper_volume * beeper_sample + 0.5 * mm_right;
}
// Copy the buffer to the stream
SDL_memcpy(stream, self->audioCallbackBuffer, len);
SDL_memset(self->audioCallbackBuffer, 0, len);
}
///
///
/// ImGUI Interface
///
///
void SoundManager::DisplayImGuiChunk()
{
if (ImGui::Checkbox("Enable HDMI Sound", &bIsEnabled))
{
if (bIsEnabled)
BeginPlay();
else
StopPlay();
}
ImGui::SameLine();
ImGui::TextDisabled("(!)");
if (ImGui::BeginItemTooltip())
{
ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f);
ImGui::TextUnformatted(
"WARNING:\n"
"Do not enable HDMI sound when the Apple 2 is emitting sounds.\n"
"There is a chance that the sound will be reversed, i.e:\n"
"Sound will be on when it should be off, and vice versa.\n"
"So make sure you check this box only when you're certain the Apple 2 is silent.\n");
ImGui::PopTextWrapPos();
ImGui::EndTooltip();
}
ImGui::SliderFloat("Volume", &beeper_volume, 0.f, 1.f);
ImGui::Separator();
static int sm_imgui_samples_delay = (SM_BEEPER_BUFFER_SIZE + beeper_samples_idx_write - beeper_samples_idx_read) % SM_BEEPER_BUFFER_SIZE;
if ((SDL_GetTicks64() & 0xC0) == 0)
sm_imgui_samples_delay = (SM_BEEPER_BUFFER_SIZE + beeper_samples_idx_write - beeper_samples_idx_read) % SM_BEEPER_BUFFER_SIZE;
ImGui::Text("Write-Read Samples Delay: %d", sm_imgui_samples_delay);
ImGui::Text("Current Audio Driver: %s\n", SDL_GetCurrentAudioDriver());
}
nlohmann::json SoundManager::SerializeState()
{
nlohmann::json jsonState = {
{"sound_enabled", bIsEnabled},
{"sound_volume", beeper_volume}
};
return jsonState;
}
void SoundManager::DeserializeState(const nlohmann::json &jsonState)
{
bIsEnabled = jsonState.value("sound_enabled", bIsEnabled);
beeper_volume = jsonState.value("sound_volume", beeper_volume);
}