11 #include "alure2-alext.h"
13 #include "alure2-aliases.h"
14 #include "alure2-typeviews.h"
17 #ifndef ALURE_STATIC_LIB
19 #define ALURE_API __declspec(dllimport)
20 #elif defined(__has_attribute)
21 #if __has_attribute(visibility)
22 #define ALURE_API __attribute__((visibility("default")))
24 #elif defined(__GNUC__)
25 #define ALURE_API __attribute__((visibility("default")))
31 #endif /* ALURE_API */
33 #ifndef EFXEAXREVERBPROPERTIES_DEFINED
34 #define EFXEAXREVERBPROPERTIES_DEFINED
44 float flReflectionsGain
;
45 float flReflectionsDelay
;
46 float flReflectionsPan
[3];
47 float flLateReverbGain
;
48 float flLateReverbDelay
;
49 float flLateReverbPan
[3];
52 float flModulationTime
;
53 float flModulationDepth
;
54 float flAirAbsorptionGainHF
;
57 float flRoomRolloffFactor
;
59 } EFXEAXREVERBPROPERTIES
, *LPEFXEAXREVERBPROPERTIES
;
64 // Available class interfaces.
72 class AuxiliaryEffectSlot
;
78 // Opaque class implementations.
79 class DeviceManagerImpl
;
85 class SourceGroupImpl
;
86 class AuxiliaryEffectSlotImpl
;
89 /** Convert a value from decibels to linear gain. */
90 template<typename T
, typename NonRefT
=RemoveRefT
<T
>,
91 typename
=EnableIfT
<std::is_floating_point
<NonRefT
>::value
>>
92 constexpr inline NonRefT
dBToLinear(T
&& value
)
93 { return std::pow(NonRefT(10.0), std::forward
<T
>(value
) / NonRefT(20.0)); }
95 /** Convert a value from linear gain to decibels. */
96 template<typename T
, typename NonRefT
=RemoveRefT
<T
>,
97 typename
=EnableIfT
<std::is_floating_point
<NonRefT
>::value
>>
98 constexpr inline NonRefT
LinearTodB(T
&& value
)
99 { return std::log10(std::forward
<T
>(value
)) * NonRefT(20.0); }
102 * An attribute pair, for passing attributes to Device::createContext and
105 using AttributePair
= std::pair
<ALCint
,ALCint
>;
106 static_assert(sizeof(AttributePair
) == sizeof(ALCint
[2]), "Bad AttributePair size");
107 inline AttributePair
AttributesEnd() noexcept
{ return std::make_pair(0, 0); }
110 struct FilterParams
{
112 ALfloat mGainHF
; // For low-pass and band-pass filters
113 ALfloat mGainLF
; // For high-pass and band-pass filters
118 Array
<ALfloat
,3> mValue
;
121 constexpr Vector3() noexcept
122 : mValue
{{0.0f
, 0.0f
, 0.0f
}}
124 constexpr Vector3(const Vector3
&rhs
) noexcept
125 : mValue
{{rhs
.mValue
[0], rhs
.mValue
[1], rhs
.mValue
[2]}}
127 constexpr Vector3(ALfloat val
) noexcept
128 : mValue
{{val
, val
, val
}}
130 constexpr Vector3(ALfloat x
, ALfloat y
, ALfloat z
) noexcept
133 Vector3(const ALfloat
*vec
) noexcept
134 : mValue
{{vec
[0], vec
[1], vec
[2]}}
137 const ALfloat
*getPtr() const noexcept
138 { return mValue
.data(); }
140 ALfloat
& operator[](size_t i
) noexcept
141 { return mValue
[i
]; }
142 constexpr const ALfloat
& operator[](size_t i
) const noexcept
143 { return mValue
[i
]; }
145 #define ALURE_DECL_OP(op) \
146 constexpr Vector3 operator op(const Vector3 &rhs) const noexcept \
148 return Vector3(mValue[0] op rhs.mValue[0], \
149 mValue[1] op rhs.mValue[1], \
150 mValue[2] op rhs.mValue[2]); \
157 #define ALURE_DECL_OP(op) \
158 Vector3& operator op(const Vector3 &rhs) noexcept \
160 mValue[0] op rhs.mValue[0]; \
161 mValue[1] op rhs.mValue[1]; \
162 mValue[2] op rhs.mValue[2]; \
171 #define ALURE_DECL_OP(op) \
172 constexpr Vector3 operator op(ALfloat scale) const noexcept \
174 return Vector3(mValue[0] op scale, \
175 mValue[1] op scale, \
176 mValue[2] op scale); \
181 #define ALURE_DECL_OP(op) \
182 Vector3& operator op(ALfloat scale) noexcept \
184 mValue[0] op scale; \
185 mValue[1] op scale; \
186 mValue[2] op scale; \
193 constexpr ALfloat
getLengthSquared() const noexcept
194 { return mValue
[0]*mValue
[0] + mValue
[1]*mValue
[1] + mValue
[2]*mValue
[2]; }
195 ALfloat
getLength() const noexcept
196 { return std::sqrt(getLengthSquared()); }
198 constexpr ALfloat
getDistanceSquared(const Vector3
&pos
) const noexcept
199 { return (pos
- *this).getLengthSquared(); }
200 ALfloat
getDistance(const Vector3
&pos
) const noexcept
201 { return (pos
- *this).getLength(); }
203 static_assert(sizeof(Vector3
) == sizeof(ALfloat
[3]), "Bad Vector3 size");
206 enum class SampleType
{
212 ALURE_API
const char *GetSampleTypeName(SampleType type
);
214 enum class ChannelConfig
{
215 /** 1-channel mono sound. */
217 /** 2-channel stereo sound. */
219 /** 2-channel rear sound (back-left and back-right). */
221 /** 4-channel surround sound. */
223 /** 5.1 surround sound. */
225 /** 6.1 surround sound. */
227 /** 7.1 surround sound. */
229 /** 3-channel B-Format, using FuMa channel ordering and scaling. */
231 /** 4-channel B-Format, using FuMa channel ordering and scaling. */
234 ALURE_API
const char *GetChannelConfigName(ChannelConfig cfg
);
236 ALURE_API ALuint
FramesToBytes(ALuint frames
, ChannelConfig chans
, SampleType type
);
237 ALURE_API ALuint
BytesToFrames(ALuint bytes
, ChannelConfig chans
, SampleType type
);
240 /** Class for storing a major.minor version number. */
246 constexpr Version() noexcept
: mMajor(0), mMinor(0) { }
247 constexpr Version(ALuint _maj
, ALuint _min
) noexcept
: mMajor(_maj
), mMinor(_min
) { }
248 constexpr Version(const Version
&) noexcept
= default;
250 constexpr ALuint
getMajor() const noexcept
{ return mMajor
; }
251 constexpr ALuint
getMinor() const noexcept
{ return mMinor
; }
253 constexpr bool operator==(const Version
&rhs
) const noexcept
254 { return mMajor
== rhs
.mMajor
&& mMinor
== rhs
.mMinor
; }
255 constexpr bool operator!=(const Version
&rhs
) const noexcept
256 { return !(*this == rhs
); }
257 constexpr bool operator<=(const Version
&rhs
) const noexcept
258 { return mMajor
< rhs
.mMajor
|| (mMajor
== rhs
.mMajor
&& mMinor
<= rhs
.mMinor
); }
259 constexpr bool operator>=(const Version
&rhs
) const noexcept
260 { return mMajor
> rhs
.mMajor
|| (mMajor
== rhs
.mMajor
&& mMinor
>= rhs
.mMinor
); }
261 constexpr bool operator<(const Version
&rhs
) const noexcept
262 { return mMajor
< rhs
.mMajor
|| (mMajor
== rhs
.mMajor
&& mMinor
< rhs
.mMinor
); }
263 constexpr bool operator>(const Version
&rhs
) const noexcept
264 { return mMajor
> rhs
.mMajor
|| (mMajor
== rhs
.mMajor
&& mMinor
> rhs
.mMinor
); }
266 constexpr bool isZero() const noexcept
{ return *this == Version
{0,0}; }
269 #define MAKE_PIMPL(BaseT, ImplT) \
274 using handle_type = ImplT*; \
276 BaseT() : pImpl(nullptr) { } \
277 BaseT(ImplT *impl) : pImpl(impl) { } \
278 BaseT(const BaseT&) = default; \
279 BaseT(BaseT&& rhs) : pImpl(rhs.pImpl) { rhs.pImpl = nullptr; } \
281 BaseT& operator=(const BaseT&) = default; \
282 BaseT& operator=(BaseT&& rhs) \
284 pImpl = rhs.pImpl; rhs.pImpl = nullptr; \
288 bool operator==(const BaseT &rhs) const { return pImpl == rhs.pImpl; } \
289 bool operator!=(const BaseT &rhs) const { return pImpl != rhs.pImpl; } \
290 bool operator<=(const BaseT &rhs) const { return pImpl <= rhs.pImpl; } \
291 bool operator>=(const BaseT &rhs) const { return pImpl >= rhs.pImpl; } \
292 bool operator<(const BaseT &rhs) const { return pImpl < rhs.pImpl; } \
293 bool operator>(const BaseT &rhs) const { return pImpl > rhs.pImpl; } \
295 operator bool() const { return !!pImpl; } \
297 handle_type getHandle() const { return pImpl; }
299 enum class DeviceEnumeration
{
300 Basic
= ALC_DEVICE_SPECIFIER
,
301 Full
= ALC_ALL_DEVICES_SPECIFIER
,
302 Capture
= ALC_CAPTURE_DEVICE_SPECIFIER
305 enum class DefaultDeviceType
{
306 Basic
= ALC_DEFAULT_DEVICE_SPECIFIER
,
307 Full
= ALC_DEFAULT_ALL_DEVICES_SPECIFIER
,
308 Capture
= ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER
312 * A class managing Device objects and other related functionality. This class
313 * is a singleton, only one instance will exist in a process.
315 class ALURE_API DeviceManager
{
316 DeviceManagerImpl
&pImpl
;
318 DeviceManager(DeviceManagerImpl
&impl
) : pImpl(impl
) { }
321 DeviceManager(const DeviceManager
&) = default;
322 DeviceManager(DeviceManager
&& rhs
) : pImpl(rhs
.pImpl
) { }
324 /** Retrieves the DeviceManager instance. */
325 static DeviceManager
get();
327 /** Queries the existence of a non-device-specific ALC extension. */
328 bool queryExtension(const String
&name
) const;
329 bool queryExtension(const char *name
) const;
331 /** Enumerates available device names of the given type. */
332 Vector
<String
> enumerate(DeviceEnumeration type
) const;
333 /** Retrieves the default device of the given type. */
334 String
defaultDeviceName(DefaultDeviceType type
) const;
337 * Opens the playback device given by name, or the default if blank. Throws
338 * an exception on error.
340 Device
openPlayback(const String
&name
={});
341 Device
openPlayback(const char *name
);
344 * Opens the playback device given by name, or the default if blank.
345 * Returns an empty Device on error.
347 Device
openPlayback(const String
&name
, const std::nothrow_t
&) noexcept
;
348 Device
openPlayback(const char *name
, const std::nothrow_t
&) noexcept
;
350 /** Opens the default playback device. Returns an empty Device on error. */
351 Device
openPlayback(const std::nothrow_t
&) noexcept
;
355 enum class PlaybackName
{
356 Basic
= ALC_DEVICE_SPECIFIER
,
357 Full
= ALC_ALL_DEVICES_SPECIFIER
360 class ALURE_API Device
{
361 MAKE_PIMPL(Device
, DeviceImpl
)
364 /** Retrieves the device name as given by type. */
365 String
getName(PlaybackName type
=PlaybackName::Full
) const;
366 /** Queries the existence of an ALC extension on this device. */
367 bool queryExtension(const String
&name
) const;
368 bool queryExtension(const char *name
) const;
370 /** Retrieves the ALC version supported by this device. */
371 Version
getALCVersion() const;
374 * Retrieves the EFX version supported by this device. If the ALC_EXT_EFX
375 * extension is unsupported, this will be 0.0.
377 Version
getEFXVersion() const;
379 /** Retrieves the device's playback frequency, in hz. */
380 ALCuint
getFrequency() const;
383 * Retrieves the maximum number of auxiliary source sends. If ALC_EXT_EFX
384 * is unsupported, this will be 0.
386 ALCuint
getMaxAuxiliarySends() const;
389 * Enumerates available HRTF names. The names are sorted as OpenAL gives
390 * them, such that the index of a given name is the ID to use with
393 * If the ALC_SOFT_HRTF extension is unavailable, this will return an empty
396 Vector
<String
> enumerateHRTFNames() const;
399 * Retrieves whether HRTF is enabled on the device or not.
401 * If the ALC_SOFT_HRTF extension is unavailable, this will return false
402 * although there could still be HRTF applied at a lower hardware level.
404 bool isHRTFEnabled() const;
407 * Retrieves the name of the HRTF currently being used by this device.
409 * If HRTF is not currently enabled, this will be empty.
411 String
getCurrentHRTF() const;
414 * Resets the device, using the specified attributes.
416 * If the ALC_SOFT_HRTF extension is unavailable, this will be a no-op.
418 void reset(ArrayView
<AttributePair
> attributes
);
421 * Creates a new Context on this device, using the specified attributes.
422 * Throws an exception if context creation fails.
424 Context
createContext(ArrayView
<AttributePair
> attributes
={});
426 * Creates a new Context on this device, using the specified attributes.
427 * Returns an empty Context if context creation fails.
429 Context
createContext(ArrayView
<AttributePair
> attributes
, const std::nothrow_t
&) noexcept
;
430 Context
createContext(const std::nothrow_t
&) noexcept
;
433 * Pauses device processing, stopping updates for its contexts. Multiple
434 * calls are allowed but it is not reference counted, so the device will
435 * resume after one resumeDSP call.
437 * Requires the ALC_SOFT_pause_device extension.
442 * Resumes device processing, restarting updates for its contexts. Multiple
443 * calls are allowed and will no-op.
448 * Closes and frees the device. All previously-created contexts must first
455 enum class DistanceModel
{
456 InverseClamped
= AL_INVERSE_DISTANCE_CLAMPED
,
457 LinearClamped
= AL_LINEAR_DISTANCE_CLAMPED
,
458 ExponentClamped
= AL_EXPONENT_DISTANCE_CLAMPED
,
459 Inverse
= AL_INVERSE_DISTANCE
,
460 Linear
= AL_LINEAR_DISTANCE
,
461 Exponent
= AL_EXPONENT_DISTANCE
,
465 class ALURE_API Context
{
466 MAKE_PIMPL(Context
, ContextImpl
)
469 /** Makes the specified context current for OpenAL operations. */
470 static void MakeCurrent(Context context
);
471 /** Retrieves the current context used for OpenAL operations. */
472 static Context
GetCurrent();
475 * Makes the specified context current for OpenAL operations on the calling
476 * thread only. Requires the ALC_EXT_thread_local_context extension on both
477 * the context's device and the DeviceManager.
479 static void MakeThreadCurrent(Context context
);
480 /** Retrieves the thread-specific context used for OpenAL operations. */
481 static Context
GetThreadCurrent();
484 * Destroys the context. The context must not be current when this is
489 /** Retrieves the Device this context was created from. */
496 * Retrieves a Listener instance for this context. Each context will only
497 * have one listener, which is automatically destroyed with the context.
499 Listener
getListener();
502 * Sets a MessageHandler instance which will be used to provide certain
503 * messages back to the application. Only one handler may be set for a
504 * context at a time. The previously set handler will be returned.
506 SharedPtr
<MessageHandler
> setMessageHandler(SharedPtr
<MessageHandler
> handler
);
508 /** Gets the currently-set message handler. */
509 SharedPtr
<MessageHandler
> getMessageHandler() const;
512 * Specifies the desired interval that the background thread will be woken
513 * up to process tasks, e.g. keeping streaming sources filled. An interval
514 * of 0 means the background thread will only be woken up manually with
515 * calls to update. The default is 0.
517 void setAsyncWakeInterval(std::chrono::milliseconds interval
);
520 * Retrieves the current interval used for waking up the background thread.
522 std::chrono::milliseconds
getAsyncWakeInterval() const;
524 // Functions below require the context to be current
527 * Creates a Decoder instance for the given audio file or resource name.
529 SharedPtr
<Decoder
> createDecoder(StringView name
);
532 * Queries if the channel configuration and sample type are supported by
535 bool isSupported(ChannelConfig channels
, SampleType type
) const;
538 * Queries the list of resamplers supported by the context. If the
539 * AL_SOFT_source_resampler extension is unsupported this will be an empty
540 * array, otherwise there will be at least one entry.
542 ArrayView
<String
> getAvailableResamplers();
544 * Queries the context's default resampler index. Be aware, if the
545 * AL_SOFT_source_resampler extension is unsupported the resampler list
546 * will be empty and this will resturn 0. If you try to access the
547 * resampler list with this index without the extension, undefined behavior
548 * will occur (accessing an out of bounds array index).
550 ALsizei
getDefaultResamplerIndex() const;
553 * Creates and caches a Buffer for the given audio file or resource name.
554 * Multiple calls with the same name will return the same Buffer object.
555 * Cached buffers must be freed using removeBuffer before destroying the
556 * context. If the buffer can't be loaded it will throw an exception.
558 Buffer
getBuffer(StringView name
);
561 * Asynchronously prepares a cached Buffer for the given audio file or
562 * resource name. Multiple calls with the same name will return multiple
563 * SharedFutures for the same Buffer object. Once called, the buffer must
564 * be freed using removeBuffer before destroying the context, even if you
565 * never get the Buffer from the SharedFuture.
567 * The Buffer will be scheduled to load asynchronously, and the caller gets
568 * back a SharedFuture that can be checked later (or waited on) to get the
569 * actual Buffer when it's ready. The application must take care to handle
570 * exceptions from the SharedFuture in case an unrecoverable error ocurred
573 SharedFuture
<Buffer
> getBufferAsync(StringView name
);
576 * Asynchronously prepares cached Buffers for the given audio file or
577 * resource names. Duplicate names and buffers already cached are ignored.
578 * Cached buffers must be freed using removeBuffer before destroying the
581 * The Buffer objects will be scheduled for loading asynchronously, and
582 * should be retrieved later when needed using getBufferAsync or getBuffer.
583 * Buffers that cannot be loaded, for example due to an unsupported format,
584 * will be ignored and a later call to getBuffer or getBufferAsync will
585 * throw an exception.
587 void precacheBuffersAsync(ArrayView
<StringView
> names
);
590 * Creates and caches a Buffer using the given name by reading the given
591 * decoder. The name may alias an audio file, but it must not currently
592 * exist in the buffer cache.
594 Buffer
createBufferFrom(StringView name
, SharedPtr
<Decoder
> decoder
);
597 * Asynchronously prepares a cached Buffer using the given name by reading
598 * the given decoder. The name may alias an audio file, but it must not
599 * currently exist in the buffer cache. Once called, the buffer must be
600 * freed using removeBuffer before destroying the context, even if you
601 * never get the Buffer from the SharedFuture.
603 * The Buffer will be scheduled to load asynchronously, and the caller gets
604 * back a SharedFuture that can be checked later (or waited on) to get the
605 * actual Buffer when it's ready. The application must take care to handle
606 * exceptions from the SharedFuture in case an unrecoverable error ocurred
607 * during the load. The decoder must not have its read or seek methods
608 * called while the buffer is not ready.
610 SharedFuture
<Buffer
> createBufferAsyncFrom(StringView name
, SharedPtr
<Decoder
> decoder
);
613 * Looks for a cached buffer using the given name and returns it. If the
614 * given name does not exist in the cache, and null buffer is returned.
616 Buffer
findBuffer(StringView name
);
619 * Looks for an asynchronously-loading buffer using the given name and
620 * returns a SharedFuture for it. If the given name does not exist in the
621 * cache, an invalid SharedFuture is returned (check with a call to
622 * \c SharedFuture::valid).
624 SharedFuture
<Buffer
> findBufferAsync(StringView name
);
627 * Deletes the cached Buffer object for the given audio file or resource
628 * name. If a source is currently playing the buffer, it will be stopped
631 void removeBuffer(StringView name
);
633 * Deletes the given cached buffer. If a source is currently playing the
634 * buffer, it will be stopped first.
636 void removeBuffer(Buffer buffer
);
639 * Creates a new Source for playing audio. There is no practical limit to
640 * the number of sources you may create. You must call Source::release when
641 * the source is no longer needed.
643 Source
createSource();
645 AuxiliaryEffectSlot
createAuxiliaryEffectSlot();
647 Effect
createEffect();
649 SourceGroup
createSourceGroup();
651 /** Sets the doppler factor to apply to all source doppler calculations. */
652 void setDopplerFactor(ALfloat factor
);
655 * Sets the speed of sound propagation, in units per second, to calculate
656 * the doppler effect along with other distance-related time effects. The
657 * default is 343.3 units per second (a realistic speed assuming 1 meter
658 * per unit). If this is adjusted for a different unit scale,
659 * Listener::setMetersPerUnit should also be adjusted.
661 void setSpeedOfSound(ALfloat speed
);
664 * Sets the distance model used to attenuate sources given their distance
665 * from the listener. The default, InverseClamped, provides a realistic 1/r
666 * reduction in volume (that is, every doubling of distance causes the gain
667 * to reduce by half).
669 * The Clamped distance models restrict the source distance for the purpose
670 * of distance attenuation, so a source won't sound closer than its
671 * reference distance or farther than its max distance.
673 void setDistanceModel(DistanceModel model
);
675 /** Updates the context and all sources belonging to this context. */
679 class ALURE_API Listener
{
680 MAKE_PIMPL(Listener
, ListenerImpl
)
683 /** Sets the "master" gain for all context output. */
684 void setGain(ALfloat gain
);
687 * Specifies the listener's 3D position, velocity, and orientation
688 * together (see: setPosition, setVelocity, and setOrientation).
690 void set3DParameters(const Vector3
&position
, const Vector3
&velocity
, const std::pair
<Vector3
,Vector3
> &orientation
);
692 /** Specifies the listener's 3D position. */
693 void setPosition(const Vector3
&position
);
694 void setPosition(const ALfloat
*pos
);
697 * Specifies the listener's 3D velocity, in units per second. As with
698 * OpenAL, this does not actually alter the listener's position, and
699 * instead just alters the pitch as determined by the doppler effect.
701 void setVelocity(const Vector3
&velocity
);
702 void setVelocity(const ALfloat
*vel
);
705 * Specifies the listener's 3D orientation, using position-relative 'at'
706 * and 'up' direction vectors.
708 void setOrientation(const std::pair
<Vector3
,Vector3
> &orientation
);
709 void setOrientation(const ALfloat
*at
, const ALfloat
*up
);
710 void setOrientation(const ALfloat
*ori
);
713 * Sets the number of meters per unit, used for various effects that rely
714 * on the distance in meters (including air absorption and initial reverb
715 * decay). If this is changed, it's strongly recommended to also set the
716 * speed of sound (e.g. context.setSpeedOfSound(343.3 / m_u) to maintain a
717 * realistic 343.3m/s for sound propagation).
719 void setMetersPerUnit(ALfloat m_u
);
723 class ALURE_API Buffer
{
724 MAKE_PIMPL(Buffer
, BufferImpl
)
727 /** Retrieves the length of the buffer in sample frames. */
728 ALuint
getLength() const;
730 /** Retrieves the buffer's frequency in hz. */
731 ALuint
getFrequency() const;
733 /** Retrieves the buffer's sample configuration. */
734 ChannelConfig
getChannelConfig() const;
736 /** Retrieves the buffer's sample type. */
737 SampleType
getSampleType() const;
740 * Retrieves the storage size used by the buffer, in bytes. Note that the
741 * size in bytes may not be what you expect from the length, as it may take
742 * more space internally than the ChannelConfig and SampleType suggest to
745 ALuint
getSize() const;
748 * Sets the buffer's loop points, used for looping sources. If the current
749 * context does not support the AL_SOFT_loop_points extension, start and
750 * end must be 0 and getLength() respectively. Otherwise, start must be
751 * less than end, and end must be less than or equal to getLength().
753 * The buffer must not be in use when this method is called.
755 * \param start The starting point, in sample frames (inclusive).
756 * \param end The ending point, in sample frames (exclusive).
758 void setLoopPoints(ALuint start
, ALuint end
);
760 /** Retrieves the current loop points as a [start,end) pair. */
761 std::pair
<ALuint
,ALuint
> getLoopPoints() const;
764 * Retrieves the Source objects currently playing the buffer. Stopping the
765 * returned sources will allow the buffer to be removed from the context.
767 Vector
<Source
> getSources() const;
769 /** Retrieves the name the buffer was created with. */
770 StringView
getName() const;
773 * Queries the number of sources currently using the buffer. Be aware that
774 * you need to call \c Context::update to reliably ensure the count is kept
775 * updated for when sources reach their end. This is equivalent to calling
776 * getSources().size().
778 size_t getSourceCount() const;
782 enum class Spatialize
{
785 Auto
= 0x0002 /* AL_AUTO_SOFT */
788 class ALURE_API Source
{
789 MAKE_PIMPL(Source
, SourceImpl
)
793 * Plays the source using a buffer. The same buffer may be played from
794 * multiple sources simultaneously.
796 void play(Buffer buffer
);
798 * Plays the source by asynchronously streaming audio from a decoder. The
799 * given decoder must *NOT* have its read or seek methods called from
800 * elsewhere while in use.
802 * \param decoder The decoder object to play audio from.
803 * \param chunk_len The number of sample frames to read for each chunk
804 * update. Smaller values will require more frequent updates and
805 * larger values will handle more data with each chunk.
806 * \param queue_size The number of chunks to keep queued during playback.
807 * Smaller values use less memory while larger values improve
808 * protection against underruns.
810 void play(SharedPtr
<Decoder
> decoder
, ALuint chunk_len
, ALuint queue_size
);
813 * Prepares to play a source using a future buffer. The method will return
814 * right away and the source will begin playing once the future buffer
815 * becomes ready. If the future buffer is already ready, it begins playing
816 * immediately as if you called play(future_buffer.get()).
818 * The future buffer is checked during calls to \c Context::update and the
819 * source will start playback once the future buffer reports it's ready.
820 * Use the isPending method to check if the source is still waiting for the
823 void play(SharedFuture
<Buffer
> future_buffer
);
826 * Stops playback, releasing the buffer or decoder reference. Any pending
827 * playback from a future buffer is canceled.
832 * Fades the source to the specified gain over the given duration, at which
833 * point playback will stop. This gain is in addition to the base gain, and
834 * must be greater than 0 and less than 1. The duration must also be
837 * Pending playback from a future buffer is not immediately canceled, but
838 * the fading starts with this call. If the future buffer then becomes
839 * ready, it will start mid-fade. Pending playback will be canceled if the
840 * fade out completes before the future buffer becomes ready.
842 * Fading is updated during calls to \c Context::update, which should be
843 * called regularly (30 to 50 times per second) for the fading to be
846 void fadeOutToStop(ALfloat gain
, std::chrono::milliseconds duration
);
848 /** Pauses the source if it is playing. */
851 /** Resumes the source if it is paused. */
854 /** Specifies if the source is waiting to play a future buffer. */
855 bool isPending() const;
857 /** Specifies if the source is currently playing. */
858 bool isPlaying() const;
860 /** Specifies if the source is currently paused. */
861 bool isPaused() const;
864 * Sets this source as a child of the given source group. The given source
865 * group's parameters will influence this and all other sources that belong
866 * to it. A source can only be the child of one source group at a time,
867 * although that source group may belong to another source group.
869 * Passing in a null group removes it from its current source group.
871 void setGroup(SourceGroup group
);
873 /** Retrieves the source group this source belongs to. */
874 SourceGroup
getGroup() const;
877 * Specifies the source's playback priority. The lowest priority sources
878 * will be forcefully stopped when no more mixing sources are available and
879 * higher priority sources are played.
881 void setPriority(ALuint priority
);
882 /** Retrieves the source's priority. */
883 ALuint
getPriority() const;
886 * Sets the source's offset, in sample frames. If the source is playing or
887 * paused, it will go to that offset immediately, otherwise the source will
888 * start at the specified offset the next time it's played.
890 void setOffset(uint64_t offset
);
892 * Retrieves the source offset in sample frames and its latency in nano-
893 * seconds. For streaming sources this will be the offset based on the
894 * decoder's read position.
896 * If the AL_SOFT_source_latency extension is unsupported, the latency will
899 std::pair
<uint64_t,std::chrono::nanoseconds
> getSampleOffsetLatency() const;
900 uint64_t getSampleOffset() const { return std::get
<0>(getSampleOffsetLatency()); }
902 * Retrieves the source offset and latency in seconds. For streaming
903 * sources this will be the offset based on the decoder's read position.
905 * If the AL_SOFT_source_latency extension is unsupported, the latency will
908 std::pair
<Seconds
,Seconds
> getSecOffsetLatency() const;
909 Seconds
getSecOffset() const { return std::get
<0>(getSecOffsetLatency()); }
912 * Specifies if the source should loop on the Buffer or Decoder object's
915 void setLooping(bool looping
);
916 bool getLooping() const;
919 * Specifies a linear pitch shift base. A value of 1.0 is the default
922 void setPitch(ALfloat pitch
);
923 ALfloat
getPitch() const;
926 * Specifies the base linear gain. A value of 1.0 is the default normal
929 void setGain(ALfloat gain
);
930 ALfloat
getGain() const;
933 * Specifies the minimum and maximum gain. The source's gain is clamped to
934 * this range after distance attenuation and cone attenuation are applied
935 * to the gain base, although before the filter gain adjustements.
937 void setGainRange(ALfloat mingain
, ALfloat maxgain
);
938 std::pair
<ALfloat
,ALfloat
> getGainRange() const;
939 ALfloat
getMinGain() const { return std::get
<0>(getGainRange()); }
940 ALfloat
getMaxGain() const { return std::get
<1>(getGainRange()); }
943 * Specifies the reference distance and maximum distance the source will
944 * use for the current distance model. For Clamped distance models, the
945 * source's calculated distance is clamped to the specified range before
946 * applying distance-related attenuation.
948 * For all distance models, the reference distance is the distance at which
949 * the source's volume will not have any extra attenuation (an effective
950 * gain multiplier of 1).
952 void setDistanceRange(ALfloat refdist
, ALfloat maxdist
);
953 std::pair
<ALfloat
,ALfloat
> getDistanceRange() const;
954 ALfloat
getReferenceDistance() const { return std::get
<0>(getDistanceRange()); }
955 ALfloat
getMaxDistance() const { return std::get
<1>(getDistanceRange()); }
958 * Specifies the source's 3D position, velocity, and direction together
959 * (see: setPosition, setVelocity, and setDirection).
961 void set3DParameters(const Vector3
&position
, const Vector3
&velocity
, const Vector3
&direction
);
964 * Specifies the source's 3D position, velocity, and orientation together
965 * (see: setPosition, setVelocity, and setOrientation).
967 void set3DParameters(const Vector3
&position
, const Vector3
&velocity
, const std::pair
<Vector3
,Vector3
> &orientation
);
969 /** Specifies the source's 3D position. */
970 void setPosition(const Vector3
&position
);
971 void setPosition(const ALfloat
*pos
);
972 Vector3
getPosition() const;
975 * Specifies the source's 3D velocity, in units per second. As with OpenAL,
976 * this does not actually alter the source's position, and instead just
977 * alters the pitch as determined by the doppler effect.
979 void setVelocity(const Vector3
&velocity
);
980 void setVelocity(const ALfloat
*vel
);
981 Vector3
getVelocity() const;
984 * Specifies the source's 3D facing direction. Deprecated in favor of
987 void setDirection(const Vector3
&direction
);
988 void setDirection(const ALfloat
*dir
);
989 Vector3
getDirection() const;
992 * Specifies the source's 3D orientation, using position-relative 'at' and
993 * 'up' direction vectors. Note: unlike the AL_EXT_BFORMAT extension this
994 * property comes from, this also affects the facing direction, superceding
997 void setOrientation(const std::pair
<Vector3
,Vector3
> &orientation
);
998 void setOrientation(const ALfloat
*at
, const ALfloat
*up
);
999 void setOrientation(const ALfloat
*ori
);
1000 std::pair
<Vector3
,Vector3
> getOrientation() const;
1003 * Specifies the source's cone angles, in degrees. The inner angle is the
1004 * area within which the listener will hear the source with no extra
1005 * attenuation, while the listener being outside of the outer angle will
1006 * hear the source attenuated according to the outer cone gains. The area
1007 * follows the facing direction, so for example an inner angle of 180 means
1008 * the entire front face of the source is in the inner cone.
1010 void setConeAngles(ALfloat inner
, ALfloat outer
);
1011 std::pair
<ALfloat
,ALfloat
> getConeAngles() const;
1012 ALfloat
getInnerConeAngle() const { return std::get
<0>(getConeAngles()); }
1013 ALfloat
getOuterConeAngle() const { return std::get
<1>(getConeAngles()); }
1016 * Specifies the linear gain multiplier when the listener is outside of the
1017 * source's outer cone area. The specified gain applies to all frequencies,
1018 * while gainhf applies extra attenuation to high frequencies creating a
1021 * \param gainhf has no effect without the ALC_EXT_EFX extension.
1023 void setOuterConeGains(ALfloat gain
, ALfloat gainhf
=1.0f
);
1024 std::pair
<ALfloat
,ALfloat
> getOuterConeGains() const;
1025 ALfloat
getOuterConeGain() const { return std::get
<0>(getOuterConeGains()); }
1026 ALfloat
getOuterConeGainHF() const { return std::get
<1>(getOuterConeGains()); }
1029 * Specifies the rolloff factors for the direct and send paths. This is
1030 * effectively a distance scaling relative to the reference distance. Note:
1031 * the room rolloff factor is 0 by default, disabling distance attenuation
1032 * for send paths. This is because the reverb engine will, by default,
1033 * apply a more realistic room decay based on the reverb decay time and
1036 void setRolloffFactors(ALfloat factor
, ALfloat roomfactor
=0.0f
);
1037 std::pair
<ALfloat
,ALfloat
> getRolloffFactors() const;
1038 ALfloat
getRolloffFactor() const { return std::get
<0>(getRolloffFactors()); }
1039 ALfloat
getRoomRolloffFactor() const { return std::get
<1>(getRolloffFactors()); }
1042 * Specifies the doppler factor for the doppler effect's pitch shift. This
1043 * effectively scales the source and listener velocities for the doppler
1046 void setDopplerFactor(ALfloat factor
);
1047 ALfloat
getDopplerFactor() const;
1050 * Specifies if the source's position, velocity, and direction/orientation
1051 * are relative to the listener.
1053 void setRelative(bool relative
);
1054 bool getRelative() const;
1057 * Specifies the source's radius. This causes the source to behave as if
1058 * every point within the spherical area emits sound.
1060 * Has no effect without the AL_EXT_SOURCE_RADIUS extension.
1062 void setRadius(ALfloat radius
);
1063 ALfloat
getRadius() const;
1066 * Specifies the left and right channel angles, in radians, when playing a
1067 * stereo buffer or stream. The angles go counter-clockwise, with 0 being
1068 * in front and positive values going left.
1070 * Has no effect without the AL_EXT_STEREO_ANGLES extension.
1072 void setStereoAngles(ALfloat leftAngle
, ALfloat rightAngle
);
1073 std::pair
<ALfloat
,ALfloat
> getStereoAngles() const;
1076 * Specifies if the source always has 3D spatialization features (On),
1077 * never has 3D spatialization features (Off), or if spatialization is
1078 * enabled based on playing a mono sound or not (Auto, default).
1080 * Has no effect without the AL_SOFT_source_spatialize extension.
1082 void set3DSpatialize(Spatialize spatialize
);
1083 Spatialize
get3DSpatialize() const;
1086 * Specifies the index of the resampler to use for this source. The index
1087 * is from the resamplers returned by \c Context::getAvailableResamplers,
1088 * and must be 0 or greater.
1090 * Has no effect without the AL_SOFT_source_resampler extension.
1092 void setResamplerIndex(ALsizei index
);
1093 ALsizei
getResamplerIndex() const;
1096 * Specifies a multiplier for the amount of atmospheric high-frequency
1097 * absorption, ranging from 0 to 10. A factor of 1 results in a nominal
1098 * -0.05dB per meter, with higher values simulating foggy air and lower
1099 * values simulating dryer air. The default is 0.
1101 void setAirAbsorptionFactor(ALfloat factor
);
1102 ALfloat
getAirAbsorptionFactor() const;
1105 * Specifies to automatically apply adjustments to the direct path's high-
1106 * frequency gain, and the send paths' gain and high-frequency gain. The
1107 * default is true for all.
1109 void setGainAuto(bool directhf
, bool send
, bool sendhf
);
1110 std::tuple
<bool,bool,bool> getGainAuto() const;
1111 bool getDirectGainHFAuto() const { return std::get
<0>(getGainAuto()); }
1112 bool getSendGainAuto() const { return std::get
<1>(getGainAuto()); }
1113 bool getSendGainHFAuto() const { return std::get
<2>(getGainAuto()); }
1115 /** Sets the filter properties on the direct path signal. */
1116 void setDirectFilter(const FilterParams
&filter
);
1118 * Sets the filter properties on the given send path signal. Any auxiliary
1119 * effect slot on the send path remains in place.
1121 void setSendFilter(ALuint send
, const FilterParams
&filter
);
1123 * Connects the effect slot to the given send path. Any filter properties
1124 * on the send path remain as they were.
1126 void setAuxiliarySend(AuxiliaryEffectSlot slot
, ALuint send
);
1128 * Connects the effect slot to the given send path, using the filter
1131 void setAuxiliarySendFilter(AuxiliaryEffectSlot slot
, ALuint send
, const FilterParams
&filter
);
1134 * Releases the source, stopping playback, releasing resources, and
1135 * returning it to the system.
1141 class ALURE_API SourceGroup
{
1142 MAKE_PIMPL(SourceGroup
, SourceGroupImpl
)
1146 * Adds this source group as a subgroup of the specified source group. This
1147 * method will throw an exception if this group is being added to a group
1148 * it has as a sub-group (i.e. it would create a circular sub-group chain).
1150 void setParentGroup(SourceGroup group
);
1152 /** Retrieves the source group this source group is a child of. */
1153 SourceGroup
getParentGroup() const;
1155 /** Returns the list of sources currently in the group. */
1156 Vector
<Source
> getSources() const;
1158 /** Returns the list of subgroups currently in the group. */
1159 Vector
<SourceGroup
> getSubGroups() const;
1162 * Sets the source group gain, which accumulates with its sources' and
1165 void setGain(ALfloat gain
);
1166 /** Gets the source group gain. */
1167 ALfloat
getGain() const;
1170 * Sets the source group pitch, which accumulates with its sources' and
1171 * sub-groups' pitch.
1173 void setPitch(ALfloat pitch
);
1174 /** Gets the source group pitch. */
1175 ALfloat
getPitch() const;
1178 * Pauses all currently-playing sources that are under this group,
1179 * including sub-groups.
1181 void pauseAll() const;
1183 * Resumes all paused sources that are under this group, including
1186 void resumeAll() const;
1188 /** Stops all sources that are under this group, including sub-groups. */
1189 void stopAll() const;
1192 * Releases the source group, removing all sources from it before being
1204 class ALURE_API AuxiliaryEffectSlot
{
1205 MAKE_PIMPL(AuxiliaryEffectSlot
, AuxiliaryEffectSlotImpl
)
1208 void setGain(ALfloat gain
);
1210 * If set to true, the reverb effect will automatically apply adjustments
1211 * to the source's send slot gains based on the effect properties.
1213 * Has no effect when using non-reverb effects. Default is true.
1215 void setSendAuto(bool sendauto
);
1218 * Updates the effect slot with a new effect. The given effect object may
1219 * be altered or destroyed without affecting the effect slot.
1221 void applyEffect(Effect effect
);
1224 * Releases the effect slot, returning it to the system. If the effect slot
1225 * is currently set on a source send, it will be removed first.
1230 * Retrieves each Source object and its pairing send this effect slot is
1231 * set on. Setting a different (or null) effect slot on each source's given
1232 * send will allow the effect slot to be released.
1234 Vector
<SourceSend
> getSourceSends() const;
1237 * Queries the number of source sends the effect slot is used by. This is
1238 * equivalent to calling getSourceSends().size().
1240 size_t getUseCount() const;
1244 class ALURE_API Effect
{
1245 MAKE_PIMPL(Effect
, EffectImpl
)
1249 * Updates the effect with the specified reverb properties. If the
1250 * EAXReverb effect is not supported, it will automatically attempt to
1251 * downgrade to the Standard Reverb effect.
1253 void setReverbProperties(const EFXEAXREVERBPROPERTIES
&props
);
1260 * Audio decoder interface. Applications may derive from this, implementing the
1261 * necessary methods, and use it in places the API wants a Decoder object.
1263 class ALURE_API Decoder
{
1267 /** Retrieves the sample frequency, in hz, of the audio being decoded. */
1268 virtual ALuint
getFrequency() const noexcept
= 0;
1269 /** Retrieves the channel configuration of the audio being decoded. */
1270 virtual ChannelConfig
getChannelConfig() const noexcept
= 0;
1271 /** Retrieves the sample type of the audio being decoded. */
1272 virtual SampleType
getSampleType() const noexcept
= 0;
1275 * Retrieves the total length of the audio, in sample frames. If unknown,
1276 * returns 0. Note that if the returned length is 0, the decoder may not be
1277 * used to load a Buffer.
1279 virtual uint64_t getLength() const noexcept
= 0;
1281 * Seek to pos, specified in sample frames. Returns true if the seek was
1284 virtual bool seek(uint64_t pos
) noexcept
= 0;
1287 * Retrieves the loop points, in sample frames, as a [start,end) pair. If
1288 * start >= end, all available samples are included in the loop.
1290 virtual std::pair
<uint64_t,uint64_t> getLoopPoints() const noexcept
= 0;
1293 * Decodes count sample frames, writing them to ptr, and returns the number
1294 * of sample frames written. Returning less than the requested count
1295 * indicates the end of the audio.
1297 virtual ALuint
read(ALvoid
*ptr
, ALuint count
) noexcept
= 0;
1301 * Audio decoder factory interface. Applications may derive from this,
1302 * implementing the necessary methods, and use it in places the API wants a
1303 * DecoderFactory object.
1305 class ALURE_API DecoderFactory
{
1307 virtual ~DecoderFactory();
1310 * Creates and returns a Decoder instance for the given resource file. If
1311 * the decoder needs to retain the file handle for reading as-needed, it
1312 * should move the UniquePtr to internal storage.
1314 * \return nullptr if a decoder can't be created from the file.
1316 virtual SharedPtr
<Decoder
> createDecoder(UniquePtr
<std::istream
> &file
) noexcept
= 0;
1320 * Registers a decoder factory for decoding audio. Registered factories are
1321 * used in lexicographical order, e.g. if Factory1 is registered with name1 and
1322 * Factory2 is registered with name2, Factory1 will be used before Factory2 if
1323 * name1 < name2. Internal decoder factories are always used after registered
1326 * Alure retains a reference to the DecoderFactory instance and will release it
1327 * (destructing the object) when the library unloads.
1329 * \param name A unique name identifying this decoder factory.
1330 * \param factory A DecoderFactory instance used to create Decoder instances.
1332 ALURE_API
void RegisterDecoder(StringView name
, UniquePtr
<DecoderFactory
> factory
);
1335 * Unregisters a decoder factory by name. Alure returns the instance back to
1338 * \param name The unique name identifying a previously-registered decoder
1341 * \return The unregistered decoder factory instance, or 0 (nullptr) if a
1342 * decoder factory with the given name doesn't exist.
1344 ALURE_API UniquePtr
<DecoderFactory
> UnregisterDecoder(StringView name
) noexcept
;
1348 * A file I/O factory interface. Applications may derive from this and set an
1349 * instance to be used by the audio decoders. By default, the library uses
1352 class ALURE_API FileIOFactory
{
1355 * Sets the factory instance to be used by the audio decoders. If a
1356 * previous factory was set, it's returned to the application. Passing in a
1357 * nullptr reverts to the default.
1359 static UniquePtr
<FileIOFactory
> set(UniquePtr
<FileIOFactory
> factory
) noexcept
;
1362 * Gets the current FileIOFactory instance being used by the audio
1365 static FileIOFactory
&get() noexcept
;
1367 virtual ~FileIOFactory();
1369 /** Opens a read-only binary file for the given name. */
1370 virtual UniquePtr
<std::istream
> openFile(const String
&name
) noexcept
= 0;
1375 * A message handler interface. Applications may derive from this and set an
1376 * instance on a context to receive messages. The base methods are no-ops, so
1377 * derived classes only need to implement methods for relevant messages.
1379 * It's recommended that applications mark their handler methods using the
1380 * override keyword, to ensure they're properly overriding the base methods in
1383 class ALURE_API MessageHandler
{
1385 virtual ~MessageHandler();
1388 * Called when the given device has been disconnected and is no longer
1389 * usable for output. As per the ALC_EXT_disconnect specification,
1390 * disconnected devices remain valid, however all playing sources are
1391 * automatically stopped, any sources that are attempted to play will
1392 * immediately stop, and new contexts may not be created on the device.
1394 * Note that connection status is checked during Context::update calls, so
1395 * that method must be called regularly to be notified when a device is
1396 * disconnected. This method may not be called if the device lacks support
1397 * for the ALC_EXT_disconnect extension.
1399 virtual void deviceDisconnected(Device device
) noexcept
;
1402 * Called when the given source reaches the end of the buffer or stream.
1404 * Sources that stopped automatically will be detected upon a call to
1407 virtual void sourceStopped(Source source
) noexcept
;
1410 * Called when the given source was forced to stop. This can be because
1411 * either there were no more mixing sources and a higher-priority source
1412 * preempted it, it's part of a SourceGroup (or sub-group thereof) that had
1413 * its SourceGroup::stopAll method called, or it was playing a buffer
1414 * that's getting removed.
1416 virtual void sourceForceStopped(Source source
) noexcept
;
1419 * Called when a new buffer is about to be created and loaded. May be
1420 * called asynchronously for buffers being loaded asynchronously.
1422 * \param name The resource name, as passed to Context::getBuffer.
1423 * \param channels Channel configuration of the given audio data.
1424 * \param type Sample type of the given audio data.
1425 * \param samplerate Sample rate of the given audio data.
1426 * \param data The audio data that is about to be fed to the OpenAL buffer.
1428 virtual void bufferLoading(StringView name
, ChannelConfig channels
, SampleType type
, ALuint samplerate
, ArrayView
<ALbyte
> data
) noexcept
;
1431 * Called when a resource isn't found, allowing the app to substitute in a
1432 * different resource. For buffers being cached, the original name will
1433 * still be used for the cache entry so the app doesn't have to keep track
1434 * of substituted resource names.
1436 * This will be called again if the new name also isn't found.
1438 * \param name The resource name that was not found.
1439 * \return The replacement resource name to use instead. Returning an empty
1440 * string means to stop trying.
1442 virtual String
resourceNotFound(StringView name
) noexcept
;
1447 } // namespace alure
1449 #endif /* AL_ALURE2_H */