12#ifndef AL_STEREO_ANGLES
13#define AL_STEREO_ANGLES 0x1030
15#ifndef AL_SOURCE_SPATIALIZE_SOFT
16#define AL_SOURCE_SPATIALIZE_SOFT 0x1214
23constexpr size_t kMaxPendingChunks = 8;
25bool hasAlExtension(
const char*
name) {
return name && alIsExtensionPresent(
name) == AL_TRUE; }
27Diagnostic invalidAudioArg(
const char*
message,
const char*
path =
"audio.source") {
34 alGenSources(1, &alSource);
37 alSourcei(alSource, AL_LOOPING, looping ? AL_TRUE : AL_FALSE);
41 :
audio(
audio), decoder(decoder), ownsDecoder(takeDecoderOwnership), streaming(streaming) {
43 alGenSources(1, &alSource);
46 alGenBuffers(streamBufferCount, streamBuffers);
48 audio->registerStream(
this);
49 audio->notifyWorker();
52 throw eve::Exception(
"Non-stream Decoder Source should be created via SoundData");
66 alSourcei(alSource, AL_BUFFER, 0);
67 alDeleteSources(1, &alSource);
71 alDeleteBuffers(1, &alBuffer);
74 if (streamBufferCount > 0) {
75 alDeleteBuffers(streamBufferCount, streamBuffers);
76 streamBufferCount = 0;
84 std::lock_guard<std::mutex> lock(decoderMutex);
92ALenum Source::alFormat()
const {
98 std::lock_guard<std::mutex> lock(decoderMutex);
104 if (ch == 1 && bits == 8)
return AL_FORMAT_MONO8;
105 if (ch == 1 && bits == 16)
return AL_FORMAT_MONO16;
106 if (ch == 2 && bits == 8)
return AL_FORMAT_STEREO8;
107 if (ch == 2 && bits == 16)
return AL_FORMAT_STEREO16;
111int Source::decoderSampleRateOr(
int fallback)
const {
112 std::lock_guard<std::mutex> lock(decoderMutex);
118 std::lock_guard<std::mutex> lock(decoderMutex);
122void Source::ensureStaticBuffer() {
123 if (alBuffer || !staticData)
return;
124 alGenBuffers(1, &alBuffer);
125 alBufferData(alBuffer, alFormat(), staticData->
getData(),
static_cast<ALsizei
>(staticData->
getSize()),
127 alSourcei(alSource, AL_BUFFER,
static_cast<ALint
>(alBuffer));
130float Source::currentAudibleVolume() const noexcept {
return fading_ ? audibleVolume_ : volume; }
132void Source::applyGainPitch() {
133 float master = audio ? audio->
getVolume() : 1.f;
134 const float audible = fading_ ? audibleVolume_ : volume;
135 alSourcef(alSource, AL_GAIN, audible * master * (fading_ ? 1.f : fadeWeight_));
136 alSourcef(alSource, AL_PITCH, pitch);
139void Source::applyRolloff() {
140 if (alSource) alSourcef(alSource, AL_ROLLOFF_FACTOR, rolloffFactor_);
143void Source::applyBalanceToAl() {
144 if (!alSource)
return;
145 if (balanceUsesStereoAngles_) {
147 const float halfPi = 1.57079632679f;
148 const float left = -halfPi + balance_ * halfPi;
149 const float right = halfPi + balance_ * halfPi;
154 if (balanceUsesMonoPosition_) {
155 alSource3f(alSource, AL_POSITION, balance_, positionY_, positionZ_);
158 alSource3f(alSource, AL_POSITION, positionX_, positionY_, positionZ_);
166 alSourcePlay(alSource);
169 ensureStaticBuffer();
171 alSourcePlay(alSource);
176 alSourcePause(alSource);
181 if (!alSource)
return;
182 alSourceStop(alSource);
187 alGetSourcei(alSource, AL_BUFFERS_PROCESSED, &processed);
188 while (processed-- > 0) {
190 alSourceUnqueueBuffers(alSource, 1, &
b);
193 alGetSourcei(alSource, AL_BUFFERS_QUEUED, &
queued);
196 alSourceUnqueueBuffers(alSource, 1, &
b);
199 std::lock_guard<std::mutex> lock(pendingMutex);
200 while (!pending.empty()) pending.pop();
203 std::lock_guard<std::mutex> lock(decoderMutex);
204 if (decoder) decoder->
rewind();
208 alSourceRewind(alSource);
214 alGetSourcei(alSource, AL_SOURCE_STATE, &
state);
215 return state == AL_PLAYING;
219 volume = std::max(0.f,
v);
221 audibleVolume_ = volume;
228 pitch = std::max(0.001f,
p);
235 if (!streaming) alSourcei(alSource, AL_LOOPING, looping ? AL_TRUE : AL_FALSE);
242 std::lock_guard<std::mutex> lock(decoderMutex);
243 if (!decoder || !decoder->
isSeekable())
return false;
248 std::lock_guard<std::mutex> lock(decoderMutex);
249 if (!decoder || !decoder->
seek(seconds))
return false;
255 alSourcef(alSource, AL_SEC_OFFSET,
static_cast<ALfloat
>(seconds));
261 alGetSourcef(alSource, AL_SEC_OFFSET, &sec);
262 return static_cast<double>(sec);
267 std::lock_guard<std::mutex> lock(decoderMutex);
276 if (balanceUsesMonoPosition_) {
277 alSource3f(alSource, AL_POSITION, balance_, positionY_, positionZ_);
280 alSource3f(alSource, AL_POSITION,
x,
y,
z);
286 alSourcei(alSource, AL_SOURCE_RELATIVE,
relative ? AL_TRUE : AL_FALSE);
289 alSourcef(alSource, AL_REFERENCE_DISTANCE, ref);
290 alSourcef(alSource, AL_MAX_DISTANCE,
max);
295 if (!std::isfinite(factor) || factor < 0.f)
297 rolloffFactor_ = factor;
303 if (!std::isfinite(
blend) || blend < 0.f || blend > 1.f)
304 return Result<void>::failure(invalidAudioArg(
"spatial blend must be finite and in [0,1]",
"spatialBlend"));
306 const bool softSpatialize = hasAlExtension(
"AL_SOFT_source_spatialize");
309 invalidAudioArg(
"stereo spatialBlend>0 requires AL_SOFT_source_spatialize; use mono or configureAmbientBed",
313 spatialBlend_ =
blend;
316 rolloffFactor_ = 0.f;
319 rolloffFactor_ =
blend;
326 if (!std::isfinite(balance) || balance < -1.f || balance > 1.f)
329 const bool stereoAngles = hasAlExtension(
"AL_EXT_STEREO_ANGLES");
330 balanceUsesStereoAngles_ =
false;
331 balanceUsesMonoPosition_ =
false;
332 if (stereoAngles &&
channels == 2) {
334 balanceUsesStereoAngles_ =
true;
340 balanceUsesMonoPosition_ =
true;
345 return Result<void>::failure(invalidAudioArg(
"stereo balance requires AL_EXT_STEREO_ANGLES",
"balance"));
348 invalidAudioArg(
"mono balance without stereo angles requires a relative source",
"balance"));
349 return Result<void>::failure(invalidAudioArg(
"balance is unsupported for this source format",
"balance"));
352Result<void> Source::beginFade(
float targetVolume,
float durationSeconds,
float now,
bool stopWhenSilent) {
353 if (!std::isfinite(targetVolume) || targetVolume < 0.f || !std::isfinite(durationSeconds) ||
354 durationSeconds < 0.f || !std::isfinite(now))
356 invalidAudioArg(
"fade requires finite now, non-negative duration and volume",
"fade"));
357 if (durationSeconds == 0.f) {
359 stopWhenSilent_ =
false;
361 volume = targetVolume;
362 audibleVolume_ = targetVolume;
364 if (stopWhenSilent && targetVolume == 0.f)
stop();
367 fadeFrom_ = currentAudibleVolume();
368 fadeToVolume_ = targetVolume;
370 fadeEnd_ = now + durationSeconds;
373 stopWhenSilent_ = stopWhenSilent;
374 audibleVolume_ = fadeFrom_;
380 return beginFade(targetVolume, durationSeconds, now,
false);
384 return beginFade(0.f, durationSeconds, now,
true);
389 volume = audibleVolume_;
391 stopWhenSilent_ =
false;
398 if (!std::isfinite(now))
return Result<void>::failure(invalidAudioArg(
"advanceFade requires finite now",
"fade"));
400 if (now <= fadeStart_) {
402 audibleVolume_ = fadeFrom_;
406 if (now >= fadeEnd_ || fadeEnd_ <= fadeStart_) {
407 volume = fadeToVolume_;
408 audibleVolume_ = fadeToVolume_;
411 const bool shouldStop = stopWhenSilent_ && fadeToVolume_ == 0.f;
412 stopWhenSilent_ =
false;
414 if (shouldStop)
stop();
417 const float progress = (now - fadeStart_) / (fadeEnd_ - fadeStart_);
418 fadeWeight_ = progress;
419 audibleVolume_ = fadeFrom_ + (fadeToVolume_ - fadeFrom_) * progress;
425 if (!streaming || !wantsData.load())
return;
427 std::lock_guard<std::mutex> lock(pendingMutex);
428 if (pending.size() >= kMaxPendingChunks)
return;
436 std::lock_guard<std::mutex> decoderLock(decoderMutex);
437 if (!decoder)
return;
440 if (looping && decoder->
rewind()) {
448 auto *buf =
static_cast<const uint8_t *
>(decoder->
getBuffer());
449 chunk.
bytes.assign(buf, buf +
n);
452 std::lock_guard<std::mutex> lock(pendingMutex);
453 pending.push(std::move(chunk));
457 if (!streaming || !alSource)
return;
460 alGetSourcei(alSource, AL_BUFFERS_PROCESSED, &processed);
461 while (processed-- > 0) {
463 alSourceUnqueueBuffers(alSource, 1, &
b);
466 std::lock_guard<std::mutex> lock(pendingMutex);
467 if (pending.empty()) {
474 std::vector<uint8_t> silence(256, 0);
475 alBufferData(
b, alFormat(), silence.data(),
static_cast<ALsizei
>(silence.size()),
476 decoderSampleRateOr(44100));
477 alSourceQueueBuffers(alSource, 1, &
b);
480 chunk = std::move(pending.front());
483 alBufferData(
b, alFormat(), chunk.
bytes.data(),
static_cast<ALsizei
>(chunk.
bytes.size()),
484 decoderSampleRateOr(44100));
485 alSourceQueueBuffers(alSource, 1, &
b);
490 alGetSourcei(alSource, AL_BUFFERS_QUEUED, &
queued);
491 for (
int i =
queued; i < streamBufferCount; ++i) {
494 std::lock_guard<std::mutex> lock(pendingMutex);
495 if (pending.empty())
break;
496 chunk = std::move(pending.front());
501 ALuint buf = streamBuffers[
queued];
502 alBufferData(buf, alFormat(), chunk.
bytes.data(),
static_cast<ALsizei
>(chunk.
bytes.size()),
503 decoderSampleRateOr(44100));
504 alSourceQueueBuffers(alSource, 1, &buf);
505 alGetSourcei(alSource, AL_BUFFERS_QUEUED, &
queued);
510 alGetSourcei(alSource, AL_BUFFERS_QUEUED, &
q);
511 if (
q > 0) alSourcePlay(alSource);
std::map< std::string, std::vector< Key >, std::less<> > channels
std::vector< double > angles
std::array< double, 10 > q
#define AL_SOURCE_SPATIALIZE_SOFT
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
EVENGINE_API_FOUNDATION public API.
Move-only operation result carrying either a value or Status.
static Result success(T value)
Construct a successful result owning value.
static Result failure(Status status)
Construct a failed result from a structured status.
OpenAL audio module: device management, master listener state, and Source factory....
float getVolume() const
Returns the volume.
void unregisterSource(Source *s)
Internal: removes a source from all module tracking.
void notifyWorker()
Internal: wakes the decode worker thread.
void fillPendingFromDecoder()
Called by the Audio worker thread. Internally synchronized against concurrent decoder teardown (see d...
void play()
Starts (or resumes) playback.
void pause()
Pauses playback, keeping the play position.
Result< void > cancelFade()
Abort an active fade, keeping the current audible volume.
void setVolume(float v)
Sets source gain (clamped to >= 0). Does not cancel an active fade target.
int getChannelCount() const
Channel count of the bound buffer/decoder (1 or 2), or 0 when unknown.
float getVolume() const
Returns the audible user volume after the last advanceFade (or committed volume).
Result< void > fadeOutAndStop(float durationSeconds, float now)
Fade audible volume to zero then stop when the ramp completes.
void setVelocity(float x, float y, float z)
Sets the source velocity (used by OpenAL doppler).
bool isPlaying() const
True when playing.
Result< void > setBalance(float balance)
Stereo/ambient balance in [-1,1] (left..right).
float getPitch() const
Returns the pitch.
void setRelative(bool relative)
Makes the source ignore the listener position (head-relative).
void setPosition(float x, float y, float z)
Sets the source position in world units.
void stop()
Stops playback and rewinds the play position.
Result< void > fadeTo(float targetVolume, float durationSeconds, float now)
Ramp audible volume toward targetVolume using injected simulation time.
Result< void > setRolloffFactor(float factor)
Sets OpenAL rolloff factor (clamped to >= 0).
double getDuration() const
Total duration in seconds (0 for live/unbounded streams).
Result< void > setSpatialBlend(float blend)
Continuous 2D/3D mix: 0 = ambient bed (relative, no rolloff), 1 = full world.
Result< void > advanceFade(float now)
Advance an active fade envelope to absolute simulation time now.
double tell() const
Current play time in seconds.
void setAttenuationDistances(float ref, float max)
Sets OpenAL reference and maximum attenuation distances.
bool seek(double seconds)
Seeks to a time in seconds; false when seeking is unsupported.
Source(Audio *audio, sound::SoundData *data)
Creates a static source from decoded audio (both arguments required).
void setLooping(bool l)
Enables/disables looping.
void setDirection(float x, float y, float z)
Sets the source directional cone orientation.
bool isLooping() const
True when looping.
void pump()
Main thread: queues/unqueues AL buffers for a streaming source.
void setPitch(float p)
Sets playback pitch (clamped to >= 0).
Streaming audio decoder (medialoader-backed). Native builds own encoded bytes and decode incrementall...
void * getBuffer() const
Internal decoded buffer.
double getDuration()
Total duration in seconds.
int getSampleRate() const
Returns the sample rate.
bool isSeekable()
True when seeking is supported.
int getChannelCount() const
Format metadata.
bool rewind()
Rewinds to the start; false when unsupported.
bool seek(double seconds)
Seeks to a time in seconds; false when unsupported.
int getBitDepth() const
Returns the bit depth.
int decode()
Decodes the next chunk; returns bytes produced (0 = end/error).
Raw PCM audio buffer with format metadata (samples/rate/bit depth/channels).
double getDuration() const
Duration in seconds.
void * getData() const
Raw PCM access.
int getBitDepth() const
Returns the bit depth.
int getChannelCount() const
Returns the channel count.
int getSampleRate() const
Returns the sample rate.
size_t getSize() const
Returns the size.
constexpr int kStreamBufferCount
流式 Source 的 OpenAL 缓冲数量。
Build metadata (engine git commit, build time, third-party version).
std::vector< uint8_t > bytes