载入中...
搜索中...
未找到
Audio.cpp
浏览该文件的文档.
1#include "Audio.h"
2#include "PcmStream.h"
3#include "Source.h"
4
5#include "AudioAmbient.h"
6#include "AudioCapabilities.h"
7#include "AudioFade.h"
8#include "AudioZone.h"
9#include "EventSinkOwner.h"
10#include "UnderwaterAudio.h"
11#include "common/Exception.h"
12#include "common/Profile.h"
15#include "sound/Decoder.h"
16#include "sound/Sound.h"
17#include "sound/SoundData.h"
18
19#include <AL/al.h>
20#include <simplesquirrel/simplesquirrel.hpp>
21
22#include <algorithm>
23#include <chrono>
24
25namespace eve {
26namespace audio {
27
29
31 StartupStage stage("audio: OpenAL device/context + worker thread");
32 std::unique_ptr<ALCdevice, decltype(&alcCloseDevice)> deviceOwner(alcOpenDevice(nullptr), &alcCloseDevice);
33 device = deviceOwner.get();
34 if (!device) throw eve::Exception("Could not open OpenAL device");
35 const auto releaseContext = [](ALCcontext* value) {
36 if (alcGetCurrentContext() == value) alcMakeContextCurrent(nullptr);
37 alcDestroyContext(value);
38 };
39 std::unique_ptr<ALCcontext, decltype(releaseContext)> contextOwner(alcCreateContext(device, nullptr),
40 releaseContext);
41 context = contextOwner.get();
42 if (!context || !alcMakeContextCurrent(context)) throw eve::Exception("Could not create OpenAL context");
43 alListenerf(AL_GAIN, masterVolume);
44 capabilities_ = std::make_unique<AudioCapabilities>(*this);
45 worker = std::thread([this] { workerMain(); });
47 (void)contextOwner.release();
48 (void)deviceOwner.release();
49}
50
52 capabilities_.reset();
54 running = false;
55 cv.notify_all();
56 if (worker.joinable()) worker.join();
57
58 for (auto &weak : pcmStreams)
59 if (auto state = weak.lock()) PcmStream::closeState(state);
60 pcmStreams.clear();
61
62 {
63 std::lock_guard<std::mutex> lock(mutex);
64 // Sources are owned by callers; just clear tracking.
65 streamSources.clear();
66 allSources.clear();
67 }
68
69 alcMakeContextCurrent(nullptr);
70 if (context) {
71 alcDestroyContext(context);
72 context = nullptr;
73 }
74 if (device) {
75 alcCloseDevice(device);
76 device = nullptr;
77 }
78}
79
80void Audio::workerMain() {
81 while (running.load()) {
82 std::unique_lock<std::mutex> lock(mutex);
83 cv.wait_for(lock, std::chrono::milliseconds(10), [this] { return !running.load() || !streamSources.empty(); });
84 if (!running.load()) break;
85 // Keep Audio::mutex held while filling. Source::~Source() removes the
86 // source from streamSources under the same mutex, so a source cannot be
87 // destroyed (and its decoderMutex/pendingMutex freed) while the worker
88 // is mid-fill. A snapshot-then-release pattern would let the destructor
89 // finish between the snapshot and the fill; the worker would then lock
90 // mutexes that no longer exist (std::system_error: mutex lock failed).
91 for (Source *s : streamSources) {
92 if (s) s->fillPendingFromDecoder();
93 }
94 }
95}
96
98 std::lock_guard<std::mutex> lock(mutex);
99 streamSources.push_back(s);
100}
101
103 std::lock_guard<std::mutex> lock(mutex);
104 streamSources.erase(std::remove(streamSources.begin(), streamSources.end(), s), streamSources.end());
105 allSources.erase(std::remove(allSources.begin(), allSources.end(), s), allSources.end());
106}
107
109
110void Audio::notifyWorker() { cv.notify_all(); }
111
113 auto* s = new Source(this, data);
114 std::lock_guard<std::mutex> lock(mutex);
115 allSources.push_back(s);
116 return s;
117}
118
120 auto result = PcmStream::create(sampleRate, channels);
121 if (!result.ok()) return Result<std::unique_ptr<PcmStream>>::failure(result.status());
122 pcmStreams.push_back(result.value()->state_);
123 return result;
124}
125
127 if (type != "static" && type != "stream") throw eve::Exception("Invalid source type '%s'", type.c_str());
128 if (type == "static") {
129 auto *sound = sound::Sound::create();
130 auto* sd = sound->newSoundDataFromDecoder(decoder);
131 auto* s = newSource(sd);
132 // SoundData owned by caller eventually; keep sd alive via Source holding pointer only —
133 // Source does not own SoundData. Caller must keep SoundData alive.
134 // For static-from-decoder convenience, leak prevention: Source should own or we document.
135 // Spec: squirrel manages SoundData. Here C++ path: attach as dependency by not deleting.
136 // Store sd on Source via staticData without ownership — caller must delete sd after Source.
137 // Better: Source holds SoundData* without delete; document. For this factory, transfer:
138 // We'll let Source keep staticData pointer; user deletes Source then SoundData.
139 return s;
140 }
141 auto* s = new Source(this, decoder, true);
142 std::lock_guard<std::mutex> lock(mutex);
143 allSources.push_back(s);
144 return s;
145}
146
148 if (type != "static" && type != "stream") throw eve::Exception("Invalid source type '%s'", type.c_str());
149 auto *sound = sound::Sound::create();
150 if (type == "static") {
151 auto *sd = sound->newSoundData(data);
152 return newSource(sd);
153 }
154 auto* dec = sound->newDecoder(data);
155 auto* s = new Source(this, dec, true, true);
156 std::lock_guard<std::mutex> lock(mutex);
157 allSources.push_back(s);
158 return s;
159}
160
162 if (s) s->play();
163}
165 if (s) s->stop();
166}
168 if (s) s->pause();
169}
171 for (auto &weak : pcmStreams) {
172 if (auto state = weak.lock()) PcmStream::closeState(state);
173 }
174 // Hold the mutex while stopping: Source::~Source() → unregisterSource()
175 // blocks on the same mutex, so a concurrently destroyed source cannot be
176 // touched here after it has been removed from allSources.
177 std::lock_guard<std::mutex> lock(mutex);
178 for (Source *s : allSources) {
179 if (s) s->stop();
180 }
181}
182
184 std::lock_guard<std::mutex> lock(mutex);
185 return static_cast<int>(allSources.size());
186}
187
188void Audio::setVolume(float v) {
189 masterVolume = std::max(0.f, v);
190 alListenerf(AL_GAIN, masterVolume);
191}
192float Audio::getVolume() const { return masterVolume; }
193
194void Audio::setPosition(float x, float y, float z) { alListener3f(AL_POSITION, x, y, z); }
195void Audio::setVelocity(float x, float y, float z) { alListener3f(AL_VELOCITY, x, y, z); }
196void Audio::setOrientation(float fx, float fy, float fz, float ux, float uy, float uz) {
197 float ori[6] = {fx, fy, fz, ux, uy, uz};
198 alListenerfv(AL_ORIENTATION, ori);
199}
200
202 EV_PROFILE_MODULE("audio", "Audio::pump");
203 std::erase_if(pcmStreams, [](auto &weak) {
204 auto state = weak.lock();
205 if (!state) return true;
206 PcmStream::pumpState(state);
207 return false;
208 });
209 // Same guarantee as workerMain: destruction removes the source under this
210 // mutex, so the pointer stays valid for the whole iteration.
211 std::lock_guard<std::mutex> lock(mutex);
212 for (Source *s : streamSources) {
213 if (s) s->pump();
214 }
215}
216
217void Audio::expose(ssq::Table &table) {
218 auto cls = table.addClass(name, Audio::create, false);
219 expose(cls);
220 exposePcmStream(table, cls);
221
222 auto src = table.addClass<Source>("Source", std::function<Source*()>([]() -> Source* { return nullptr; }), true);
223 src.addFunc("play", &Source::play);
224 src.addFunc("pause", &Source::pause);
225 src.addFunc("stop", &Source::stop);
226 src.addFunc("isPlaying", &Source::isPlaying);
227 src.addFunc("setVolume", &Source::setVolume);
228 src.addFunc("getVolume", &Source::getVolume);
229 src.addFunc("setPitch", &Source::setPitch);
230 src.addFunc("getPitch", &Source::getPitch);
231 src.addFunc("setLooping", &Source::setLooping);
232 src.addFunc("isLooping", &Source::isLooping);
233 src.addFunc("seek", &Source::seek);
234 src.addFunc("tell", &Source::tell);
235 src.addFunc("getDuration", &Source::getDuration);
236 src.addFunc("setPosition", &Source::setPosition);
237 src.addFunc("setVelocity", &Source::setVelocity);
238 src.addFunc("setDirection", &Source::setDirection);
239 src.addFunc("setRelative", &Source::setRelative);
240 src.addFunc("isRelative", [](Source* self) { return self->isRelative(); });
241 src.addFunc("setAttenuationDistances", &Source::setAttenuationDistances);
242 src.addFunc("fadeTo", [vm = table.getHandle()](Source* self, float target, float duration, float now) {
243 return eve::script::projectResult(vm, self->fadeTo(target, duration, now));
244 });
245 src.addFunc("fadeOutAndStop", [vm = table.getHandle()](Source* self, float duration, float now) {
246 return eve::script::projectResult(vm, self->fadeOutAndStop(duration, now));
247 });
248 src.addFunc("cancelFade",
249 [vm = table.getHandle()](Source* self) { return eve::script::projectResult(vm, self->cancelFade()); });
250 src.addFunc("advanceFade", [vm = table.getHandle()](Source* self, float now) {
251 return eve::script::projectResult(vm, self->advanceFade(now));
252 });
253 src.addFunc("getFadeWeight", [](Source* self) { return self->getFadeWeight(); });
254 src.addFunc("isFading", [](Source* self) { return self->isFading(); });
255 src.addFunc("setSpatialBlend", [vm = table.getHandle()](Source* self, float blend) {
256 return eve::script::projectResult(vm, self->setSpatialBlend(blend));
257 });
258 src.addFunc("getSpatialBlend", [](Source* self) { return self->getSpatialBlend(); });
259 src.addFunc("setBalance", [vm = table.getHandle()](Source* self, float balance) {
260 return eve::script::projectResult(vm, self->setBalance(balance));
261 });
262 src.addFunc("getBalance", [](Source* self) { return self->getBalance(); });
263 src.addFunc("setRolloffFactor", [vm = table.getHandle()](Source* self, float factor) {
264 return eve::script::projectResult(vm, self->setRolloffFactor(factor));
265 });
266 src.addFunc("getRolloffFactor", [](Source* self) { return self->getRolloffFactor(); });
267 src.addFunc("getChannelCount", [](Source* self) { return self->getChannelCount(); });
268 table.addFunc("crossfadeSources",
269 [vm = table.getHandle()](Source* from, Source* to, float toVolume, float duration, float now) {
270 return eve::script::projectResult(vm, crossfadeSources(from, to, toVolume, duration, now));
271 });
272 table.addFunc("configureAmbientBed", [vm = table.getHandle()](Source* source) {
273 return eve::script::projectResult(vm, configureAmbientBed(source));
274 });
275 table.addFunc("applyUnderwaterAudio", [vm = table.getHandle()](Source* down, Source* up, Source* ambience,
276 bool playDown, bool playUp, bool loopAmbience,
277 float volume, float fadeSeconds, float now) {
278 return eve::script::projectResult(
279 vm, applyUnderwaterAudio(down, up, ambience, playDown, playUp, loopAmbience, volume, fadeSeconds, now));
280 });
281 auto zoneItem = table.addClass("AudioZoneItem", ssq::Class::Ctor<AudioZoneItem()>());
282 zoneItem.addVar("volume", &AudioZoneItem::volume);
283 zoneItem.addVar("fadeInTime", &AudioZoneItem::fadeInTime);
284 zoneItem.addVar("fadeOutTime", &AudioZoneItem::fadeOutTime);
285 zoneItem.addVar("duration", &AudioZoneItem::duration);
286 auto zoneProfile = table.addClass("AudioZoneProfile", ssq::Class::Ctor<AudioZoneProfile()>());
287 zoneProfile.addVar("x", &AudioZoneProfile::x);
288 zoneProfile.addVar("y", &AudioZoneProfile::y);
289 zoneProfile.addVar("z", &AudioZoneProfile::z);
290 zoneProfile.addVar("radius", &AudioZoneProfile::radius);
291 zoneProfile.addVar("minimumBreakTime", &AudioZoneProfile::minimumBreakTime);
292 zoneProfile.addVar("maximumBreakTime", &AudioZoneProfile::maximumBreakTime);
293 zoneProfile.addVar("deactivationTime", &AudioZoneProfile::deactivationTime);
294 zoneProfile.addVar("global", &AudioZoneProfile::global);
295 zoneProfile.addFunc("addItem", [vm = table.getHandle()](AudioZoneProfile* p, const AudioZoneItem* item) {
296 auto r =
297 p && item
298 ? p->addItem(*item)
299 : Result<int>::failure(Diagnostic::error(DiagnosticCode::InvalidArgument, "profile and item required"));
300 return eve::script::projectResult(vm, std::move(r), [](int v) { return Value(v); });
301 });
302 zoneProfile.addFunc("getItemCount", [](const AudioZoneProfile* p) { return p ? p->itemCount() : 0; });
303 auto zoneState = table.addClass("AudioZoneState", ssq::Class::Ctor<AudioZoneState()>());
304 zoneState.addVar("selectedTrack", &AudioZoneState::selectedTrack);
305 zoneState.addVar("playing", &AudioZoneState::playing);
306 table.addFunc(
307 "evaluateAudioZone", [vm = table.getHandle()](const AudioZoneProfile* p, AudioZoneState* state, float now,
308 float x, float y, float z, float master, std::uint32_t seed) {
309 auto r = p && state ? evaluateAudioZone(*p, *state, now, x, y, z, master, seed)
310 : Result<AudioZoneOutput>::failure(
311 Diagnostic::error(DiagnosticCode::InvalidArgument, "profile and state required"));
312 return eve::script::projectResult(vm, std::move(r), [](const AudioZoneOutput& v) {
313 return Value::Object{
314 {"play", v.play}, {"stop", v.stop}, {"trackIndex", v.trackIndex}, {"volume", v.volume}};
315 });
316 });
317 table.addFunc("applyAudioZoneOutput", [vm = table.getHandle()](Source* source, bool play, bool stop, float volume) {
318 AudioZoneOutput output;
319 output.play = play;
320 output.stop = stop;
321 output.volume = volume;
323 });
324}
325
326void Audio::expose(ssq::Class &cls) {
327 cls.addFunc("getName", &Audio::getName);
328 cls.addFunc("newSource", &Audio::newSource);
329 cls.addFunc("newSourceFromDecoder", &Audio::newSourceFromDecoder);
330 cls.addFunc("newSourceFromData", &Audio::newSourceFromData);
331 cls.addFunc("play", &Audio::play);
332 cls.addFunc("stop", &Audio::stop);
333 cls.addFunc("stopAll", &Audio::stopAll);
334 cls.addFunc("pause", &Audio::pause);
335 cls.addFunc("setVolume", &Audio::setVolume);
336 cls.addFunc("getVolume", &Audio::getVolume);
337 cls.addFunc("setPosition", &Audio::setPosition);
338 cls.addFunc("setVelocity", &Audio::setVelocity);
339 cls.addFunc("setOrientation", &Audio::setOrientation);
340}
341
342} // namespace audio
343} // namespace eve
double z
double y
double x
LogicalId target
float duration
std::map< std::string, std::vector< Key >, std::less<> > channels
std::string output
Audio * audio
double volume
const std::string & s
glm::vec4 p[6]
HSQUIRRELVM vm
Definition ECS.cpp:38
HSQOBJECT cls
Definition ECS.cpp:39
std::string name
Definition ECS.cpp:154
vkb::Device & device
double r
float v
HexVec3 up
float blend
std::string to
std::string from
Poco::JSON::Object::Ptr result
#define Module_IMPL(ModuleName, newExpr)
Definition Module.h:27
std::string error
Definition Package.cpp:174
#define EV_PROFILE_MODULE(module, name)
Profile the enclosing scope, tagged with a module for grouping.
Definition Profile.h:158
Object::Ptr value
std::string_view source
The single Squirrel projection for common Result, Status and Value.
uint32_t seed
Definition TreeMesh.cpp:276
const VegetationPresetContext & context
Data public API.
Definition Data.h:8
EVENGINE_API_FOUNDATION public API.
Definition Exception.h:13
Move-only operation result carrying either a value or Status.
Definition Result.h:176
StartupStage public API.
std::map< std::string, Value > Object
Definition Value.h:34
OpenAL audio module: device management, master listener state, and Source factory....
Definition Audio.h:34
void pause(Source *s)
Pauses a source (no-op when s is null).
Definition Audio.cpp:167
Source * newSourceFromDecoder(sound::Decoder *decoder, std::string type)
Creates a Source from a decoder; type must be "static" or "stream".
Definition Audio.cpp:126
float getVolume() const
Returns the volume.
Definition Audio.cpp:192
void unregisterSource(Source *s)
Internal: removes a source from all module tracking.
Definition Audio.cpp:102
void setVolume(float v)
Sets master volume (clamped to >= 0) applied to the OpenAL listener.
Definition Audio.cpp:188
void stop(Source *s)
Stops playback of a source (no-op when s is null).
Definition Audio.cpp:164
void setVelocity(float x, float y, float z)
Sets the listener velocity (used by OpenAL doppler).
Definition Audio.cpp:195
void stopAll()
Stops every live Source and permanently closes caller-fed PCM streams.
Definition Audio.cpp:170
void setPosition(float x, float y, float z)
Sets the listener position in world units.
Definition Audio.cpp:194
Source * newSourceFromData(Data *data, std::string type)
Creates a Source from raw encoded data; type must be "static" or "stream".
Definition Audio.cpp:147
Source * newSource(sound::SoundData *data)
Creates a static (non-streaming) Source from decoded sound data.
Definition Audio.cpp:112
void play(Source *s)
Starts playback of a source (no-op when s is null).
Definition Audio.cpp:161
~Audio() override
Audio.
Definition Audio.cpp:51
Result< std::unique_ptr< PcmStream > > newPcmStream(int sampleRate, int channels)
Allocate a bounded PCM stream without a Sound/decoder dependency.
Definition Audio.cpp:119
void registerStream(Source *s)
Internal: registers a streaming source with the decode worker.
Definition Audio.cpp:97
void unregisterStream(Source *s)
Internal: removes a source from worker tracking.
Definition Audio.cpp:108
int getSourceCount()
Return the current number of caller- or handler-owned live sources.
Definition Audio.cpp:183
Audio()
Audio.
Definition Audio.cpp:30
void setOrientation(float fx, float fy, float fz, float ux, float uy, float uz)
Sets the listener forward and up orientation vectors.
Definition Audio.cpp:196
void pump()
Advances streaming sources; call once per frame from the main thread.
Definition Audio.cpp:201
void notifyWorker()
Internal: wakes the decode worker thread.
Definition Audio.cpp:110
A playable audio source (static buffer or streaming decoder). Not thread-safe for playback control ex...
Definition Source.h:30
void play()
Starts (or resumes) playback.
Definition Source.cpp:161
void pause()
Pauses playback, keeping the play position.
Definition Source.cpp:175
void setVolume(float v)
Sets source gain (clamped to >= 0). Does not cancel an active fade target.
Definition Source.cpp:218
float getVolume() const
Returns the audible user volume after the last advanceFade (or committed volume).
Definition Source.cpp:225
void setVelocity(float x, float y, float z)
Sets the source velocity (used by OpenAL doppler).
Definition Source.cpp:282
bool isPlaying() const
True when playing.
Definition Source.cpp:212
float getPitch() const
Returns the pitch.
Definition Source.cpp:231
void setRelative(bool relative)
Makes the source ignore the listener position (head-relative).
Definition Source.cpp:284
void setPosition(float x, float y, float z)
Sets the source position in world units.
Definition Source.cpp:272
void stop()
Stops playback and rewinds the play position.
Definition Source.cpp:180
double getDuration() const
Total duration in seconds (0 for live/unbounded streams).
Definition Source.cpp:265
double tell() const
Current play time in seconds.
Definition Source.cpp:259
void setAttenuationDistances(float ref, float max)
Sets OpenAL reference and maximum attenuation distances.
Definition Source.cpp:288
bool seek(double seconds)
Seeks to a time in seconds; false when seeking is unsupported.
Definition Source.cpp:239
void setLooping(bool l)
Enables/disables looping.
Definition Source.cpp:233
void setDirection(float x, float y, float z)
Sets the source directional cone orientation.
Definition Source.cpp:283
bool isLooping() const
True when looping.
Definition Source.cpp:237
void setPitch(float p)
Sets playback pitch (clamped to >= 0).
Definition Source.cpp:227
Streaming audio decoder (medialoader-backed). Native builds own encoded bytes and decode incrementall...
Definition Decoder.h:23
Raw PCM audio buffer with format metadata (samples/rate/bit depth/channels).
Definition SoundData.h:15
void bindAudioEventSinkOwner(Audio *owner) noexcept
Bind the live Audio module into the platform event pump sink. @ownership Borrowed; cleared when the A...
Definition EventSink.cpp:36
Result< AudioZoneOutput > evaluateAudioZone(const AudioZoneProfile &p, AudioZoneState &state, float now, float px, float py, float pz, float master, std::uint32_t seed)
Evaluate PcgAudioManager/PcgAudioZone for one explicit time and player observation.
Definition AudioZone.cpp:42
void exposePcmStream(ssq::Table &table, ssq::Class &audioClass)
Install VM-bound adapters; borrows both handles only during registration.
Result< void > applyAudioZoneOutput(Source *source, const AudioZoneOutput &output)
Apply one evaluated command to the caller-selected track Source without retaining it.
eve::Diagnostic Diagnostic
eve::Result< T > Result
std::unordered_map< std::string, SkillDefinition > & table()
Definition Skill.cpp:73
ssq::Table projectResult(HSQUIRRELVM vm, Result< void > &&result)
Consume and project a void native Result using the common schema.
Build metadata (engine git commit, build time, third-party version).
Definition Build.cpp:16
DiagnosticCode
Stable machine-readable diagnostic codes.
Definition Diagnostic.h:47