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. The buffer must not be in use by a Source.
630 void removeBuffer(StringView name
);
632 * Deletes the given cached buffer. The buffer must not be in use by a
635 void removeBuffer(Buffer buffer
);
638 * Creates a new Source for playing audio. There is no practical limit to
639 * the number of sources you may create. You must call Source::release when
640 * the source is no longer needed.
642 Source
createSource();
644 AuxiliaryEffectSlot
createAuxiliaryEffectSlot();
646 Effect
createEffect();
648 SourceGroup
createSourceGroup(StringView name
);
649 SourceGroup
getSourceGroup(StringView name
);
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(ALfloat x
, ALfloat y
, ALfloat z
);
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(ALfloat x
, ALfloat y
, ALfloat z
);
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(ALfloat x1
, ALfloat y1
, ALfloat z1
, ALfloat x2
, ALfloat y2
, ALfloat z2
);
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;
772 /** Queries if the buffer is in use and can't be removed. */
773 bool isInUse() const;
777 enum class Spatialize
{
780 Auto
= 0x0002 /* AL_AUTO_SOFT */
783 class ALURE_API Source
{
784 MAKE_PIMPL(Source
, SourceImpl
)
788 * Plays the source using a buffer. The same buffer may be played from
789 * multiple sources simultaneously.
791 void play(Buffer buffer
);
793 * Plays the source by asynchronously streaming audio from a decoder. The
794 * given decoder must *NOT* have its read or seek methods called from
795 * elsewhere while in use.
797 * \param decoder The decoder object to play audio from.
798 * \param chunk_len The number of sample frames to read for each chunk
799 * update. Smaller values will require more frequent updates and
800 * larger values will handle more data with each chunk.
801 * \param queue_size The number of chunks to keep queued during playback.
802 * Smaller values use less memory while larger values improve
803 * protection against underruns.
805 void play(SharedPtr
<Decoder
> decoder
, ALuint chunk_len
, ALuint queue_size
);
808 * Prepares to play a source using a future buffer. The method will return
809 * right away and the source will begin playing once the future buffer
810 * becomes ready. If the future buffer is already ready, it begins playing
811 * immediately as if you called play(future_buffer.get()).
813 * The future buffer is checked during calls to \c Context::update and the
814 * source will start playback once the future buffer reports it's ready.
815 * Use the isPending method to check if the source is still waiting for the
818 void play(SharedFuture
<Buffer
> future_buffer
);
821 * Stops playback, releasing the buffer or decoder reference. Any pending
822 * playback from a future buffer is canceled.
827 * Fades the source to the specified gain over the given duration, at which
828 * point playback will stop. This gain is in addition to the base gain, and
829 * must be greater than 0 and less than 1. The duration must also be
832 * Pending playback from a future buffer is not immediately canceled, but
833 * the fading starts with this call. If the future buffer then becomes
834 * ready, it will start mid-fade. Pending playback will be canceled if the
835 * fade out completes before the future buffer becomes ready.
837 * Fading is updated during calls to \c Context::update, which should be
838 * called regularly (30 to 50 times per second) for the fading to be
841 void fadeOutToStop(ALfloat gain
, std::chrono::milliseconds duration
);
843 /** Pauses the source if it is playing. */
846 /** Resumes the source if it is paused. */
849 /** Specifies if the source is waiting to play a future buffer. */
850 bool isPending() const;
852 /** Specifies if the source is currently playing. */
853 bool isPlaying() const;
855 /** Specifies if the source is currently paused. */
856 bool isPaused() const;
859 * Sets this source as a child of the given source group. The given source
860 * group's parameters will influence this and all other sources that belong
861 * to it. A source can only be the child of one source group at a time,
862 * although that source group may belong to another source group.
864 * Passing in a null group removes it from its current source group.
866 void setGroup(SourceGroup group
);
868 /** Retrieves the source group this source belongs to. */
869 SourceGroup
getGroup() const;
872 * Specifies the source's playback priority. The lowest priority sources
873 * will be forcefully stopped when no more mixing sources are available and
874 * higher priority sources are played.
876 void setPriority(ALuint priority
);
877 /** Retrieves the source's priority. */
878 ALuint
getPriority() const;
881 * Sets the source's offset, in sample frames. If the source is playing or
882 * paused, it will go to that offset immediately, otherwise the source will
883 * start at the specified offset the next time it's played.
885 void setOffset(uint64_t offset
);
887 * Retrieves the source offset in sample frames and its latency in nano-
888 * seconds. For streaming sources this will be the offset based on the
889 * decoder's read position.
891 * If the AL_SOFT_source_latency extension is unsupported, the latency will
894 std::pair
<uint64_t,std::chrono::nanoseconds
> getSampleOffsetLatency() const;
895 uint64_t getSampleOffset() const { return std::get
<0>(getSampleOffsetLatency()); }
897 * Retrieves the source offset and latency in seconds. For streaming
898 * sources this will be the offset based on the decoder's read position.
900 * If the AL_SOFT_source_latency extension is unsupported, the latency will
903 std::pair
<Seconds
,Seconds
> getSecOffsetLatency() const;
904 Seconds
getSecOffset() const { return std::get
<0>(getSecOffsetLatency()); }
907 * Specifies if the source should loop on the Buffer or Decoder object's
910 void setLooping(bool looping
);
911 bool getLooping() const;
914 * Specifies a linear pitch shift base. A value of 1.0 is the default
917 void setPitch(ALfloat pitch
);
918 ALfloat
getPitch() const;
921 * Specifies the base linear gain. A value of 1.0 is the default normal
924 void setGain(ALfloat gain
);
925 ALfloat
getGain() const;
928 * Specifies the minimum and maximum gain. The source's gain is clamped to
929 * this range after distance attenuation and cone attenuation are applied
930 * to the gain base, although before the filter gain adjustements.
932 void setGainRange(ALfloat mingain
, ALfloat maxgain
);
933 std::pair
<ALfloat
,ALfloat
> getGainRange() const;
934 ALfloat
getMinGain() const { return std::get
<0>(getGainRange()); }
935 ALfloat
getMaxGain() const { return std::get
<1>(getGainRange()); }
938 * Specifies the reference distance and maximum distance the source will
939 * use for the current distance model. For Clamped distance models, the
940 * source's calculated distance is clamped to the specified range before
941 * applying distance-related attenuation.
943 * For all distance models, the reference distance is the distance at which
944 * the source's volume will not have any extra attenuation (an effective
945 * gain multiplier of 1).
947 void setDistanceRange(ALfloat refdist
, ALfloat maxdist
);
948 std::pair
<ALfloat
,ALfloat
> getDistanceRange() const;
949 ALfloat
getReferenceDistance() const { return std::get
<0>(getDistanceRange()); }
950 ALfloat
getMaxDistance() const { return std::get
<1>(getDistanceRange()); }
953 * Specifies the source's 3D position, velocity, and direction together
954 * (see: setPosition, setVelocity, and setDirection).
956 void set3DParameters(const Vector3
&position
, const Vector3
&velocity
, const Vector3
&direction
);
959 * Specifies the source's 3D position, velocity, and orientation together
960 * (see: setPosition, setVelocity, and setOrientation).
962 void set3DParameters(const Vector3
&position
, const Vector3
&velocity
, const std::pair
<Vector3
,Vector3
> &orientation
);
964 /** Specifies the source's 3D position. */
965 void setPosition(ALfloat x
, ALfloat y
, ALfloat z
);
966 void setPosition(const ALfloat
*pos
);
967 Vector3
getPosition() const;
970 * Specifies the source's 3D velocity, in units per second. As with OpenAL,
971 * this does not actually alter the source's position, and instead just
972 * alters the pitch as determined by the doppler effect.
974 void setVelocity(ALfloat x
, ALfloat y
, ALfloat z
);
975 void setVelocity(const ALfloat
*vel
);
976 Vector3
getVelocity() const;
979 * Specifies the source's 3D facing direction. Deprecated in favor of
982 void setDirection(ALfloat x
, ALfloat y
, ALfloat z
);
983 void setDirection(const ALfloat
*dir
);
984 Vector3
getDirection() const;
987 * Specifies the source's 3D orientation, using position-relative 'at' and
988 * 'up' direction vectors. Note: unlike the AL_EXT_BFORMAT extension this
989 * property comes from, this also affects the facing direction, superceding
992 void setOrientation(ALfloat x1
, ALfloat y1
, ALfloat z1
, ALfloat x2
, ALfloat y2
, ALfloat z2
);
993 void setOrientation(const ALfloat
*at
, const ALfloat
*up
);
994 void setOrientation(const ALfloat
*ori
);
995 std::pair
<Vector3
,Vector3
> getOrientation() const;
998 * Specifies the source's cone angles, in degrees. The inner angle is the
999 * area within which the listener will hear the source with no extra
1000 * attenuation, while the listener being outside of the outer angle will
1001 * hear the source attenuated according to the outer cone gains. The area
1002 * follows the facing direction, so for example an inner angle of 180 means
1003 * the entire front face of the source is in the inner cone.
1005 void setConeAngles(ALfloat inner
, ALfloat outer
);
1006 std::pair
<ALfloat
,ALfloat
> getConeAngles() const;
1007 ALfloat
getInnerConeAngle() const { return std::get
<0>(getConeAngles()); }
1008 ALfloat
getOuterConeAngle() const { return std::get
<1>(getConeAngles()); }
1011 * Specifies the linear gain multiplier when the listener is outside of the
1012 * source's outer cone area. The specified gain applies to all frequencies,
1013 * while gainhf applies extra attenuation to high frequencies creating a
1016 * \param gainhf has no effect without the ALC_EXT_EFX extension.
1018 void setOuterConeGains(ALfloat gain
, ALfloat gainhf
=1.0f
);
1019 std::pair
<ALfloat
,ALfloat
> getOuterConeGains() const;
1020 ALfloat
getOuterConeGain() const { return std::get
<0>(getOuterConeGains()); }
1021 ALfloat
getOuterConeGainHF() const { return std::get
<1>(getOuterConeGains()); }
1024 * Specifies the rolloff factors for the direct and send paths. This is
1025 * effectively a distance scaling relative to the reference distance. Note:
1026 * the room rolloff factor is 0 by default, disabling distance attenuation
1027 * for send paths. This is because the reverb engine will, by default,
1028 * apply a more realistic room decay based on the reverb decay time and
1031 void setRolloffFactors(ALfloat factor
, ALfloat roomfactor
=0.0f
);
1032 std::pair
<ALfloat
,ALfloat
> getRolloffFactors() const;
1033 ALfloat
getRolloffFactor() const { return std::get
<0>(getRolloffFactors()); }
1034 ALfloat
getRoomRolloffFactor() const { return std::get
<1>(getRolloffFactors()); }
1037 * Specifies the doppler factor for the doppler effect's pitch shift. This
1038 * effectively scales the source and listener velocities for the doppler
1041 void setDopplerFactor(ALfloat factor
);
1042 ALfloat
getDopplerFactor() const;
1045 * Specifies if the source's position, velocity, and direction/orientation
1046 * are relative to the listener.
1048 void setRelative(bool relative
);
1049 bool getRelative() const;
1052 * Specifies the source's radius. This causes the source to behave as if
1053 * every point within the spherical area emits sound.
1055 * Has no effect without the AL_EXT_SOURCE_RADIUS extension.
1057 void setRadius(ALfloat radius
);
1058 ALfloat
getRadius() const;
1061 * Specifies the left and right channel angles, in radians, when playing a
1062 * stereo buffer or stream. The angles go counter-clockwise, with 0 being
1063 * in front and positive values going left.
1065 * Has no effect without the AL_EXT_STEREO_ANGLES extension.
1067 void setStereoAngles(ALfloat leftAngle
, ALfloat rightAngle
);
1068 std::pair
<ALfloat
,ALfloat
> getStereoAngles() const;
1071 * Specifies if the source always has 3D spatialization features (On),
1072 * never has 3D spatialization features (Off), or if spatialization is
1073 * enabled based on playing a mono sound or not (Auto, default).
1075 * Has no effect without the AL_SOFT_source_spatialize extension.
1077 void set3DSpatialize(Spatialize spatialize
);
1078 Spatialize
get3DSpatialize() const;
1081 * Specifies the index of the resampler to use for this source. The index
1082 * is from the resamplers returned by \c Context::getAvailableResamplers,
1083 * and must be 0 or greater.
1085 * Has no effect without the AL_SOFT_source_resampler extension.
1087 void setResamplerIndex(ALsizei index
);
1088 ALsizei
getResamplerIndex() const;
1091 * Specifies a multiplier for the amount of atmospheric high-frequency
1092 * absorption, ranging from 0 to 10. A factor of 1 results in a nominal
1093 * -0.05dB per meter, with higher values simulating foggy air and lower
1094 * values simulating dryer air. The default is 0.
1096 void setAirAbsorptionFactor(ALfloat factor
);
1097 ALfloat
getAirAbsorptionFactor() const;
1100 * Specifies to automatically apply adjustments to the direct path's high-
1101 * frequency gain, and the send paths' gain and high-frequency gain. The
1102 * default is true for all.
1104 void setGainAuto(bool directhf
, bool send
, bool sendhf
);
1105 std::tuple
<bool,bool,bool> getGainAuto() const;
1106 bool getDirectGainHFAuto() const { return std::get
<0>(getGainAuto()); }
1107 bool getSendGainAuto() const { return std::get
<1>(getGainAuto()); }
1108 bool getSendGainHFAuto() const { return std::get
<2>(getGainAuto()); }
1110 /** Sets the filter properties on the direct path signal. */
1111 void setDirectFilter(const FilterParams
&filter
);
1113 * Sets the filter properties on the given send path signal. Any auxiliary
1114 * effect slot on the send path remains in place.
1116 void setSendFilter(ALuint send
, const FilterParams
&filter
);
1118 * Connects the effect slot to the given send path. Any filter properties
1119 * on the send path remain as they were.
1121 void setAuxiliarySend(AuxiliaryEffectSlot slot
, ALuint send
);
1123 * Connects the effect slot to the given send path, using the filter
1126 void setAuxiliarySendFilter(AuxiliaryEffectSlot slot
, ALuint send
, const FilterParams
&filter
);
1129 * Releases the source, stopping playback, releasing resources, and
1130 * returning it to the system.
1136 class ALURE_API SourceGroup
{
1137 MAKE_PIMPL(SourceGroup
, SourceGroupImpl
)
1140 /** Retrieves the associated name of the source group. */
1141 StringView
getName() const;
1144 * Adds this source group as a subgroup of the specified source group. This
1145 * method will throw an exception if this group is being added to a group
1146 * it has as a sub-group (i.e. it would create a circular sub-group chain).
1148 void setParentGroup(SourceGroup group
);
1150 /** Retrieves the source group this source group is a child of. */
1151 SourceGroup
getParentGroup() const;
1153 /** Returns the list of sources currently in the group. */
1154 Vector
<Source
> getSources() const;
1156 /** Returns the list of subgroups currently in the group. */
1157 Vector
<SourceGroup
> getSubGroups() const;
1160 * Sets the source group gain, which accumulates with its sources' and
1163 void setGain(ALfloat gain
);
1164 /** Gets the source group gain. */
1165 ALfloat
getGain() const;
1168 * Sets the source group pitch, which accumulates with its sources' and
1169 * sub-groups' pitch.
1171 void setPitch(ALfloat pitch
);
1172 /** Gets the source group pitch. */
1173 ALfloat
getPitch() const;
1176 * Pauses all currently-playing sources that are under this group,
1177 * including sub-groups.
1179 void pauseAll() const;
1181 * Resumes all paused sources that are under this group, including
1184 void resumeAll() const;
1186 /** Stops all sources that are under this group, including sub-groups. */
1187 void stopAll() const;
1190 * Releases the source group, removing all sources from it before being
1202 class ALURE_API AuxiliaryEffectSlot
{
1203 MAKE_PIMPL(AuxiliaryEffectSlot
, AuxiliaryEffectSlotImpl
)
1206 void setGain(ALfloat gain
);
1208 * If set to true, the reverb effect will automatically apply adjustments
1209 * to the source's send slot gains based on the effect properties.
1211 * Has no effect when using non-reverb effects. Default is true.
1213 void setSendAuto(bool sendauto
);
1216 * Updates the effect slot with a new effect. The given effect object may
1217 * be altered or destroyed without affecting the effect slot.
1219 void applyEffect(Effect effect
);
1222 * Releases the effect slot, returning it to the system. It must not be in
1228 * Retrieves each Source object and its pairing send this effect slot is
1229 * set on. Setting a different (or null) effect slot on each source's given
1230 * send will allow the effect slot to be released.
1232 Vector
<SourceSend
> getSourceSends() const;
1234 /** Determines if the effect slot is in use by a source. */
1235 bool isInUse() const;
1239 class ALURE_API Effect
{
1240 MAKE_PIMPL(Effect
, EffectImpl
)
1244 * Updates the effect with the specified reverb properties. If the
1245 * EAXReverb effect is not supported, it will automatically attempt to
1246 * downgrade to the Standard Reverb effect.
1248 void setReverbProperties(const EFXEAXREVERBPROPERTIES
&props
);
1255 * Audio decoder interface. Applications may derive from this, implementing the
1256 * necessary methods, and use it in places the API wants a Decoder object.
1258 class ALURE_API Decoder
{
1262 /** Retrieves the sample frequency, in hz, of the audio being decoded. */
1263 virtual ALuint
getFrequency() const = 0;
1264 /** Retrieves the channel configuration of the audio being decoded. */
1265 virtual ChannelConfig
getChannelConfig() const = 0;
1266 /** Retrieves the sample type of the audio being decoded. */
1267 virtual SampleType
getSampleType() const = 0;
1270 * Retrieves the total length of the audio, in sample frames. If unknown,
1271 * returns 0. Note that if the returned length is 0, the decoder may not be
1272 * used to load a Buffer.
1274 virtual uint64_t getLength() const = 0;
1276 * Seek to pos, specified in sample frames. Returns true if the seek was
1279 virtual bool seek(uint64_t pos
) = 0;
1282 * Retrieves the loop points, in sample frames, as a [start,end) pair. If
1283 * start >= end, all available samples are included in the loop.
1285 virtual std::pair
<uint64_t,uint64_t> getLoopPoints() const = 0;
1288 * Decodes count sample frames, writing them to ptr, and returns the number
1289 * of sample frames written. Returning less than the requested count
1290 * indicates the end of the audio.
1292 virtual ALuint
read(ALvoid
*ptr
, ALuint count
) = 0;
1296 * Audio decoder factory interface. Applications may derive from this,
1297 * implementing the necessary methods, and use it in places the API wants a
1298 * DecoderFactory object.
1300 class ALURE_API DecoderFactory
{
1302 virtual ~DecoderFactory();
1305 * Creates and returns a Decoder instance for the given resource file. If
1306 * the decoder needs to retain the file handle for reading as-needed, it
1307 * should move the UniquePtr to internal storage.
1309 * \return nullptr if a decoder can't be created from the file.
1311 virtual SharedPtr
<Decoder
> createDecoder(UniquePtr
<std::istream
> &file
) = 0;
1315 * Registers a decoder factory for decoding audio. Registered factories are
1316 * used in lexicographical order, e.g. if Factory1 is registered with name1 and
1317 * Factory2 is registered with name2, Factory1 will be used before Factory2 if
1318 * name1 < name2. Internal decoder factories are always used after registered
1321 * Alure retains a reference to the DecoderFactory instance and will release it
1322 * (destructing the object) when the library unloads.
1324 * \param name A unique name identifying this decoder factory.
1325 * \param factory A DecoderFactory instance used to create Decoder instances.
1327 ALURE_API
void RegisterDecoder(StringView name
, UniquePtr
<DecoderFactory
> factory
);
1330 * Unregisters a decoder factory by name. Alure returns the instance back to
1333 * \param name The unique name identifying a previously-registered decoder
1336 * \return The unregistered decoder factory instance, or 0 (nullptr) if a
1337 * decoder factory with the given name doesn't exist.
1339 ALURE_API UniquePtr
<DecoderFactory
> UnregisterDecoder(StringView name
);
1343 * A file I/O factory interface. Applications may derive from this and set an
1344 * instance to be used by the audio decoders. By default, the library uses
1347 class ALURE_API FileIOFactory
{
1350 * Sets the factory instance to be used by the audio decoders. If a
1351 * previous factory was set, it's returned to the application. Passing in a
1352 * nullptr reverts to the default.
1354 static UniquePtr
<FileIOFactory
> set(UniquePtr
<FileIOFactory
> factory
);
1357 * Gets the current FileIOFactory instance being used by the audio
1360 static FileIOFactory
&get();
1362 virtual ~FileIOFactory();
1364 /** Opens a read-only binary file for the given name. */
1365 virtual UniquePtr
<std::istream
> openFile(const String
&name
) = 0;
1370 * A message handler interface. Applications may derive from this and set an
1371 * instance on a context to receive messages. The base methods are no-ops, so
1372 * derived classes only need to implement methods for relevant messages.
1374 * It's recommended that applications mark their handler methods using the
1375 * override keyword, to ensure they're properly overriding the base methods in
1378 class ALURE_API MessageHandler
{
1380 virtual ~MessageHandler();
1383 * Called when the given device has been disconnected and is no longer
1384 * usable for output. As per the ALC_EXT_disconnect specification,
1385 * disconnected devices remain valid, however all playing sources are
1386 * automatically stopped, any sources that are attempted to play will
1387 * immediately stop, and new contexts may not be created on the device.
1389 * Note that connection status is checked during Context::update calls, so
1390 * that method must be called regularly to be notified when a device is
1391 * disconnected. This method may not be called if the device lacks support
1392 * for the ALC_EXT_disconnect extension.
1394 virtual void deviceDisconnected(Device device
);
1397 * Called when the given source reaches the end of the buffer or stream.
1399 * Sources that stopped automatically will be detected upon a call to
1402 virtual void sourceStopped(Source source
);
1405 * Called when the given source was forced to stop. This can be because
1406 * either there were no more mixing sources and a higher-priority source
1407 * preempted it, or it's part of a SourceGroup (or sub-group thereof) that
1408 * had its SourceGroup::stopAll method called.
1410 virtual void sourceForceStopped(Source source
);
1413 * Called when a new buffer is about to be created and loaded. May be
1414 * called asynchronously for buffers being loaded asynchronously.
1416 * \param name The resource name, as passed to Context::getBuffer.
1417 * \param channels Channel configuration of the given audio data.
1418 * \param type Sample type of the given audio data.
1419 * \param samplerate Sample rate of the given audio data.
1420 * \param data The audio data that is about to be fed to the OpenAL buffer.
1422 virtual void bufferLoading(StringView name
, ChannelConfig channels
, SampleType type
, ALuint samplerate
, ArrayView
<ALbyte
> data
);
1425 * Called when a resource isn't found, allowing the app to substitute in a
1426 * different resource. For buffers being cached, the original name will
1427 * still be used for the cache entry so the app doesn't have to keep track
1428 * of substituted resource names.
1430 * This will be called again if the new name also isn't found.
1432 * \param name The resource name that was not found.
1433 * \return The replacement resource name to use instead. Returning an empty
1434 * string means to stop trying.
1436 virtual String
resourceNotFound(StringView name
);
1441 } // namespace alure
1443 #endif /* AL_ALURE2_H */