18 #if defined(ALURE_STATIC_LIB)
21 #define ALURE_API __declspec(dllimport)
22 #elif defined(__GNUC__) || (defined(__has_attribute) && __has_attribute(visibility))
23 #define ALURE_API __attribute__((visibility("default")))
27 #endif /* ALURE_API */
29 #ifndef EFXEAXREVERBPROPERTIES_DEFINED
30 #define EFXEAXREVERBPROPERTIES_DEFINED
40 float flReflectionsGain
;
41 float flReflectionsDelay
;
42 float flReflectionsPan
[3];
43 float flLateReverbGain
;
44 float flLateReverbDelay
;
45 float flLateReverbPan
[3];
48 float flModulationTime
;
49 float flModulationDepth
;
50 float flAirAbsorptionGainHF
;
53 float flRoomRolloffFactor
;
55 } EFXEAXREVERBPROPERTIES
, *LPEFXEAXREVERBPROPERTIES
;
61 class DeviceManagerImpl
;
73 class SourceGroupImpl
;
74 class AuxiliaryEffectSlot
;
75 class AuxiliaryEffectSlotImpl
;
84 using RemoveRefT
= typename
std::remove_reference
<T
>::type
;
86 using EnableIfT
= typename
std::enable_if
<B
>::type
;
89 // Duration in seconds, using double precision
90 using Seconds
= std::chrono::duration
<double>;
92 // A SharedPtr implementation, defaults to C++11's std::shared_ptr. If this is
93 // changed, you must recompile the library.
95 using SharedPtr
= std::shared_ptr
<T
>;
96 template<typename T
, typename
... Args
>
97 constexpr inline SharedPtr
<T
> MakeShared(Args
&&... args
)
99 return std::make_shared
<T
>(std::forward
<Args
>(args
)...);
102 // A UniquePtr implementation, defaults to C++11's std::unique_ptr. If this is
103 // changed, you must recompile the library.
104 template<typename T
, typename D
= std::default_delete
<T
>>
105 using UniquePtr
= std::unique_ptr
<T
, D
>;
106 template<typename T
, typename
... Args
>
107 constexpr inline UniquePtr
<T
> MakeUnique(Args
&&... args
)
109 #if __cplusplus >= 201402L
110 return std::make_unique
<T
>(std::forward
<Args
>(args
)...);
112 return std::unique_ptr
<T
>(new T(std::forward
<Args
>(args
)...));
116 // A Promise/Future (+SharedFuture) implementation, defaults to C++11's
117 // std::promise, std::future, and std::shared_future. If this is changed, you
118 // must recompile the library.
120 using Promise
= std::promise
<T
>;
122 using Future
= std::future
<T
>;
124 using SharedFuture
= std::shared_future
<T
>;
126 // A Vector implementation, defaults to C++'s std::vector. If this is changed,
127 // you must recompile the library.
129 using Vector
= std::vector
<T
>;
131 // A static-sized Array implementation, defaults to C++11's std::array. If this
132 // is changed, you must recompile the library.
133 template<typename T
, std::size_t N
>
134 using Array
= std::array
<T
, N
>;
136 // A String implementation, default's to C++'s std::string. If this is changed,
137 // you must recompile the library.
139 using BasicString
= std::basic_string
<T
>;
140 using String
= BasicString
<std::string::value_type
>;
142 // Tag specific containers that guarantee contiguous storage. The standard
143 // provides no such mechanism, so we have to manually specify which are
146 struct IsContiguousTag
: std::false_type
{};
147 template<typename T
, size_t N
>
148 struct IsContiguousTag
<Array
<T
,N
>> : std::true_type
{};
150 struct IsContiguousTag
<Vector
<T
>> : std::true_type
{};
152 struct IsContiguousTag
<BasicString
<T
>> : std::true_type
{};
154 // A rather simple ArrayView container. This allows accepting various array
155 // types (Array, Vector, a static-sized array, a dynamic array + size) without
156 // copying its elements.
160 using value_type
= T
;
161 using iterator
= const value_type
*;
162 using const_iterator
= const value_type
*;
165 const value_type
*mElems
;
169 ArrayView() noexcept
: mElems(nullptr), mNumElems(0) { }
170 ArrayView(const ArrayView
&) noexcept
= default;
171 ArrayView(ArrayView
&&) noexcept
= default;
172 ArrayView(const value_type
*elems
, size_t num_elems
) noexcept
173 : mElems(elems
), mNumElems(num_elems
) { }
174 template<typename OtherT
> ArrayView(RemoveRefT
<OtherT
>&&) = delete;
175 template<typename OtherT
,
176 typename
= EnableIfT
<IsContiguousTag
<RemoveRefT
<OtherT
>>::value
>>
177 ArrayView(const OtherT
&rhs
) noexcept
: mElems(rhs
.data()), mNumElems(rhs
.size()) { }
179 ArrayView(const value_type (&elems
)[N
]) noexcept
: mElems(elems
), mNumElems(N
) { }
181 ArrayView
& operator=(const ArrayView
&) noexcept
= default;
183 const value_type
*data() const noexcept
{ return mElems
; }
185 size_t size() const noexcept
{ return mNumElems
; }
186 bool empty() const noexcept
{ return mNumElems
== 0; }
188 const value_type
& operator[](size_t i
) const { return mElems
[i
]; }
190 const value_type
& front() const { return mElems
[0]; }
191 const value_type
& back() const { return mElems
[mNumElems
-1]; }
193 const value_type
& at(size_t i
) const
196 throw std::out_of_range("alure::ArrayView::at: element out of range");
200 const_iterator
begin() const noexcept
{ return mElems
; }
201 const_iterator
cbegin() const noexcept
{ return mElems
; }
203 const_iterator
end() const noexcept
{ return mElems
+ mNumElems
; }
204 const_iterator
cend() const noexcept
{ return mElems
+ mNumElems
; }
208 class BasicStringView
: public ArrayView
<T
> {
209 using BaseT
= ArrayView
<T
>;
210 using StringT
= BasicString
<T
>;
213 using typename
BaseT::value_type
;
215 BasicStringView() noexcept
= default;
216 BasicStringView(const BasicStringView
&) noexcept
= default;
217 BasicStringView(const value_type
*elems
, size_t num_elems
) noexcept
218 : ArrayView
<T
>(elems
, num_elems
) { }
219 BasicStringView(const value_type
*elems
) : ArrayView
<T
>(elems
, std::strlen(elems
)) { }
220 BasicStringView(StringT
&&) = delete;
221 BasicStringView(const StringT
&rhs
) noexcept
: ArrayView
<T
>(rhs
) { }
222 #if __cplusplus >= 201703L
223 BasicStringView(const std::basic_string_view
<T
> &rhs
) noexcept
224 : ArrayView
<T
>(rhs
.data(), rhs
.length()) { }
227 BasicStringView
& operator=(const BasicStringView
&) noexcept
= default;
229 size_t length() const { return BaseT::size(); }
231 explicit operator StringT() const { return StringT(BaseT::data(), length()); }
232 #if __cplusplus >= 201703L
233 operator std::basic_string_view
<T
>() const
234 { return std::basic_string_view
<T
>(BaseT::data(), length()); }
237 StringT
operator+(const StringT
&rhs
) const
239 StringT ret
= StringT(*this);
243 StringT
operator+(const typename
StringT::value_type
*rhs
) const
245 StringT ret
= StringT(*this);
250 using StringView
= BasicStringView
<String::value_type
>;
252 // Inline operators to concat String and C-style strings with StringViews.
254 inline BasicString
<T
> operator+(const BasicString
<T
> &lhs
, const BasicStringView
<T
> &rhs
)
255 { return BasicString
<T
>(lhs
).append(rhs
.data(), rhs
.size()); }
257 inline BasicString
<T
> operator+(BasicString
<T
>&& lhs
, const BasicStringView
<T
> &rhs
)
258 { return std::move(lhs
.append(rhs
.data(), rhs
.size())); }
260 inline BasicString
<T
> operator+(const typename BasicString
<T
>::value_type
*lhs
, const BasicStringView
<T
> &rhs
)
261 { return lhs
+ BasicString
<T
>(rhs
); }
263 inline BasicString
<T
>& operator+=(BasicString
<T
> &lhs
, const BasicStringView
<T
> &rhs
)
264 { return lhs
.append(rhs
.data(), rhs
.size()); }
265 // Inline operator to write out a StringView to an ostream
267 inline std::basic_ostream
<T
>& operator<<(std::basic_ostream
<T
> &lhs
, const BasicStringView
<T
> &rhs
)
276 * An attribute pair, for passing attributes to Device::createContext and
279 using AttributePair
= std::pair
<ALCint
,ALCint
>;
280 static_assert(sizeof(AttributePair
) == sizeof(ALCint
[2]), "Bad AttributePair size");
283 struct FilterParams
{
285 ALfloat mGainHF
; // For low-pass and band-pass filters
286 ALfloat mGainLF
; // For high-pass and band-pass filters
291 Array
<ALfloat
,3> mValue
;
294 constexpr Vector3() noexcept
295 : mValue
{{0.0f
, 0.0f
, 0.0f
}}
297 constexpr Vector3(const Vector3
&rhs
) noexcept
298 : mValue
{{rhs
.mValue
[0], rhs
.mValue
[1], rhs
.mValue
[2]}}
300 constexpr Vector3(ALfloat val
) noexcept
301 : mValue
{{val
, val
, val
}}
303 constexpr Vector3(ALfloat x
, ALfloat y
, ALfloat z
) noexcept
306 Vector3(const ALfloat
*vec
) noexcept
307 : mValue
{{vec
[0], vec
[1], vec
[2]}}
310 const ALfloat
*getPtr() const noexcept
311 { return mValue
.data(); }
313 ALfloat
& operator[](size_t i
) noexcept
314 { return mValue
[i
]; }
315 constexpr const ALfloat
& operator[](size_t i
) const noexcept
316 { return mValue
[i
]; }
318 #define ALURE_DECL_OP(op) \
319 constexpr Vector3 operator op(const Vector3 &rhs) const noexcept \
321 return Vector3(mValue[0] op rhs.mValue[0], \
322 mValue[1] op rhs.mValue[1], \
323 mValue[2] op rhs.mValue[2]); \
330 #define ALURE_DECL_OP(op) \
331 Vector3& operator op(const Vector3 &rhs) noexcept \
333 mValue[0] op rhs.mValue[0]; \
334 mValue[1] op rhs.mValue[1]; \
335 mValue[2] op rhs.mValue[2]; \
344 #define ALURE_DECL_OP(op) \
345 constexpr Vector3 operator op(ALfloat scale) const noexcept \
347 return Vector3(mValue[0] op scale, \
348 mValue[1] op scale, \
349 mValue[2] op scale); \
354 #define ALURE_DECL_OP(op) \
355 Vector3& operator op(ALfloat scale) noexcept \
357 mValue[0] op scale; \
358 mValue[1] op scale; \
359 mValue[2] op scale; \
366 constexpr ALfloat
getLengthSquared() const noexcept
367 { return mValue
[0]*mValue
[0] + mValue
[1]*mValue
[1] + mValue
[2]*mValue
[2]; }
368 ALfloat
getLength() const noexcept
369 { return std::sqrt(getLengthSquared()); }
371 constexpr ALfloat
getDistanceSquared(const Vector3
&pos
) const noexcept
372 { return (pos
- *this).getLengthSquared(); }
373 ALfloat
getDistance(const Vector3
&pos
) const noexcept
374 { return (pos
- *this).getLength(); }
376 static_assert(sizeof(Vector3
) == sizeof(ALfloat
[3]), "Bad Vector3 size");
379 enum class SampleType
{
385 ALURE_API
const char *GetSampleTypeName(SampleType type
);
387 enum class ChannelConfig
{
388 /** 1-channel mono sound. */
390 /** 2-channel stereo sound. */
392 /** 2-channel rear sound (back-left and back-right). */
394 /** 4-channel surround sound. */
396 /** 5.1 surround sound. */
398 /** 6.1 surround sound. */
400 /** 7.1 surround sound. */
402 /** 3-channel B-Format, using FuMa channel ordering and scaling. */
404 /** 4-channel B-Format, using FuMa channel ordering and scaling. */
407 ALURE_API
const char *GetChannelConfigName(ChannelConfig cfg
);
409 ALURE_API ALuint
FramesToBytes(ALuint frames
, ChannelConfig chans
, SampleType type
);
410 ALURE_API ALuint
BytesToFrames(ALuint bytes
, ChannelConfig chans
, SampleType type
);
413 /** Class for storing a major.minor version number. */
419 constexpr Version(ALuint _maj
, ALuint _min
) : mMajor(_maj
), mMinor(_min
) { }
421 constexpr ALuint
getMajor() const noexcept
{ return mMajor
; }
422 constexpr ALuint
getMinor() const noexcept
{ return mMinor
; }
423 constexpr bool isZero() const noexcept
{ return mMajor
== 0 && mMinor
== 0; }
426 #define MAKE_PIMPL(BaseT, ImplT) \
431 using handle_type = ImplT*; \
433 BaseT() : pImpl(nullptr) { } \
434 BaseT(ImplT *impl) : pImpl(impl) { } \
435 BaseT(const BaseT&) = default; \
436 BaseT(BaseT&& rhs) : pImpl(rhs.pImpl) { rhs.pImpl = nullptr; } \
438 BaseT& operator=(const BaseT&) = default; \
439 BaseT& operator=(BaseT&& rhs) \
441 pImpl = rhs.pImpl; rhs.pImpl = nullptr; \
445 bool operator==(const BaseT &rhs) const { return pImpl == rhs.pImpl; } \
446 bool operator==(BaseT&& rhs) const { return pImpl == rhs.pImpl; } \
448 operator bool() const { return !!pImpl; } \
450 handle_type getHandle() const { return pImpl; }
452 enum class DeviceEnumeration
{
453 Basic
= ALC_DEVICE_SPECIFIER
,
454 Full
= ALC_ALL_DEVICES_SPECIFIER
,
455 Capture
= ALC_CAPTURE_DEVICE_SPECIFIER
458 enum class DefaultDeviceType
{
459 Basic
= ALC_DEFAULT_DEVICE_SPECIFIER
,
460 Full
= ALC_DEFAULT_ALL_DEVICES_SPECIFIER
,
461 Capture
= ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER
465 * A class managing Device objects and other related functionality. This class
466 * is a singleton, only one instance will exist in a process.
468 class ALURE_API DeviceManager
{
469 DeviceManagerImpl
*pImpl
;
471 DeviceManager(DeviceManagerImpl
*impl
) : pImpl(impl
) { }
472 friend class ALDeviceManager
;
475 DeviceManager(const DeviceManager
&) = default;
476 DeviceManager(DeviceManager
&& rhs
) : pImpl(rhs
.pImpl
) { }
478 /** Retrieves the DeviceManager instance. */
479 static DeviceManager
get();
481 /** Queries the existence of a non-device-specific ALC extension. */
482 bool queryExtension(StringView name
) const;
483 bool queryExtension(const char *name
) const;
485 /** Enumerates available device names of the given type. */
486 Vector
<String
> enumerate(DeviceEnumeration type
) const;
487 /** Retrieves the default device of the given type. */
488 String
defaultDeviceName(DefaultDeviceType type
) const;
491 * Opens the playback device given by name, or the default if blank. Throws
492 * an exception on error.
494 Device
openPlayback(StringView name
=StringView());
495 Device
openPlayback(const char *name
);
498 * Opens the playback device given by name, or the default if blank.
499 * Returns an empty Device on error.
501 Device
openPlayback(StringView name
, const std::nothrow_t
&);
502 Device
openPlayback(const char *name
, const std::nothrow_t
&);
504 /** Opens the default playback device. Returns an empty Device on error. */
505 Device
openPlayback(const std::nothrow_t
&);
509 enum class PlaybackName
{
510 Basic
= ALC_DEVICE_SPECIFIER
,
511 Full
= ALC_ALL_DEVICES_SPECIFIER
514 class ALURE_API Device
{
515 MAKE_PIMPL(Device
, DeviceImpl
)
518 /** Retrieves the device name as given by type. */
519 String
getName(PlaybackName type
=PlaybackName::Full
) const;
520 /** Queries the existence of an ALC extension on this device. */
521 bool queryExtension(StringView name
) const;
522 bool queryExtension(const char *name
) const;
524 /** Retrieves the ALC version supported by this device. */
525 Version
getALCVersion() const;
528 * Retrieves the EFX version supported by this device. If the ALC_EXT_EFX
529 * extension is unsupported, this will be 0.0.
531 Version
getEFXVersion() const;
533 /** Retrieves the device's playback frequency, in hz. */
534 ALCuint
getFrequency() const;
537 * Retrieves the maximum number of auxiliary source sends. If ALC_EXT_EFX
538 * is unsupported, this will be 0.
540 ALCuint
getMaxAuxiliarySends() const;
543 * Enumerates available HRTF names. The names are sorted as OpenAL gives
544 * them, such that the index of a given name is the ID to use with
547 * Requires the ALC_SOFT_HRTF extension.
549 Vector
<String
> enumerateHRTFNames() const;
552 * Retrieves whether HRTF is enabled on the device or not.
554 * Requires the ALC_SOFT_HRTF extension.
556 bool isHRTFEnabled() const;
559 * Retrieves the name of the HRTF currently being used by this device.
561 * Requires the ALC_SOFT_HRTF extension.
563 String
getCurrentHRTF() const;
566 * Resets the device, using the specified attributes.
568 * Requires the ALC_SOFT_HRTF extension.
570 void reset(ArrayView
<AttributePair
> attributes
);
573 * Creates a new Context on this device, using the specified attributes.
575 Context
createContext(ArrayView
<AttributePair
> attributes
=ArrayView
<AttributePair
>());
578 * Pauses device processing, stopping updates for its contexts. Multiple
579 * calls are allowed but it is not reference counted, so the device will
580 * resume after one resumeDSP call.
582 * Requires the ALC_SOFT_pause_device extension.
587 * Resumes device processing, restarting updates for its contexts. Multiple
588 * calls are allowed and will no-op.
593 * Closes and frees the device. All previously-created contexts must first
600 enum class DistanceModel
{
601 InverseClamped
= AL_INVERSE_DISTANCE_CLAMPED
,
602 LinearClamped
= AL_LINEAR_DISTANCE_CLAMPED
,
603 ExponentClamped
= AL_EXPONENT_DISTANCE_CLAMPED
,
604 Inverse
= AL_INVERSE_DISTANCE
,
605 Linear
= AL_LINEAR_DISTANCE
,
606 Exponent
= AL_EXPONENT_DISTANCE
,
610 class ALURE_API Context
{
611 MAKE_PIMPL(Context
, ContextImpl
)
614 /** Makes the specified context current for OpenAL operations. */
615 static void MakeCurrent(Context context
);
616 /** Retrieves the current context used for OpenAL operations. */
617 static Context
GetCurrent();
620 * Makes the specified context current for OpenAL operations on the calling
621 * thread only. Requires the ALC_EXT_thread_local_context extension on both
622 * the context's device and the DeviceManager.
624 static void MakeThreadCurrent(Context context
);
625 /** Retrieves the thread-specific context used for OpenAL operations. */
626 static Context
GetThreadCurrent();
629 * Destroys the context. The context must not be current when this is
634 /** Retrieves the Device this context was created from. */
641 * Retrieves a Listener instance for this context. Each context will only
642 * have one listener, which is automatically destroyed with the context.
644 Listener
getListener();
647 * Sets a MessageHandler instance which will be used to provide certain
648 * messages back to the application. Only one handler may be set for a
649 * context at a time. The previously set handler will be returned.
651 SharedPtr
<MessageHandler
> setMessageHandler(SharedPtr
<MessageHandler
> handler
);
653 /** Gets the currently-set message handler. */
654 SharedPtr
<MessageHandler
> getMessageHandler() const;
657 * Specifies the desired interval that the background thread will be woken
658 * up to process tasks, e.g. keeping streaming sources filled. An interval
659 * of 0 means the background thread will only be woken up manually with
660 * calls to update. The default is 0.
662 void setAsyncWakeInterval(std::chrono::milliseconds interval
);
665 * Retrieves the current interval used for waking up the background thread.
667 std::chrono::milliseconds
getAsyncWakeInterval() const;
669 // Functions below require the context to be current
672 * Creates a Decoder instance for the given audio file or resource name.
674 SharedPtr
<Decoder
> createDecoder(const String
&name
);
677 * Queries if the channel configuration and sample type are supported by
680 bool isSupported(ChannelConfig channels
, SampleType type
) const;
683 * Queries the list of resamplers supported by the context. If the
684 * AL_SOFT_source_resampler extension is unsupported this will be an empty
685 * array, otherwise there will be at least one entry.
687 ArrayView
<String
> getAvailableResamplers();
689 * Queries the context's default resampler index. Be aware, if the
690 * AL_SOFT_source_resampler extension is unsupported the resampler list
691 * will be empty and this will resturn 0. If you try to access the
692 * resampler list with this index without the extension, undefined behavior
693 * will occur (accessing an out of bounds array index).
695 ALsizei
getDefaultResamplerIndex() const;
698 * Creates and caches a Buffer for the given audio file or resource name.
699 * Multiple calls with the same name will return the same Buffer object.
700 * Cached buffers must be freed using removeBuffer before destroying the
701 * context. If the buffer can't be loaded it will throw an exception.
703 Buffer
getBuffer(const String
&name
);
706 * Asynchronously prepares a cached Buffer for the given audio file or
707 * resource name. Multiple calls with the same name will return multiple
708 * SharedFutures for the same Buffer object. Once called, the buffer must
709 * be freed using removeBuffer before destroying the context, even if you
710 * never get the Buffer from the SharedFuture.
712 * The Buffer will be scheduled to load asynchronously, and the caller gets
713 * back a SharedFuture that can be checked later (or waited on) to get the
714 * actual Buffer when it's ready. The application must take care to handle
715 * exceptions from the SharedFuture in case an unrecoverable error ocurred
718 SharedFuture
<Buffer
> getBufferAsync(const String
&name
);
721 * Asynchronously prepares cached Buffers for the given audio file or
722 * resource names. Duplicate names and buffers already cached are ignored.
723 * Cached buffers must be freed using removeBuffer before destroying the
726 * The Buffer objects will be scheduled for loading asynchronously, and
727 * should be retrieved later when needed using getBufferAsync or getBuffer.
728 * Buffers that cannot be loaded, for example due to an unsupported format,
729 * will be ignored and a later call to getBuffer or getBufferAsync will
730 * throw an exception.
732 * Note that you should avoid trying to asynchronously cache more than 16
733 * buffers at a time. The internal ringbuffer used to communicate with the
734 * background thread can only hold 16 async load requests, and trying to
735 * add more will cause the call to stall until the background thread
736 * completes some loads for more to be filled in.
738 void precacheBuffersAsync(ArrayView
<String
> names
);
741 * Creates and caches a Buffer using the given name. The name may alias an
742 * audio file, but it must not currently exist in the buffer cache.
744 Buffer
createBufferFrom(const String
&name
, SharedPtr
<Decoder
> decoder
);
747 * Asynchronously prepares a cached Buffer using the given name. The name
748 * may alias an audio file, but it must not currently exist in the buffer
749 * cache. Once called, the buffer must be freed using removeBuffer before
750 * destroying the context, even if you never get the Buffer from the
753 * The Buffer will be scheduled to load asynchronously, and the caller gets
754 * back a SharedFuture that can be checked later (or waited on) to get the
755 * actual Buffer when it's ready. The application must take care to handle
756 * exceptions from the SharedFuture in case an unrecoverable error ocurred
757 * during the load. The decoder must not have its read or seek methods
758 * called while the buffer is not ready.
760 SharedFuture
<Buffer
> createBufferAsyncFrom(const String
&name
, SharedPtr
<Decoder
> decoder
);
763 * Deletes the cached Buffer object for the given audio file or resource
764 * name. The buffer must not be in use by a Source.
766 void removeBuffer(const String
&name
);
768 * Deletes the given cached buffer. The buffer must not be in use by a
771 void removeBuffer(Buffer buffer
);
774 * Creates a new Source. There is no practical limit to the number of
775 * sources you may create. You must call Source::release when the source is
778 Source
createSource();
780 AuxiliaryEffectSlot
createAuxiliaryEffectSlot();
782 Effect
createEffect();
784 SourceGroup
createSourceGroup(String name
);
785 SourceGroup
getSourceGroup(const String
&name
);
787 /** Sets the doppler factor to apply to all source calculations. */
788 void setDopplerFactor(ALfloat factor
);
791 * Sets the speed of sound propagation, in units per second, to calculate
792 * the doppler effect along with other distance-related time effects. The
793 * default is 343.3 units per second (a realistic speed assuming 1 meter
794 * per unit). If this is adjusted for a different unit scale,
795 * Listener::setMetersPerUnit should also be adjusted.
797 void setSpeedOfSound(ALfloat speed
);
799 void setDistanceModel(DistanceModel model
);
801 /** Updates the context and all sources belonging to this context. */
805 class ALURE_API Listener
{
806 MAKE_PIMPL(Listener
, ListenerImpl
)
809 /** Sets the "master" gain for all context output. */
810 void setGain(ALfloat gain
);
813 * Specifies the listener's 3D position, velocity, and orientation
816 void set3DParameters(const Vector3
&position
, const Vector3
&velocity
, std::pair
<Vector3
,Vector3
> orientation
);
818 /** Specifies the listener's 3D position. */
819 void setPosition(ALfloat x
, ALfloat y
, ALfloat z
);
820 void setPosition(const ALfloat
*pos
);
823 * Specifies the listener's 3D velocity, in units per second. As with
824 * OpenAL, this does not actually alter the listener's position, and
825 * instead just alters the pitch as determined by the doppler effect.
827 void setVelocity(ALfloat x
, ALfloat y
, ALfloat z
);
828 void setVelocity(const ALfloat
*vel
);
831 * Specifies the listener's 3D orientation, using position-relative 'at'
832 * and 'up' direction vectors.
834 void setOrientation(ALfloat x1
, ALfloat y1
, ALfloat z1
, ALfloat x2
, ALfloat y2
, ALfloat z2
);
835 void setOrientation(const ALfloat
*at
, const ALfloat
*up
);
836 void setOrientation(const ALfloat
*ori
);
839 * Sets the number of meters per unit, used for various effects that rely
840 * on the distance in meters (including air absorption and initial reverb
841 * decay). If this is changed, it's strongly recommended to also set the
842 * speed of sound (e.g. context.setSpeedOfSound(343.3 / m_u) to maintain a
843 * realistic 343.3m/s for sound propagation).
845 void setMetersPerUnit(ALfloat m_u
);
849 class ALURE_API Buffer
{
850 MAKE_PIMPL(Buffer
, BufferImpl
)
853 /** Retrieves the length of the buffer in sample frames. */
854 ALuint
getLength() const;
856 /** Retrieves the buffer's frequency in hz. */
857 ALuint
getFrequency() const;
859 /** Retrieves the buffer's sample configuration. */
860 ChannelConfig
getChannelConfig() const;
862 /** Retrieves the buffer's sample type. */
863 SampleType
getSampleType() const;
865 /** Retrieves the storage size used by the buffer, in bytes. */
866 ALuint
getSize() const;
869 * Sets the buffer's loop points, used for looping sources. If the current
870 * context does not support the AL_SOFT_loop_points extension, start and
871 * end must be 0 and getLength() respectively. Otherwise, start must be
872 * less than end, and end must be less than or equal to getLength().
874 * The buffer must not be in use when this method is called.
876 * \param start The starting point, in sample frames (inclusive).
877 * \param end The ending point, in sample frames (exclusive).
879 void setLoopPoints(ALuint start
, ALuint end
);
881 /** Retrieves the current loop points as a [start,end) pair. */
882 std::pair
<ALuint
,ALuint
> getLoopPoints() const;
885 * Retrieves the Source objects currently playing the buffer. Stopping the
886 * returned sources will allow the buffer to be removed from the context.
888 Vector
<Source
> getSources() const;
890 /** Retrieves the name the buffer was created with. */
891 const String
&getName() const;
893 /** Queries if the buffer is in use and can't be removed. */
894 bool isInUse() const;
898 enum class Spatialize
{
901 Auto
= 0x0002 /* AL_AUTO_SOFT */
904 class ALURE_API Source
{
905 MAKE_PIMPL(Source
, SourceImpl
)
909 * Plays the source using buffer. The same buffer may be played from
910 * multiple sources simultaneously.
912 void play(Buffer buffer
);
914 * Plays the source by streaming audio from decoder. This will use
915 * queuesize buffers, each with updatelen sample frames. The given decoder
916 * must *NOT* have its read or seek methods called from elsewhere while in
919 void play(SharedPtr
<Decoder
> decoder
, ALuint updatelen
, ALuint queuesize
);
921 * Stops playback, releasing the buffer or decoder reference.
925 /** Pauses the source if it is playing. */
928 /** Resumes the source if it is paused. */
931 /** Specifies if the source is currently playing. */
932 bool isPlaying() const;
934 /** Specifies if the source is currently paused. */
935 bool isPaused() const;
938 * Specifies the source's playback priority. Lowest priority sources will
939 * be evicted first when higher priority sources are played.
941 void setPriority(ALuint priority
);
942 /** Retrieves the source's priority. */
943 ALuint
getPriority() const;
946 * Sets the source's offset, in sample frames. If the source is playing or
947 * paused, it will go to that offset immediately, otherwise the source will
948 * start at the specified offset the next time it's played.
950 void setOffset(uint64_t offset
);
952 * Retrieves the source offset in sample frames and its latency in nano-
953 * seconds. For streaming sources this will be the offset based on the
954 * decoder's read position.
956 * If the AL_SOFT_source_latency extension is unsupported, the latency will
959 std::pair
<uint64_t,std::chrono::nanoseconds
> getSampleOffsetLatency() const;
960 uint64_t getSampleOffset() const { return std::get
<0>(getSampleOffsetLatency()); }
962 * Retrieves the source offset and latency in seconds. For streaming
963 * sources this will be the offset based on the decoder's read position.
965 * If the AL_SOFT_source_latency extension is unsupported, the latency will
968 std::pair
<Seconds
,Seconds
> getSecOffsetLatency() const;
969 Seconds
getSecOffset() const { return std::get
<0>(getSecOffsetLatency()); }
972 * Specifies if the source should loop on the Buffer or Decoder object's
975 void setLooping(bool looping
);
976 bool getLooping() const;
979 * Specifies a linear pitch shift base. A value of 1.0 is the default
982 void setPitch(ALfloat pitch
);
983 ALfloat
getPitch() const;
986 * Specifies the base linear gain. A value of 1.0 is the default normal
989 void setGain(ALfloat gain
);
990 ALfloat
getGain() const;
993 * Specifies the minimum and maximum gain. The source's gain is clamped to
994 * this range after distance attenuation and cone attenuation are applied
995 * to the gain base, although before the filter gain adjustements.
997 void setGainRange(ALfloat mingain
, ALfloat maxgain
);
998 std::pair
<ALfloat
,ALfloat
> getGainRange() const;
999 ALfloat
getMinGain() const { return std::get
<0>(getGainRange()); }
1000 ALfloat
getMaxGain() const { return std::get
<1>(getGainRange()); }
1003 * Specifies the reference distance and maximum distance the source will
1004 * use for the current distance model. For Clamped distance models, the
1005 * source's calculated distance is clamped to the specified range before
1006 * applying distance-related attenuation.
1008 * For all distance models, the reference distance is the distance at which
1009 * the source's volume will not have any extra attenuation (an effective
1010 * gain multiplier of 1).
1012 void setDistanceRange(ALfloat refdist
, ALfloat maxdist
);
1013 std::pair
<ALfloat
,ALfloat
> getDistanceRange() const;
1014 ALfloat
getReferenceDistance() const { return std::get
<0>(getDistanceRange()); }
1015 ALfloat
getMaxDistance() const { return std::get
<1>(getDistanceRange()); }
1017 /** Specifies the source's 3D position, velocity, and direction together. */
1018 void set3DParameters(const Vector3
&position
, const Vector3
&velocity
, const Vector3
&direction
);
1020 /** Specifies the source's 3D position, velocity, and orientation together. */
1021 void set3DParameters(const Vector3
&position
, const Vector3
&velocity
, std::pair
<Vector3
,Vector3
> orientation
);
1023 /** Specifies the source's 3D position. */
1024 void setPosition(ALfloat x
, ALfloat y
, ALfloat z
);
1025 void setPosition(const ALfloat
*pos
);
1026 Vector3
getPosition() const;
1029 * Specifies the source's 3D velocity, in units per second. As with OpenAL,
1030 * this does not actually alter the source's position, and instead just
1031 * alters the pitch as determined by the doppler effect.
1033 void setVelocity(ALfloat x
, ALfloat y
, ALfloat z
);
1034 void setVelocity(const ALfloat
*vel
);
1035 Vector3
getVelocity() const;
1038 * Specifies the source's 3D facing direction. Deprecated in favor of
1041 void setDirection(ALfloat x
, ALfloat y
, ALfloat z
);
1042 void setDirection(const ALfloat
*dir
);
1043 Vector3
getDirection() const;
1046 * Specifies the source's 3D orientation. Note: unlike the AL_EXT_BFORMAT
1047 * extension this property comes from, this also affects the facing
1048 * direction, superceding setDirection.
1050 void setOrientation(ALfloat x1
, ALfloat y1
, ALfloat z1
, ALfloat x2
, ALfloat y2
, ALfloat z2
);
1051 void setOrientation(const ALfloat
*at
, const ALfloat
*up
);
1052 void setOrientation(const ALfloat
*ori
);
1053 std::pair
<Vector3
,Vector3
> getOrientation() const;
1056 * Specifies the source's cone angles, in degrees. The inner angle is the
1057 * area within which the listener will hear the source with no extra
1058 * attenuation, while the listener being outside of the outer angle will
1059 * hear the source attenuated according to the outer cone gains.
1061 void setConeAngles(ALfloat inner
, ALfloat outer
);
1062 std::pair
<ALfloat
,ALfloat
> getConeAngles() const;
1063 ALfloat
getInnerConeAngle() const { return std::get
<0>(getConeAngles()); }
1064 ALfloat
getOuterConeAngle() const { return std::get
<1>(getConeAngles()); }
1067 * Specifies the linear gain multiplier when the listener is outside of the
1068 * source's outer cone area. The specified gain applies to all frequencies,
1069 * while gainhf applies extra attenuation to high frequencies.
1071 * \param gainhf has no effect without the ALC_EXT_EFX extension.
1073 void setOuterConeGains(ALfloat gain
, ALfloat gainhf
=1.0f
);
1074 std::pair
<ALfloat
,ALfloat
> getOuterConeGains() const;
1075 ALfloat
getOuterConeGain() const { return std::get
<0>(getOuterConeGains()); }
1076 ALfloat
getOuterConeGainHF() const { return std::get
<1>(getOuterConeGains()); }
1079 * Specifies the rolloff factors for the direct and send paths. This is
1080 * effectively a distance scaling relative to the reference distance. Note:
1081 * the room rolloff factor is 0 by default, disabling distance attenuation
1082 * for send paths. This is because the reverb engine will, by default,
1083 * apply a more realistic room decay based on the reverb decay time and
1086 void setRolloffFactors(ALfloat factor
, ALfloat roomfactor
=0.0f
);
1087 std::pair
<ALfloat
,ALfloat
> getRolloffFactors() const;
1088 ALfloat
getRolloffFactor() const { return std::get
<0>(getRolloffFactors()); }
1089 ALfloat
getRoomRolloffFactor() const { return std::get
<1>(getRolloffFactors()); }
1092 * Specifies the doppler factor for the doppler effect's pitch shift. This
1093 * effectively scales the source and listener velocities for the doppler
1096 void setDopplerFactor(ALfloat factor
);
1097 ALfloat
getDopplerFactor() const;
1100 * Specifies if the source's position, velocity, and direction/orientation
1101 * are relative to the listener.
1103 void setRelative(bool relative
);
1104 bool getRelative() const;
1107 * Specifies the source's radius. This causes the source to behave as if
1108 * every point within the spherical area emits sound.
1110 * Has no effect without the AL_EXT_SOURCE_RADIUS extension.
1112 void setRadius(ALfloat radius
);
1113 ALfloat
getRadius() const;
1116 * Specifies the left and right channel angles, in radians, when playing a
1117 * stereo buffer or stream. The angles go counter-clockwise, with 0 being
1118 * in front and positive values going left.
1120 * Has no effect without the AL_EXT_STEREO_ANGLES extension.
1122 void setStereoAngles(ALfloat leftAngle
, ALfloat rightAngle
);
1123 std::pair
<ALfloat
,ALfloat
> getStereoAngles() const;
1126 * Specifies if the source always has 3D spatialization features (On),
1127 * never has 3D spatialization features (Off), or if spatialization is
1128 * enabled based on playing a mono sound or not (Auto, default). Has no
1129 * effect without the AL_SOFT_source_spatialize extension.
1131 void set3DSpatialize(Spatialize spatialize
);
1132 Spatialize
get3DSpatialize() const;
1134 void setResamplerIndex(ALsizei index
);
1135 ALsizei
getResamplerIndex() const;
1138 * Specifies a multiplier for the amount of atmospheric high-frequency
1139 * absorption, ranging from 0 to 10. A factor of 1 results in a nominal
1140 * -0.05dB per meter, with higher values simulating foggy air and lower
1141 * values simulating dryer air. The default is 0.
1143 void setAirAbsorptionFactor(ALfloat factor
);
1144 ALfloat
getAirAbsorptionFactor() const;
1146 void setGainAuto(bool directhf
, bool send
, bool sendhf
);
1147 std::tuple
<bool,bool,bool> getGainAuto() const;
1148 bool getDirectGainHFAuto() const { return std::get
<0>(getGainAuto()); }
1149 bool getSendGainAuto() const { return std::get
<1>(getGainAuto()); }
1150 bool getSendGainHFAuto() const { return std::get
<2>(getGainAuto()); }
1152 /** Sets the filter properties on the direct path signal. */
1153 void setDirectFilter(const FilterParams
&filter
);
1155 * Sets the filter properties on the given send path signal. Any auxiliary
1156 * effect slot on the send path remains in place.
1158 void setSendFilter(ALuint send
, const FilterParams
&filter
);
1160 * Connects the effect slot to the given send path. Any filter properties
1161 * on the send path remain as they were.
1163 void setAuxiliarySend(AuxiliaryEffectSlot slot
, ALuint send
);
1165 * Connects the effect slot to the given send path, using the filter
1168 void setAuxiliarySendFilter(AuxiliaryEffectSlot slot
, ALuint send
, const FilterParams
&filter
);
1171 * Releases the source, stopping playback, releasing resources, and
1172 * returning it to the system.
1178 class ALURE_API SourceGroup
{
1179 MAKE_PIMPL(SourceGroup
, SourceGroupImpl
)
1182 /** Retrieves the associated name of the source group. */
1183 const String
&getName() const;
1186 * Adds source to the source group. A source may only be part of one group
1187 * at a time, and will automatically be removed from its current group as
1190 void addSource(Source source
);
1191 /** Removes source from the source group. */
1192 void removeSource(Source source
);
1194 /** Adds a list of sources to the group at once. */
1195 void addSources(ArrayView
<Source
> sources
);
1196 /** Removes a list of sources from the source group. */
1197 void removeSources(ArrayView
<Source
> sources
);
1200 * Adds group as a subgroup of the source group. This method will throw an
1201 * exception if group is being added to a group it has as a sub-group (i.e.
1202 * it would create a circular sub-group chain).
1204 void addSubGroup(SourceGroup group
);
1205 /** Removes group from the source group. */
1206 void removeSubGroup(SourceGroup group
);
1208 /** Returns the list of sources currently in the group. */
1209 Vector
<Source
> getSources() const;
1211 /** Returns the list of subgroups currently in the group. */
1212 Vector
<SourceGroup
> getSubGroups() const;
1214 /** Sets the source group gain, which accumulates with its sources. */
1215 void setGain(ALfloat gain
);
1216 /** Gets the source group gain. */
1217 ALfloat
getGain() const;
1219 /** Sets the source group pitch, which accumulates with its sources. */
1220 void setPitch(ALfloat pitch
);
1221 /** Gets the source group pitch. */
1222 ALfloat
getPitch() const;
1225 * Pauses all currently-playing sources that are under this group,
1226 * including sub-groups.
1228 void pauseAll() const;
1230 * Resumes all paused sources that are under this group, including
1233 void resumeAll() const;
1235 /** Stops all sources that are under this group, including sub-groups. */
1236 void stopAll() const;
1239 * Releases the source group, removing all sources from it before being
1251 class ALURE_API AuxiliaryEffectSlot
{
1252 MAKE_PIMPL(AuxiliaryEffectSlot
, AuxiliaryEffectSlotImpl
)
1255 void setGain(ALfloat gain
);
1257 * If set to true, the reverb effect will automatically apply adjustments
1258 * to the source's send slot gains based on the effect properties.
1260 * Has no effect when using non-reverb effects. Default is true.
1262 void setSendAuto(bool sendauto
);
1265 * Updates the effect slot with a new effect. The given effect object may
1266 * be altered or destroyed without affecting the effect slot.
1268 void applyEffect(Effect effect
);
1271 * Releases the effect slot, returning it to the system. It must not be in
1277 * Retrieves each Source object and its pairing send this effect slot is
1278 * set on. Setting a different (or null) effect slot on each source's given
1279 * send will allow the effect slot to be released.
1281 Vector
<SourceSend
> getSourceSends() const;
1283 /** Determines if the effect slot is in use by a source. */
1284 bool isInUse() const;
1288 class ALURE_API Effect
{
1289 MAKE_PIMPL(Effect
, EffectImpl
)
1293 * Updates the effect with the specified reverb properties. If the
1294 * EAXReverb effect is not supported, it will automatically attempt to
1295 * downgrade to the Standard Reverb effect.
1297 void setReverbProperties(const EFXEAXREVERBPROPERTIES
&props
);
1304 * Audio decoder interface. Applications may derive from this, implementing the
1305 * necessary methods, and use it in places the API wants a Decoder object.
1307 class ALURE_API Decoder
{
1311 /** Retrieves the sample frequency, in hz, of the audio being decoded. */
1312 virtual ALuint
getFrequency() const = 0;
1313 /** Retrieves the channel configuration of the audio being decoded. */
1314 virtual ChannelConfig
getChannelConfig() const = 0;
1315 /** Retrieves the sample type of the audio being decoded. */
1316 virtual SampleType
getSampleType() const = 0;
1319 * Retrieves the total length of the audio, in sample frames. If unknown,
1320 * returns 0. Note that if the returned length is 0, the decoder may not be
1321 * used to load a Buffer.
1323 virtual uint64_t getLength() const = 0;
1325 * Seek to pos, specified in sample frames. Returns true if the seek was
1328 virtual bool seek(uint64_t pos
) = 0;
1331 * Retrieves the loop points, in sample frames, as a [start,end) pair. If
1332 * start >= end, use all available data.
1334 virtual std::pair
<uint64_t,uint64_t> getLoopPoints() const = 0;
1337 * Decodes count sample frames, writing them to ptr, and returns the number
1338 * of sample frames written. Returning less than the requested count
1339 * indicates the end of the audio.
1341 virtual ALuint
read(ALvoid
*ptr
, ALuint count
) = 0;
1345 * Audio decoder factory interface. Applications may derive from this,
1346 * implementing the necessary methods, and use it in places the API wants a
1347 * DecoderFactory object.
1349 class ALURE_API DecoderFactory
{
1351 virtual ~DecoderFactory();
1354 * Creates and returns a Decoder instance for the given resource file. If
1355 * the decoder needs to retain the file handle for reading as-needed, it
1356 * should move the UniquePtr to internal storage.
1358 * \return nullptr if a decoder can't be created from the file.
1360 virtual SharedPtr
<Decoder
> createDecoder(UniquePtr
<std::istream
> &file
) = 0;
1364 * Registers a decoder factory for decoding audio. Registered factories are
1365 * used in lexicographical order, e.g. if Factory1 is registered with name1 and
1366 * Factory2 is registered with name2, Factory1 will be used before Factory2 if
1367 * name1 < name2. Internal decoder factories are always used after registered
1370 * Alure retains a reference to the DecoderFactory instance and will release it
1371 * (destructing the object) when the library unloads.
1373 * \param name A unique name identifying this decoder factory.
1374 * \param factory A DecoderFactory instance used to create Decoder instances.
1376 ALURE_API
void RegisterDecoder(const String
&name
, UniquePtr
<DecoderFactory
> factory
);
1379 * Unregisters a decoder factory by name. Alure returns the instance back to
1382 * \param name The unique name identifying a previously-registered decoder
1385 * \return The unregistered decoder factory instance, or 0 (nullptr) if a
1386 * decoder factory with the given name doesn't exist.
1388 ALURE_API UniquePtr
<DecoderFactory
> UnregisterDecoder(const String
&name
);
1392 * A file I/O factory interface. Applications may derive from this and set an
1393 * instance to be used by the audio decoders. By default, the library uses
1396 class ALURE_API FileIOFactory
{
1399 * Sets the factory instance to be used by the audio decoders. If a
1400 * previous factory was set, it's returned to the application. Passing in a
1401 * nullptr reverts to the default.
1403 static UniquePtr
<FileIOFactory
> set(UniquePtr
<FileIOFactory
> factory
);
1406 * Gets the current FileIOFactory instance being used by the audio
1409 static FileIOFactory
&get();
1411 virtual ~FileIOFactory();
1413 /** Opens a read-only binary file for the given name. */
1414 virtual UniquePtr
<std::istream
> openFile(const String
&name
) = 0;
1419 * A message handler interface. Applications may derive from this and set an
1420 * instance on a context to receive messages. The base methods are no-ops, so
1421 * derived classes only need to implement methods for relevant messages.
1423 * It's recommended that applications mark their handler methods using the
1424 * override keyword, to ensure they're properly overriding the base methods in
1427 class ALURE_API MessageHandler
{
1429 virtual ~MessageHandler();
1432 * Called when the given device has been disconnected and is no longer
1433 * usable for output. As per the ALC_EXT_disconnect specification,
1434 * disconnected devices remain valid, however all playing sources are
1435 * automatically stopped, any sources that are attempted to play will
1436 * immediately stop, and new contexts may not be created on the device.
1438 * Note that connection status is checked during Context::update calls, so
1439 * that method must be called regularly to be notified when a device is
1440 * disconnected. This method may not be called if the device lacks support
1441 * for the ALC_EXT_disconnect extension.
1443 virtual void deviceDisconnected(Device device
);
1446 * Called when the given source reaches the end of the buffer or stream.
1448 * Sources that stopped automatically will be detected upon a call to
1451 virtual void sourceStopped(Source source
);
1454 * Called when the given source was forced to stop. This can be because
1455 * either there were no more system sources and a higher-priority source
1456 * preempted it, or it's part of a SourceGroup (or sub-group thereof) that
1457 * had its SourceGroup::stopAll method called.
1459 virtual void sourceForceStopped(Source source
);
1462 * Called when a new buffer is about to be created and loaded. May be
1463 * called asynchronously for buffers being loaded asynchronously.
1465 * \param name The resource name, as passed to Context::getBuffer.
1466 * \param channels Channel configuration of the given audio data.
1467 * \param type Sample type of the given audio data.
1468 * \param samplerate Sample rate of the given audio data.
1469 * \param data The audio data that is about to be fed to the OpenAL buffer.
1471 virtual void bufferLoading(StringView name
, ChannelConfig channels
, SampleType type
, ALuint samplerate
, ArrayView
<ALbyte
> data
);
1474 * Called when a resource isn't found, allowing the app to substitute in a
1475 * different resource. For buffers created with Context::getBuffer or
1476 * Context::getBufferAsync, the original name will still be used for the
1477 * cache map so the app doesn't have to keep track of substituted resource
1480 * This will be called again if the new name isn't found.
1482 * \param name The resource name that was not found.
1483 * \return The replacement resource name to use instead. Returning an empty
1484 * string means to stop trying.
1486 virtual String
resourceNotFound(StringView name
);
1491 } // namespace alure
1493 #endif /* AL_ALURE2_H */