Cleanup some includes
[alure.git] / include / AL / alure2.h
blob5d9c812b7d1bf82e96be1f1a39ab5d92e02115fd
1 #ifndef AL_ALURE2_H
2 #define AL_ALURE2_H
4 #include <type_traits>
5 #include <utility>
6 #include <tuple>
7 #include <cmath>
9 #include "alc.h"
10 #include "al.h"
11 #include "alure2-alext.h"
13 #include "alure2-aliases.h"
14 #include "alure2-typeviews.h"
16 #ifndef ALURE_API
17 #ifndef ALURE_STATIC_LIB
18 #if defined(_WIN32)
19 #define ALURE_API __declspec(dllimport)
20 #elif defined(__has_attribute)
21 #if __has_attribute(visibility)
22 #define ALURE_API __attribute__((visibility("default")))
23 #endif
24 #elif defined(__GNUC__)
25 #define ALURE_API __attribute__((visibility("default")))
26 #endif
27 #endif
28 #ifndef ALURE_API
29 #define ALURE_API
30 #endif
31 #endif /* ALURE_API */
33 #ifndef EFXEAXREVERBPROPERTIES_DEFINED
34 #define EFXEAXREVERBPROPERTIES_DEFINED
35 typedef struct {
36 float flDensity;
37 float flDiffusion;
38 float flGain;
39 float flGainHF;
40 float flGainLF;
41 float flDecayTime;
42 float flDecayHFRatio;
43 float flDecayLFRatio;
44 float flReflectionsGain;
45 float flReflectionsDelay;
46 float flReflectionsPan[3];
47 float flLateReverbGain;
48 float flLateReverbDelay;
49 float flLateReverbPan[3];
50 float flEchoTime;
51 float flEchoDepth;
52 float flModulationTime;
53 float flModulationDepth;
54 float flAirAbsorptionGainHF;
55 float flHFReference;
56 float flLFReference;
57 float flRoomRolloffFactor;
58 int iDecayHFLimit;
59 } EFXEAXREVERBPROPERTIES, *LPEFXEAXREVERBPROPERTIES;
60 #endif
62 namespace alure {
64 // Available class interfaces.
65 class DeviceManager;
66 class Device;
67 class Context;
68 class Listener;
69 class Buffer;
70 class Source;
71 class SourceGroup;
72 class AuxiliaryEffectSlot;
73 class Effect;
74 class Decoder;
75 class DecoderFactory;
76 class MessageHandler;
78 // Opaque class implementations.
79 class DeviceManagerImpl;
80 class DeviceImpl;
81 class ContextImpl;
82 class ListenerImpl;
83 class BufferImpl;
84 class SourceImpl;
85 class SourceGroupImpl;
86 class AuxiliaryEffectSlotImpl;
87 class EffectImpl;
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
103 * Device::reset.
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 {
111 ALfloat mGain;
112 ALfloat mGainHF; // For low-pass and band-pass filters
113 ALfloat mGainLF; // For high-pass and band-pass filters
117 class Vector3 {
118 Array<ALfloat,3> mValue;
120 public:
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
131 : mValue{{x, y, z}}
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]); \
152 ALURE_DECL_OP(+)
153 ALURE_DECL_OP(-)
154 ALURE_DECL_OP(*)
155 ALURE_DECL_OP(/)
156 #undef ALURE_DECL_OP
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]; \
163 return *this; \
165 ALURE_DECL_OP(+=)
166 ALURE_DECL_OP(-=)
167 ALURE_DECL_OP(*=)
168 ALURE_DECL_OP(/=)
170 #undef ALURE_DECL_OP
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); \
178 ALURE_DECL_OP(*)
179 ALURE_DECL_OP(/)
180 #undef ALURE_DECL_OP
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; \
187 return *this; \
189 ALURE_DECL_OP(*=)
190 ALURE_DECL_OP(/=)
191 #undef ALURE_DECL_OP
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 {
207 UInt8,
208 Int16,
209 Float32,
210 Mulaw
212 ALURE_API const char *GetSampleTypeName(SampleType type);
214 enum class ChannelConfig {
215 /** 1-channel mono sound. */
216 Mono,
217 /** 2-channel stereo sound. */
218 Stereo,
219 /** 2-channel rear sound (back-left and back-right). */
220 Rear,
221 /** 4-channel surround sound. */
222 Quad,
223 /** 5.1 surround sound. */
224 X51,
225 /** 6.1 surround sound. */
226 X61,
227 /** 7.1 surround sound. */
228 X71,
229 /** 3-channel B-Format, using FuMa channel ordering and scaling. */
230 BFormat2D,
231 /** 4-channel B-Format, using FuMa channel ordering and scaling. */
232 BFormat3D
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. */
241 class Version {
242 ALuint mMajor : 16;
243 ALuint mMinor : 16;
245 public:
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; }
252 constexpr bool isZero() const noexcept { return mMajor == 0 && mMinor == 0; }
255 #define MAKE_PIMPL(BaseT, ImplT) \
256 private: \
257 ImplT *pImpl; \
259 public: \
260 using handle_type = ImplT*; \
262 BaseT() : pImpl(nullptr) { } \
263 BaseT(ImplT *impl) : pImpl(impl) { } \
264 BaseT(const BaseT&) = default; \
265 BaseT(BaseT&& rhs) : pImpl(rhs.pImpl) { rhs.pImpl = nullptr; } \
267 BaseT& operator=(const BaseT&) = default; \
268 BaseT& operator=(BaseT&& rhs) \
270 pImpl = rhs.pImpl; rhs.pImpl = nullptr; \
271 return *this; \
274 bool operator==(const BaseT &rhs) const { return pImpl == rhs.pImpl; } \
275 bool operator!=(const BaseT &rhs) const { return pImpl != rhs.pImpl; } \
276 bool operator<=(const BaseT &rhs) const { return pImpl <= rhs.pImpl; } \
277 bool operator>=(const BaseT &rhs) const { return pImpl >= rhs.pImpl; } \
278 bool operator<(const BaseT &rhs) const { return pImpl < rhs.pImpl; } \
279 bool operator>(const BaseT &rhs) const { return pImpl > rhs.pImpl; } \
281 operator bool() const { return !!pImpl; } \
283 handle_type getHandle() const { return pImpl; }
285 enum class DeviceEnumeration {
286 Basic = ALC_DEVICE_SPECIFIER,
287 Full = ALC_ALL_DEVICES_SPECIFIER,
288 Capture = ALC_CAPTURE_DEVICE_SPECIFIER
291 enum class DefaultDeviceType {
292 Basic = ALC_DEFAULT_DEVICE_SPECIFIER,
293 Full = ALC_DEFAULT_ALL_DEVICES_SPECIFIER,
294 Capture = ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER
298 * A class managing Device objects and other related functionality. This class
299 * is a singleton, only one instance will exist in a process.
301 class ALURE_API DeviceManager {
302 DeviceManagerImpl *pImpl;
304 DeviceManager(DeviceManagerImpl *impl) : pImpl(impl) { }
305 friend class ALDeviceManager;
307 public:
308 DeviceManager(const DeviceManager&) = default;
309 DeviceManager(DeviceManager&& rhs) : pImpl(rhs.pImpl) { }
311 /** Retrieves the DeviceManager instance. */
312 static DeviceManager get();
314 /** Queries the existence of a non-device-specific ALC extension. */
315 bool queryExtension(const String &name) const;
316 bool queryExtension(const char *name) const;
318 /** Enumerates available device names of the given type. */
319 Vector<String> enumerate(DeviceEnumeration type) const;
320 /** Retrieves the default device of the given type. */
321 String defaultDeviceName(DefaultDeviceType type) const;
324 * Opens the playback device given by name, or the default if blank. Throws
325 * an exception on error.
327 Device openPlayback(const String &name={});
328 Device openPlayback(const char *name);
331 * Opens the playback device given by name, or the default if blank.
332 * Returns an empty Device on error.
334 Device openPlayback(const String &name, const std::nothrow_t&);
335 Device openPlayback(const char *name, const std::nothrow_t&);
337 /** Opens the default playback device. Returns an empty Device on error. */
338 Device openPlayback(const std::nothrow_t&);
342 enum class PlaybackName {
343 Basic = ALC_DEVICE_SPECIFIER,
344 Full = ALC_ALL_DEVICES_SPECIFIER
347 class ALURE_API Device {
348 MAKE_PIMPL(Device, DeviceImpl)
350 public:
351 /** Retrieves the device name as given by type. */
352 String getName(PlaybackName type=PlaybackName::Full) const;
353 /** Queries the existence of an ALC extension on this device. */
354 bool queryExtension(const String &name) const;
355 bool queryExtension(const char *name) const;
357 /** Retrieves the ALC version supported by this device. */
358 Version getALCVersion() const;
361 * Retrieves the EFX version supported by this device. If the ALC_EXT_EFX
362 * extension is unsupported, this will be 0.0.
364 Version getEFXVersion() const;
366 /** Retrieves the device's playback frequency, in hz. */
367 ALCuint getFrequency() const;
370 * Retrieves the maximum number of auxiliary source sends. If ALC_EXT_EFX
371 * is unsupported, this will be 0.
373 ALCuint getMaxAuxiliarySends() const;
376 * Enumerates available HRTF names. The names are sorted as OpenAL gives
377 * them, such that the index of a given name is the ID to use with
378 * ALC_HRTF_ID_SOFT.
380 * Requires the ALC_SOFT_HRTF extension.
382 Vector<String> enumerateHRTFNames() const;
385 * Retrieves whether HRTF is enabled on the device or not.
387 * Requires the ALC_SOFT_HRTF extension.
389 bool isHRTFEnabled() const;
392 * Retrieves the name of the HRTF currently being used by this device.
394 * Requires the ALC_SOFT_HRTF extension.
396 String getCurrentHRTF() const;
399 * Resets the device, using the specified attributes.
401 * Requires the ALC_SOFT_HRTF extension.
403 void reset(ArrayView<AttributePair> attributes);
406 * Creates a new Context on this device, using the specified attributes.
407 * Throws an exception if context creation fails.
409 Context createContext(ArrayView<AttributePair> attributes={});
411 * Creates a new Context on this device, using the specified attributes.
412 * Returns an empty Context if context creation fails.
414 Context createContext(ArrayView<AttributePair> attributes, const std::nothrow_t&);
415 Context createContext(const std::nothrow_t&);
418 * Pauses device processing, stopping updates for its contexts. Multiple
419 * calls are allowed but it is not reference counted, so the device will
420 * resume after one resumeDSP call.
422 * Requires the ALC_SOFT_pause_device extension.
424 void pauseDSP();
427 * Resumes device processing, restarting updates for its contexts. Multiple
428 * calls are allowed and will no-op.
430 void resumeDSP();
433 * Closes and frees the device. All previously-created contexts must first
434 * be destroyed.
436 void close();
440 enum class DistanceModel {
441 InverseClamped = AL_INVERSE_DISTANCE_CLAMPED,
442 LinearClamped = AL_LINEAR_DISTANCE_CLAMPED,
443 ExponentClamped = AL_EXPONENT_DISTANCE_CLAMPED,
444 Inverse = AL_INVERSE_DISTANCE,
445 Linear = AL_LINEAR_DISTANCE,
446 Exponent = AL_EXPONENT_DISTANCE,
447 None = AL_NONE,
450 class ALURE_API Context {
451 MAKE_PIMPL(Context, ContextImpl)
453 public:
454 /** Makes the specified context current for OpenAL operations. */
455 static void MakeCurrent(Context context);
456 /** Retrieves the current context used for OpenAL operations. */
457 static Context GetCurrent();
460 * Makes the specified context current for OpenAL operations on the calling
461 * thread only. Requires the ALC_EXT_thread_local_context extension on both
462 * the context's device and the DeviceManager.
464 static void MakeThreadCurrent(Context context);
465 /** Retrieves the thread-specific context used for OpenAL operations. */
466 static Context GetThreadCurrent();
469 * Destroys the context. The context must not be current when this is
470 * called.
472 void destroy();
474 /** Retrieves the Device this context was created from. */
475 Device getDevice();
477 void startBatch();
478 void endBatch();
481 * Retrieves a Listener instance for this context. Each context will only
482 * have one listener, which is automatically destroyed with the context.
484 Listener getListener();
487 * Sets a MessageHandler instance which will be used to provide certain
488 * messages back to the application. Only one handler may be set for a
489 * context at a time. The previously set handler will be returned.
491 SharedPtr<MessageHandler> setMessageHandler(SharedPtr<MessageHandler> handler);
493 /** Gets the currently-set message handler. */
494 SharedPtr<MessageHandler> getMessageHandler() const;
497 * Specifies the desired interval that the background thread will be woken
498 * up to process tasks, e.g. keeping streaming sources filled. An interval
499 * of 0 means the background thread will only be woken up manually with
500 * calls to update. The default is 0.
502 void setAsyncWakeInterval(std::chrono::milliseconds interval);
505 * Retrieves the current interval used for waking up the background thread.
507 std::chrono::milliseconds getAsyncWakeInterval() const;
509 // Functions below require the context to be current
512 * Creates a Decoder instance for the given audio file or resource name.
514 SharedPtr<Decoder> createDecoder(StringView name);
517 * Queries if the channel configuration and sample type are supported by
518 * the context.
520 bool isSupported(ChannelConfig channels, SampleType type) const;
523 * Queries the list of resamplers supported by the context. If the
524 * AL_SOFT_source_resampler extension is unsupported this will be an empty
525 * array, otherwise there will be at least one entry.
527 ArrayView<String> getAvailableResamplers();
529 * Queries the context's default resampler index. Be aware, if the
530 * AL_SOFT_source_resampler extension is unsupported the resampler list
531 * will be empty and this will resturn 0. If you try to access the
532 * resampler list with this index without the extension, undefined behavior
533 * will occur (accessing an out of bounds array index).
535 ALsizei getDefaultResamplerIndex() const;
538 * Creates and caches a Buffer for the given audio file or resource name.
539 * Multiple calls with the same name will return the same Buffer object.
540 * Cached buffers must be freed using removeBuffer before destroying the
541 * context. If the buffer can't be loaded it will throw an exception.
543 Buffer getBuffer(StringView name);
546 * Asynchronously prepares a cached Buffer for the given audio file or
547 * resource name. Multiple calls with the same name will return multiple
548 * SharedFutures for the same Buffer object. Once called, the buffer must
549 * be freed using removeBuffer before destroying the context, even if you
550 * never get the Buffer from the SharedFuture.
552 * The Buffer will be scheduled to load asynchronously, and the caller gets
553 * back a SharedFuture that can be checked later (or waited on) to get the
554 * actual Buffer when it's ready. The application must take care to handle
555 * exceptions from the SharedFuture in case an unrecoverable error ocurred
556 * during the load.
558 SharedFuture<Buffer> getBufferAsync(StringView name);
561 * Asynchronously prepares cached Buffers for the given audio file or
562 * resource names. Duplicate names and buffers already cached are ignored.
563 * Cached buffers must be freed using removeBuffer before destroying the
564 * context.
566 * The Buffer objects will be scheduled for loading asynchronously, and
567 * should be retrieved later when needed using getBufferAsync or getBuffer.
568 * Buffers that cannot be loaded, for example due to an unsupported format,
569 * will be ignored and a later call to getBuffer or getBufferAsync will
570 * throw an exception.
572 void precacheBuffersAsync(ArrayView<StringView> names);
575 * Creates and caches a Buffer using the given name by reading the given
576 * decoder. The name may alias an audio file, but it must not currently
577 * exist in the buffer cache.
579 Buffer createBufferFrom(StringView name, SharedPtr<Decoder> decoder);
582 * Asynchronously prepares a cached Buffer using the given name by reading
583 * the given decoder. The name may alias an audio file, but it must not
584 * currently exist in the buffer cache. Once called, the buffer must be
585 * freed using removeBuffer before destroying the context, even if you
586 * never get the Buffer from the SharedFuture.
588 * The Buffer will be scheduled to load asynchronously, and the caller gets
589 * back a SharedFuture that can be checked later (or waited on) to get the
590 * actual Buffer when it's ready. The application must take care to handle
591 * exceptions from the SharedFuture in case an unrecoverable error ocurred
592 * during the load. The decoder must not have its read or seek methods
593 * called while the buffer is not ready.
595 SharedFuture<Buffer> createBufferAsyncFrom(StringView name, SharedPtr<Decoder> decoder);
598 * Looks for a cached buffer using the given name and returns it. If the
599 * given name does not exist in the cache, and null buffer is returned.
601 Buffer findBuffer(StringView name);
604 * Looks for an asynchronously-loading buffer using the given name and
605 * returns a SharedFuture for it. If the given name does not exist in the
606 * cache, an invalid SharedFuture is returned (check with a call to
607 * \c SharedFuture::valid).
609 SharedFuture<Buffer> findBufferAsync(StringView name);
612 * Deletes the cached Buffer object for the given audio file or resource
613 * name. The buffer must not be in use by a Source.
615 void removeBuffer(StringView name);
617 * Deletes the given cached buffer. The buffer must not be in use by a
618 * Source.
620 void removeBuffer(Buffer buffer);
623 * Creates a new Source for playing audio. There is no practical limit to
624 * the number of sources you may create. You must call Source::release when
625 * the source is no longer needed.
627 Source createSource();
629 AuxiliaryEffectSlot createAuxiliaryEffectSlot();
631 Effect createEffect();
633 SourceGroup createSourceGroup(StringView name);
634 SourceGroup getSourceGroup(StringView name);
636 /** Sets the doppler factor to apply to all source doppler calculations. */
637 void setDopplerFactor(ALfloat factor);
640 * Sets the speed of sound propagation, in units per second, to calculate
641 * the doppler effect along with other distance-related time effects. The
642 * default is 343.3 units per second (a realistic speed assuming 1 meter
643 * per unit). If this is adjusted for a different unit scale,
644 * Listener::setMetersPerUnit should also be adjusted.
646 void setSpeedOfSound(ALfloat speed);
649 * Sets the distance model used to attenuate sources given their distance
650 * from the listener. The default, InverseClamped, provides a realistic 1/r
651 * reduction in volume (that is, every doubling of distance causes the gain
652 * to reduce by half).
654 * The Clamped distance models restrict the source distance for the purpose
655 * of distance attenuation, so a source won't sound closer than its
656 * reference distance or farther than its max distance.
658 void setDistanceModel(DistanceModel model);
660 /** Updates the context and all sources belonging to this context. */
661 void update();
664 class ALURE_API Listener {
665 MAKE_PIMPL(Listener, ListenerImpl)
667 public:
668 /** Sets the "master" gain for all context output. */
669 void setGain(ALfloat gain);
672 * Specifies the listener's 3D position, velocity, and orientation
673 * together (see: setPosition, setVelocity, and setOrientation).
675 void set3DParameters(const Vector3 &position, const Vector3 &velocity, const std::pair<Vector3,Vector3> &orientation);
677 /** Specifies the listener's 3D position. */
678 void setPosition(ALfloat x, ALfloat y, ALfloat z);
679 void setPosition(const ALfloat *pos);
682 * Specifies the listener's 3D velocity, in units per second. As with
683 * OpenAL, this does not actually alter the listener's position, and
684 * instead just alters the pitch as determined by the doppler effect.
686 void setVelocity(ALfloat x, ALfloat y, ALfloat z);
687 void setVelocity(const ALfloat *vel);
690 * Specifies the listener's 3D orientation, using position-relative 'at'
691 * and 'up' direction vectors.
693 void setOrientation(ALfloat x1, ALfloat y1, ALfloat z1, ALfloat x2, ALfloat y2, ALfloat z2);
694 void setOrientation(const ALfloat *at, const ALfloat *up);
695 void setOrientation(const ALfloat *ori);
698 * Sets the number of meters per unit, used for various effects that rely
699 * on the distance in meters (including air absorption and initial reverb
700 * decay). If this is changed, it's strongly recommended to also set the
701 * speed of sound (e.g. context.setSpeedOfSound(343.3 / m_u) to maintain a
702 * realistic 343.3m/s for sound propagation).
704 void setMetersPerUnit(ALfloat m_u);
708 class ALURE_API Buffer {
709 MAKE_PIMPL(Buffer, BufferImpl)
711 public:
712 /** Retrieves the length of the buffer in sample frames. */
713 ALuint getLength() const;
715 /** Retrieves the buffer's frequency in hz. */
716 ALuint getFrequency() const;
718 /** Retrieves the buffer's sample configuration. */
719 ChannelConfig getChannelConfig() const;
721 /** Retrieves the buffer's sample type. */
722 SampleType getSampleType() const;
725 * Retrieves the storage size used by the buffer, in bytes. Note that the
726 * size in bytes may not be what you expect from the length, as it may take
727 * more space internally than the ChannelConfig and SampleType suggest to
728 * be more efficient.
730 ALuint getSize() const;
733 * Sets the buffer's loop points, used for looping sources. If the current
734 * context does not support the AL_SOFT_loop_points extension, start and
735 * end must be 0 and getLength() respectively. Otherwise, start must be
736 * less than end, and end must be less than or equal to getLength().
738 * The buffer must not be in use when this method is called.
740 * \param start The starting point, in sample frames (inclusive).
741 * \param end The ending point, in sample frames (exclusive).
743 void setLoopPoints(ALuint start, ALuint end);
745 /** Retrieves the current loop points as a [start,end) pair. */
746 std::pair<ALuint,ALuint> getLoopPoints() const;
749 * Retrieves the Source objects currently playing the buffer. Stopping the
750 * returned sources will allow the buffer to be removed from the context.
752 Vector<Source> getSources() const;
754 /** Retrieves the name the buffer was created with. */
755 StringView getName() const;
757 /** Queries if the buffer is in use and can't be removed. */
758 bool isInUse() const;
762 enum class Spatialize {
763 Off = AL_FALSE,
764 On = AL_TRUE,
765 Auto = 0x0002 /* AL_AUTO_SOFT */
768 class ALURE_API Source {
769 MAKE_PIMPL(Source, SourceImpl)
771 public:
773 * Plays the source using a buffer. The same buffer may be played from
774 * multiple sources simultaneously.
776 void play(Buffer buffer);
778 * Plays the source by asynchronously streaming audio from a decoder. The
779 * given decoder must *NOT* have its read or seek methods called from
780 * elsewhere while in use.
782 * \param decoder The decoder object to play audio from.
783 * \param chunk_len The number of sample frames to read for each chunk
784 * update. Smaller values will require more frequent updates and
785 * larger values will handle more data with each chunk.
786 * \param queue_size The number of chunks to keep queued during playback.
787 * Smaller values use less memory while larger values improve
788 * protection against underruns.
790 void play(SharedPtr<Decoder> decoder, ALuint chunk_len, ALuint queue_size);
793 * Prepares to play a source using a future buffer. The method will return
794 * right away and the source will begin playing once the future buffer
795 * becomes ready. If the future buffer is already ready, it begins playing
796 * immediately as if you called play(future_buffer.get()).
798 * The future buffer is checked during calls to \c Context::update and the
799 * source will start playback once the future buffer reports it's ready.
800 * Use the isPending method to check if the source is still waiting for the
801 * future buffer.
803 void play(SharedFuture<Buffer> future_buffer);
806 * Stops playback, releasing the buffer or decoder reference. Any pending
807 * playback from a future buffer is canceled.
809 void stop();
812 * Fades the source to the specified gain over the given duration, at which
813 * point playback will stop. This gain is in addition to the base gain, and
814 * must be greater than 0 and less than 1. The duration must also be
815 * greater than 0.
817 * Pending playback from a future buffer is not immediately canceled, but
818 * the fading starts with this call. If the future buffer then becomes
819 * ready, it will start mid-fade. Pending playback will be canceled if the
820 * fade out completes before the future buffer becomes ready.
822 * Fading is updated during calls to \c Context::update, which should be
823 * called regularly (30 to 50 times per second) for the fading to be
824 * smooth.
826 void fadeOutToStop(ALfloat gain, std::chrono::milliseconds duration);
828 /** Pauses the source if it is playing. */
829 void pause();
831 /** Resumes the source if it is paused. */
832 void resume();
834 /** Specifies if the source is waiting to play a future buffer. */
835 bool isPending() const;
837 /** Specifies if the source is currently playing. */
838 bool isPlaying() const;
840 /** Specifies if the source is currently paused. */
841 bool isPaused() const;
844 * Sets this source as a child of the given source group. The given source
845 * group's parameters will influence this and all other sources that belong
846 * to it. A source can only be the child of one source group at a time,
847 * although that source group may belong to another source group.
849 * Passing in a null group removes it from its current source group.
851 void setGroup(SourceGroup group);
853 /** Retrieves the source group this source belongs to. */
854 SourceGroup getGroup() const;
857 * Specifies the source's playback priority. The lowest priority sources
858 * will be forcefully stopped when no more mixing sources are available and
859 * higher priority sources are played.
861 void setPriority(ALuint priority);
862 /** Retrieves the source's priority. */
863 ALuint getPriority() const;
866 * Sets the source's offset, in sample frames. If the source is playing or
867 * paused, it will go to that offset immediately, otherwise the source will
868 * start at the specified offset the next time it's played.
870 void setOffset(uint64_t offset);
872 * Retrieves the source offset in sample frames and its latency in nano-
873 * seconds. For streaming sources this will be the offset based on the
874 * decoder's read position.
876 * If the AL_SOFT_source_latency extension is unsupported, the latency will
877 * be 0.
879 std::pair<uint64_t,std::chrono::nanoseconds> getSampleOffsetLatency() const;
880 uint64_t getSampleOffset() const { return std::get<0>(getSampleOffsetLatency()); }
882 * Retrieves the source offset and latency in seconds. For streaming
883 * sources this will be the offset based on the decoder's read position.
885 * If the AL_SOFT_source_latency extension is unsupported, the latency will
886 * be 0.
888 std::pair<Seconds,Seconds> getSecOffsetLatency() const;
889 Seconds getSecOffset() const { return std::get<0>(getSecOffsetLatency()); }
892 * Specifies if the source should loop on the Buffer or Decoder object's
893 * loop points.
895 void setLooping(bool looping);
896 bool getLooping() const;
899 * Specifies a linear pitch shift base. A value of 1.0 is the default
900 * normal speed.
902 void setPitch(ALfloat pitch);
903 ALfloat getPitch() const;
906 * Specifies the base linear gain. A value of 1.0 is the default normal
907 * volume.
909 void setGain(ALfloat gain);
910 ALfloat getGain() const;
913 * Specifies the minimum and maximum gain. The source's gain is clamped to
914 * this range after distance attenuation and cone attenuation are applied
915 * to the gain base, although before the filter gain adjustements.
917 void setGainRange(ALfloat mingain, ALfloat maxgain);
918 std::pair<ALfloat,ALfloat> getGainRange() const;
919 ALfloat getMinGain() const { return std::get<0>(getGainRange()); }
920 ALfloat getMaxGain() const { return std::get<1>(getGainRange()); }
923 * Specifies the reference distance and maximum distance the source will
924 * use for the current distance model. For Clamped distance models, the
925 * source's calculated distance is clamped to the specified range before
926 * applying distance-related attenuation.
928 * For all distance models, the reference distance is the distance at which
929 * the source's volume will not have any extra attenuation (an effective
930 * gain multiplier of 1).
932 void setDistanceRange(ALfloat refdist, ALfloat maxdist);
933 std::pair<ALfloat,ALfloat> getDistanceRange() const;
934 ALfloat getReferenceDistance() const { return std::get<0>(getDistanceRange()); }
935 ALfloat getMaxDistance() const { return std::get<1>(getDistanceRange()); }
938 * Specifies the source's 3D position, velocity, and direction together
939 * (see: setPosition, setVelocity, and setDirection).
941 void set3DParameters(const Vector3 &position, const Vector3 &velocity, const Vector3 &direction);
944 * Specifies the source's 3D position, velocity, and orientation together
945 * (see: setPosition, setVelocity, and setOrientation).
947 void set3DParameters(const Vector3 &position, const Vector3 &velocity, const std::pair<Vector3,Vector3> &orientation);
949 /** Specifies the source's 3D position. */
950 void setPosition(ALfloat x, ALfloat y, ALfloat z);
951 void setPosition(const ALfloat *pos);
952 Vector3 getPosition() const;
955 * Specifies the source's 3D velocity, in units per second. As with OpenAL,
956 * this does not actually alter the source's position, and instead just
957 * alters the pitch as determined by the doppler effect.
959 void setVelocity(ALfloat x, ALfloat y, ALfloat z);
960 void setVelocity(const ALfloat *vel);
961 Vector3 getVelocity() const;
964 * Specifies the source's 3D facing direction. Deprecated in favor of
965 * setOrientation.
967 void setDirection(ALfloat x, ALfloat y, ALfloat z);
968 void setDirection(const ALfloat *dir);
969 Vector3 getDirection() const;
972 * Specifies the source's 3D orientation, using position-relative 'at' and
973 * 'up' direction vectors. Note: unlike the AL_EXT_BFORMAT extension this
974 * property comes from, this also affects the facing direction, superceding
975 * setDirection.
977 void setOrientation(ALfloat x1, ALfloat y1, ALfloat z1, ALfloat x2, ALfloat y2, ALfloat z2);
978 void setOrientation(const ALfloat *at, const ALfloat *up);
979 void setOrientation(const ALfloat *ori);
980 std::pair<Vector3,Vector3> getOrientation() const;
983 * Specifies the source's cone angles, in degrees. The inner angle is the
984 * area within which the listener will hear the source with no extra
985 * attenuation, while the listener being outside of the outer angle will
986 * hear the source attenuated according to the outer cone gains. The area
987 * follows the facing direction, so for example an inner angle of 180 means
988 * the entire front face of the source is in the inner cone.
990 void setConeAngles(ALfloat inner, ALfloat outer);
991 std::pair<ALfloat,ALfloat> getConeAngles() const;
992 ALfloat getInnerConeAngle() const { return std::get<0>(getConeAngles()); }
993 ALfloat getOuterConeAngle() const { return std::get<1>(getConeAngles()); }
996 * Specifies the linear gain multiplier when the listener is outside of the
997 * source's outer cone area. The specified gain applies to all frequencies,
998 * while gainhf applies extra attenuation to high frequencies creating a
999 * low-pass effect.
1001 * \param gainhf has no effect without the ALC_EXT_EFX extension.
1003 void setOuterConeGains(ALfloat gain, ALfloat gainhf=1.0f);
1004 std::pair<ALfloat,ALfloat> getOuterConeGains() const;
1005 ALfloat getOuterConeGain() const { return std::get<0>(getOuterConeGains()); }
1006 ALfloat getOuterConeGainHF() const { return std::get<1>(getOuterConeGains()); }
1009 * Specifies the rolloff factors for the direct and send paths. This is
1010 * effectively a distance scaling relative to the reference distance. Note:
1011 * the room rolloff factor is 0 by default, disabling distance attenuation
1012 * for send paths. This is because the reverb engine will, by default,
1013 * apply a more realistic room decay based on the reverb decay time and
1014 * distance.
1016 void setRolloffFactors(ALfloat factor, ALfloat roomfactor=0.0f);
1017 std::pair<ALfloat,ALfloat> getRolloffFactors() const;
1018 ALfloat getRolloffFactor() const { return std::get<0>(getRolloffFactors()); }
1019 ALfloat getRoomRolloffFactor() const { return std::get<1>(getRolloffFactors()); }
1022 * Specifies the doppler factor for the doppler effect's pitch shift. This
1023 * effectively scales the source and listener velocities for the doppler
1024 * calculation.
1026 void setDopplerFactor(ALfloat factor);
1027 ALfloat getDopplerFactor() const;
1030 * Specifies if the source's position, velocity, and direction/orientation
1031 * are relative to the listener.
1033 void setRelative(bool relative);
1034 bool getRelative() const;
1037 * Specifies the source's radius. This causes the source to behave as if
1038 * every point within the spherical area emits sound.
1040 * Has no effect without the AL_EXT_SOURCE_RADIUS extension.
1042 void setRadius(ALfloat radius);
1043 ALfloat getRadius() const;
1046 * Specifies the left and right channel angles, in radians, when playing a
1047 * stereo buffer or stream. The angles go counter-clockwise, with 0 being
1048 * in front and positive values going left.
1050 * Has no effect without the AL_EXT_STEREO_ANGLES extension.
1052 void setStereoAngles(ALfloat leftAngle, ALfloat rightAngle);
1053 std::pair<ALfloat,ALfloat> getStereoAngles() const;
1056 * Specifies if the source always has 3D spatialization features (On),
1057 * never has 3D spatialization features (Off), or if spatialization is
1058 * enabled based on playing a mono sound or not (Auto, default).
1060 * Has no effect without the AL_SOFT_source_spatialize extension.
1062 void set3DSpatialize(Spatialize spatialize);
1063 Spatialize get3DSpatialize() const;
1066 * Specifies the index of the resampler to use for this source. The index
1067 * is from the resamplers returned by \c Context::getAvailableResamplers,
1068 * and must be 0 or greater.
1070 * Has no effect without the AL_SOFT_source_resampler extension.
1072 void setResamplerIndex(ALsizei index);
1073 ALsizei getResamplerIndex() const;
1076 * Specifies a multiplier for the amount of atmospheric high-frequency
1077 * absorption, ranging from 0 to 10. A factor of 1 results in a nominal
1078 * -0.05dB per meter, with higher values simulating foggy air and lower
1079 * values simulating dryer air. The default is 0.
1081 void setAirAbsorptionFactor(ALfloat factor);
1082 ALfloat getAirAbsorptionFactor() const;
1085 * Specifies to automatically apply adjustments to the direct path's high-
1086 * frequency gain, and the send paths' gain and high-frequency gain. The
1087 * default is true for all.
1089 void setGainAuto(bool directhf, bool send, bool sendhf);
1090 std::tuple<bool,bool,bool> getGainAuto() const;
1091 bool getDirectGainHFAuto() const { return std::get<0>(getGainAuto()); }
1092 bool getSendGainAuto() const { return std::get<1>(getGainAuto()); }
1093 bool getSendGainHFAuto() const { return std::get<2>(getGainAuto()); }
1095 /** Sets the filter properties on the direct path signal. */
1096 void setDirectFilter(const FilterParams &filter);
1098 * Sets the filter properties on the given send path signal. Any auxiliary
1099 * effect slot on the send path remains in place.
1101 void setSendFilter(ALuint send, const FilterParams &filter);
1103 * Connects the effect slot to the given send path. Any filter properties
1104 * on the send path remain as they were.
1106 void setAuxiliarySend(AuxiliaryEffectSlot slot, ALuint send);
1108 * Connects the effect slot to the given send path, using the filter
1109 * properties.
1111 void setAuxiliarySendFilter(AuxiliaryEffectSlot slot, ALuint send, const FilterParams &filter);
1114 * Releases the source, stopping playback, releasing resources, and
1115 * returning it to the system.
1117 void release();
1121 class ALURE_API SourceGroup {
1122 MAKE_PIMPL(SourceGroup, SourceGroupImpl)
1124 public:
1125 /** Retrieves the associated name of the source group. */
1126 StringView getName() const;
1129 * Adds this source group as a subgroup of the specified source group. This
1130 * method will throw an exception if this group is being added to a group
1131 * it has as a sub-group (i.e. it would create a circular sub-group chain).
1133 void setParentGroup(SourceGroup group);
1135 /** Retrieves the source group this source group is a child of. */
1136 SourceGroup getParentGroup() const;
1138 /** Returns the list of sources currently in the group. */
1139 Vector<Source> getSources() const;
1141 /** Returns the list of subgroups currently in the group. */
1142 Vector<SourceGroup> getSubGroups() const;
1145 * Sets the source group gain, which accumulates with its sources' and
1146 * sub-groups' gain.
1148 void setGain(ALfloat gain);
1149 /** Gets the source group gain. */
1150 ALfloat getGain() const;
1153 * Sets the source group pitch, which accumulates with its sources' and
1154 * sub-groups' pitch.
1156 void setPitch(ALfloat pitch);
1157 /** Gets the source group pitch. */
1158 ALfloat getPitch() const;
1161 * Pauses all currently-playing sources that are under this group,
1162 * including sub-groups.
1164 void pauseAll() const;
1166 * Resumes all paused sources that are under this group, including
1167 * sub-groups.
1169 void resumeAll() const;
1171 /** Stops all sources that are under this group, including sub-groups. */
1172 void stopAll() const;
1175 * Releases the source group, removing all sources from it before being
1176 * freed.
1178 void release();
1182 struct SourceSend {
1183 Source mSource;
1184 ALuint mSend;
1187 class ALURE_API AuxiliaryEffectSlot {
1188 MAKE_PIMPL(AuxiliaryEffectSlot, AuxiliaryEffectSlotImpl)
1190 public:
1191 void setGain(ALfloat gain);
1193 * If set to true, the reverb effect will automatically apply adjustments
1194 * to the source's send slot gains based on the effect properties.
1196 * Has no effect when using non-reverb effects. Default is true.
1198 void setSendAuto(bool sendauto);
1201 * Updates the effect slot with a new effect. The given effect object may
1202 * be altered or destroyed without affecting the effect slot.
1204 void applyEffect(Effect effect);
1207 * Releases the effect slot, returning it to the system. It must not be in
1208 * use by a source.
1210 void release();
1213 * Retrieves each Source object and its pairing send this effect slot is
1214 * set on. Setting a different (or null) effect slot on each source's given
1215 * send will allow the effect slot to be released.
1217 Vector<SourceSend> getSourceSends() const;
1219 /** Determines if the effect slot is in use by a source. */
1220 bool isInUse() const;
1224 class ALURE_API Effect {
1225 MAKE_PIMPL(Effect, EffectImpl)
1227 public:
1229 * Updates the effect with the specified reverb properties. If the
1230 * EAXReverb effect is not supported, it will automatically attempt to
1231 * downgrade to the Standard Reverb effect.
1233 void setReverbProperties(const EFXEAXREVERBPROPERTIES &props);
1235 void destroy();
1240 * Audio decoder interface. Applications may derive from this, implementing the
1241 * necessary methods, and use it in places the API wants a Decoder object.
1243 class ALURE_API Decoder {
1244 public:
1245 virtual ~Decoder();
1247 /** Retrieves the sample frequency, in hz, of the audio being decoded. */
1248 virtual ALuint getFrequency() const = 0;
1249 /** Retrieves the channel configuration of the audio being decoded. */
1250 virtual ChannelConfig getChannelConfig() const = 0;
1251 /** Retrieves the sample type of the audio being decoded. */
1252 virtual SampleType getSampleType() const = 0;
1255 * Retrieves the total length of the audio, in sample frames. If unknown,
1256 * returns 0. Note that if the returned length is 0, the decoder may not be
1257 * used to load a Buffer.
1259 virtual uint64_t getLength() const = 0;
1261 * Seek to pos, specified in sample frames. Returns true if the seek was
1262 * successful.
1264 virtual bool seek(uint64_t pos) = 0;
1267 * Retrieves the loop points, in sample frames, as a [start,end) pair. If
1268 * start >= end, all available samples are included in the loop.
1270 virtual std::pair<uint64_t,uint64_t> getLoopPoints() const = 0;
1273 * Decodes count sample frames, writing them to ptr, and returns the number
1274 * of sample frames written. Returning less than the requested count
1275 * indicates the end of the audio.
1277 virtual ALuint read(ALvoid *ptr, ALuint count) = 0;
1281 * Audio decoder factory interface. Applications may derive from this,
1282 * implementing the necessary methods, and use it in places the API wants a
1283 * DecoderFactory object.
1285 class ALURE_API DecoderFactory {
1286 public:
1287 virtual ~DecoderFactory();
1290 * Creates and returns a Decoder instance for the given resource file. If
1291 * the decoder needs to retain the file handle for reading as-needed, it
1292 * should move the UniquePtr to internal storage.
1294 * \return nullptr if a decoder can't be created from the file.
1296 virtual SharedPtr<Decoder> createDecoder(UniquePtr<std::istream> &file) = 0;
1300 * Registers a decoder factory for decoding audio. Registered factories are
1301 * used in lexicographical order, e.g. if Factory1 is registered with name1 and
1302 * Factory2 is registered with name2, Factory1 will be used before Factory2 if
1303 * name1 < name2. Internal decoder factories are always used after registered
1304 * ones.
1306 * Alure retains a reference to the DecoderFactory instance and will release it
1307 * (destructing the object) when the library unloads.
1309 * \param name A unique name identifying this decoder factory.
1310 * \param factory A DecoderFactory instance used to create Decoder instances.
1312 ALURE_API void RegisterDecoder(StringView name, UniquePtr<DecoderFactory> factory);
1315 * Unregisters a decoder factory by name. Alure returns the instance back to
1316 * the application.
1318 * \param name The unique name identifying a previously-registered decoder
1319 * factory.
1321 * \return The unregistered decoder factory instance, or 0 (nullptr) if a
1322 * decoder factory with the given name doesn't exist.
1324 ALURE_API UniquePtr<DecoderFactory> UnregisterDecoder(StringView name);
1328 * A file I/O factory interface. Applications may derive from this and set an
1329 * instance to be used by the audio decoders. By default, the library uses
1330 * standard I/O.
1332 class ALURE_API FileIOFactory {
1333 public:
1335 * Sets the factory instance to be used by the audio decoders. If a
1336 * previous factory was set, it's returned to the application. Passing in a
1337 * nullptr reverts to the default.
1339 static UniquePtr<FileIOFactory> set(UniquePtr<FileIOFactory> factory);
1342 * Gets the current FileIOFactory instance being used by the audio
1343 * decoders.
1345 static FileIOFactory &get();
1347 virtual ~FileIOFactory();
1349 /** Opens a read-only binary file for the given name. */
1350 virtual UniquePtr<std::istream> openFile(const String &name) = 0;
1355 * A message handler interface. Applications may derive from this and set an
1356 * instance on a context to receive messages. The base methods are no-ops, so
1357 * derived classes only need to implement methods for relevant messages.
1359 * It's recommended that applications mark their handler methods using the
1360 * override keyword, to ensure they're properly overriding the base methods in
1361 * case they change.
1363 class ALURE_API MessageHandler {
1364 public:
1365 virtual ~MessageHandler();
1368 * Called when the given device has been disconnected and is no longer
1369 * usable for output. As per the ALC_EXT_disconnect specification,
1370 * disconnected devices remain valid, however all playing sources are
1371 * automatically stopped, any sources that are attempted to play will
1372 * immediately stop, and new contexts may not be created on the device.
1374 * Note that connection status is checked during Context::update calls, so
1375 * that method must be called regularly to be notified when a device is
1376 * disconnected. This method may not be called if the device lacks support
1377 * for the ALC_EXT_disconnect extension.
1379 virtual void deviceDisconnected(Device device);
1382 * Called when the given source reaches the end of the buffer or stream.
1384 * Sources that stopped automatically will be detected upon a call to
1385 * Context::update.
1387 virtual void sourceStopped(Source source);
1390 * Called when the given source was forced to stop. This can be because
1391 * either there were no more mixing sources and a higher-priority source
1392 * preempted it, or it's part of a SourceGroup (or sub-group thereof) that
1393 * had its SourceGroup::stopAll method called.
1395 virtual void sourceForceStopped(Source source);
1398 * Called when a new buffer is about to be created and loaded. May be
1399 * called asynchronously for buffers being loaded asynchronously.
1401 * \param name The resource name, as passed to Context::getBuffer.
1402 * \param channels Channel configuration of the given audio data.
1403 * \param type Sample type of the given audio data.
1404 * \param samplerate Sample rate of the given audio data.
1405 * \param data The audio data that is about to be fed to the OpenAL buffer.
1407 virtual void bufferLoading(StringView name, ChannelConfig channels, SampleType type, ALuint samplerate, ArrayView<ALbyte> data);
1410 * Called when a resource isn't found, allowing the app to substitute in a
1411 * different resource. For buffers being cached, the original name will
1412 * still be used for the cache entry so the app doesn't have to keep track
1413 * of substituted resource names.
1415 * This will be called again if the new name also isn't found.
1417 * \param name The resource name that was not found.
1418 * \return The replacement resource name to use instead. Returning an empty
1419 * string means to stop trying.
1421 virtual String resourceNotFound(StringView name);
1424 #undef MAKE_PIMPL
1426 } // namespace alure
1428 #endif /* AL_ALURE2_H */