Add a bool operator to AutoObj
[alure.git] / include / AL / alure2.h
blob75a0dde76b892fd2ff0229eb3cabd12209a78495
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 */
32 #ifndef ALURE_TEMPLATE
33 #ifndef ALURE_STATIC_LIB
34 #define ALURE_TEMPLATE extern template
35 #else
36 #define ALURE_TEMPLATE template
37 #endif
38 #endif /* ALURE_TEMPLATE */
40 #ifndef EFXEAXREVERBPROPERTIES_DEFINED
41 #define EFXEAXREVERBPROPERTIES_DEFINED
42 typedef struct {
43 float flDensity;
44 float flDiffusion;
45 float flGain;
46 float flGainHF;
47 float flGainLF;
48 float flDecayTime;
49 float flDecayHFRatio;
50 float flDecayLFRatio;
51 float flReflectionsGain;
52 float flReflectionsDelay;
53 float flReflectionsPan[3];
54 float flLateReverbGain;
55 float flLateReverbDelay;
56 float flLateReverbPan[3];
57 float flEchoTime;
58 float flEchoDepth;
59 float flModulationTime;
60 float flModulationDepth;
61 float flAirAbsorptionGainHF;
62 float flHFReference;
63 float flLFReference;
64 float flRoomRolloffFactor;
65 int iDecayHFLimit;
66 } EFXEAXREVERBPROPERTIES, *LPEFXEAXREVERBPROPERTIES;
67 #endif
69 #ifndef EFXCHORUSPROPERTIES_DEFINED
70 #define EFXCHORUSPROPERTIES_DEFINED
71 typedef struct {
72 int iWaveform;
73 int iPhase;
74 float flRate;
75 float flDepth;
76 float flFeedback;
77 float flDelay;
78 } EFXCHORUSPROPERTIES, *LPEFXCHORUSPROPERTIES;
79 #endif
81 namespace alure {
83 // Available class interfaces.
84 class DeviceManager;
85 class Device;
86 class Context;
87 class Listener;
88 class Buffer;
89 class Source;
90 class SourceGroup;
91 class AuxiliaryEffectSlot;
92 class Effect;
93 class Decoder;
94 class DecoderFactory;
95 class FileIOFactory;
96 class MessageHandler;
98 // Opaque class implementations.
99 class DeviceManagerImpl;
100 class DeviceImpl;
101 class ContextImpl;
102 class ListenerImpl;
103 class BufferImpl;
104 class SourceImpl;
105 class SourceGroupImpl;
106 class AuxiliaryEffectSlotImpl;
107 class EffectImpl;
111 #ifndef ALURE_STATIC_LIB
112 /****** Explicitly instantiate templates used by the lib ******/
113 ALURE_TEMPLATE class ALURE_API ALURE_SHARED_PTR_TYPE<alure::DeviceManagerImpl>;
114 /******/
115 #endif
117 namespace alure {
119 /** Convert a value from decibels to linear gain. */
120 inline float dBToLinear(float value) { return std::pow(10.0f, value / 20.0f); }
121 inline double dBToLinear(double value) { return std::pow(10.0, value / 20.0); }
122 inline double dBToLinear(int value) { return dBToLinear(double(value)); }
124 /** Convert a value from linear gain to decibels. */
125 inline float LinearTodB(float value) { return std::log10(value) * 20.0f; }
126 inline double LinearTodB(double value) { return std::log10(value) * 20.0; }
129 * An attribute pair, for passing attributes to Device::createContext and
130 * Device::reset.
132 using AttributePair = std::pair<ALCint,ALCint>;
133 static_assert(sizeof(AttributePair) == sizeof(ALCint[2]), "Bad AttributePair size");
134 inline AttributePair AttributesEnd() noexcept { return std::make_pair(0, 0); }
137 struct FilterParams {
138 ALfloat mGain;
139 ALfloat mGainHF; // For low-pass and band-pass filters
140 ALfloat mGainLF; // For high-pass and band-pass filters
144 class Vector3 {
145 Array<ALfloat,3> mValue;
147 public:
148 constexpr Vector3() noexcept
149 : mValue{{0.0f, 0.0f, 0.0f}}
151 constexpr Vector3(const Vector3 &rhs) noexcept
152 : mValue{{rhs.mValue[0], rhs.mValue[1], rhs.mValue[2]}}
154 constexpr Vector3(ALfloat val) noexcept
155 : mValue{{val, val, val}}
157 constexpr Vector3(ALfloat x, ALfloat y, ALfloat z) noexcept
158 : mValue{{x, y, z}}
160 Vector3(const ALfloat *vec) noexcept
161 : mValue{{vec[0], vec[1], vec[2]}}
164 const ALfloat *getPtr() const noexcept
165 { return mValue.data(); }
167 ALfloat& operator[](size_t i) noexcept
168 { return mValue[i]; }
169 constexpr const ALfloat& operator[](size_t i) const noexcept
170 { return mValue[i]; }
172 #define ALURE_DECL_OP(op) \
173 constexpr Vector3 operator op(const Vector3 &rhs) const noexcept \
175 return Vector3(mValue[0] op rhs.mValue[0], \
176 mValue[1] op rhs.mValue[1], \
177 mValue[2] op rhs.mValue[2]); \
179 ALURE_DECL_OP(+)
180 ALURE_DECL_OP(-)
181 ALURE_DECL_OP(*)
182 ALURE_DECL_OP(/)
183 #undef ALURE_DECL_OP
184 #define ALURE_DECL_OP(op) \
185 Vector3& operator op(const Vector3 &rhs) noexcept \
187 mValue[0] op rhs.mValue[0]; \
188 mValue[1] op rhs.mValue[1]; \
189 mValue[2] op rhs.mValue[2]; \
190 return *this; \
192 ALURE_DECL_OP(+=)
193 ALURE_DECL_OP(-=)
194 ALURE_DECL_OP(*=)
195 ALURE_DECL_OP(/=)
197 #undef ALURE_DECL_OP
198 #define ALURE_DECL_OP(op) \
199 constexpr Vector3 operator op(ALfloat scale) const noexcept \
201 return Vector3(mValue[0] op scale, \
202 mValue[1] op scale, \
203 mValue[2] op scale); \
205 ALURE_DECL_OP(*)
206 ALURE_DECL_OP(/)
207 #undef ALURE_DECL_OP
208 #define ALURE_DECL_OP(op) \
209 Vector3& operator op(ALfloat scale) noexcept \
211 mValue[0] op scale; \
212 mValue[1] op scale; \
213 mValue[2] op scale; \
214 return *this; \
216 ALURE_DECL_OP(*=)
217 ALURE_DECL_OP(/=)
218 #undef ALURE_DECL_OP
220 constexpr ALfloat getLengthSquared() const noexcept
221 { return mValue[0]*mValue[0] + mValue[1]*mValue[1] + mValue[2]*mValue[2]; }
222 ALfloat getLength() const noexcept
223 { return std::sqrt(getLengthSquared()); }
225 constexpr ALfloat getDistanceSquared(const Vector3 &pos) const noexcept
226 { return (pos - *this).getLengthSquared(); }
227 ALfloat getDistance(const Vector3 &pos) const noexcept
228 { return (pos - *this).getLength(); }
230 static_assert(sizeof(Vector3) == sizeof(ALfloat[3]), "Bad Vector3 size");
233 enum class SampleType {
234 UInt8,
235 Int16,
236 Float32,
237 Mulaw
239 ALURE_API const char *GetSampleTypeName(SampleType type);
241 enum class ChannelConfig {
242 /** 1-channel mono sound. */
243 Mono,
244 /** 2-channel stereo sound. */
245 Stereo,
246 /** 2-channel rear sound (back-left and back-right). */
247 Rear,
248 /** 4-channel surround sound. */
249 Quad,
250 /** 5.1 surround sound. */
251 X51,
252 /** 6.1 surround sound. */
253 X61,
254 /** 7.1 surround sound. */
255 X71,
256 /** 3-channel B-Format, using FuMa channel ordering and scaling. */
257 BFormat2D,
258 /** 4-channel B-Format, using FuMa channel ordering and scaling. */
259 BFormat3D
261 ALURE_API const char *GetChannelConfigName(ChannelConfig cfg);
263 ALURE_API ALuint FramesToBytes(ALuint frames, ChannelConfig chans, SampleType type);
264 ALURE_API ALuint BytesToFrames(ALuint bytes, ChannelConfig chans, SampleType type) noexcept;
267 /** Class for storing a major.minor version number. */
268 class Version {
269 ALuint mMajor : 16;
270 ALuint mMinor : 16;
272 public:
273 constexpr Version() noexcept : mMajor(0), mMinor(0) { }
274 constexpr Version(ALuint _maj, ALuint _min) noexcept : mMajor(_maj), mMinor(_min) { }
275 constexpr Version(const Version&) noexcept = default;
277 constexpr ALuint getMajor() const noexcept { return mMajor; }
278 constexpr ALuint getMinor() const noexcept { return mMinor; }
280 constexpr bool operator==(const Version &rhs) const noexcept
281 { return mMajor == rhs.mMajor && mMinor == rhs.mMinor; }
282 constexpr bool operator!=(const Version &rhs) const noexcept
283 { return !(*this == rhs); }
284 constexpr bool operator<=(const Version &rhs) const noexcept
285 { return mMajor < rhs.mMajor || (mMajor == rhs.mMajor && mMinor <= rhs.mMinor); }
286 constexpr bool operator>=(const Version &rhs) const noexcept
287 { return mMajor > rhs.mMajor || (mMajor == rhs.mMajor && mMinor >= rhs.mMinor); }
288 constexpr bool operator<(const Version &rhs) const noexcept
289 { return mMajor < rhs.mMajor || (mMajor == rhs.mMajor && mMinor < rhs.mMinor); }
290 constexpr bool operator>(const Version &rhs) const noexcept
291 { return mMajor > rhs.mMajor || (mMajor == rhs.mMajor && mMinor > rhs.mMinor); }
293 constexpr bool isZero() const noexcept { return *this == Version{0,0}; }
297 // Tag type to disctate which types are allowed in AutoObj.
298 template<typename T> struct IsAutoable : std::false_type { };
299 template<> struct IsAutoable<Context> : std::true_type { };
300 template<> struct IsAutoable<Source> : std::true_type { };
301 template<> struct IsAutoable<SourceGroup> : std::true_type { };
302 template<> struct IsAutoable<AuxiliaryEffectSlot> : std::true_type { };
303 template<> struct IsAutoable<Effect> : std::true_type { };
306 * A local storage container to manage objects in a non-copyable, movable, and
307 * auto-destructed manner. Any contained object will have its destroy() method
308 * invoked prior to being overwritten or when going out of scope. The purpose
309 * of this is to optionally provide RAII semantics to Alure's resources, such
310 * as contexts, sources, and effects.
312 * Be aware that destruction order is important, as contexts ultimately "own"
313 * the resources created from them. Said resources automatically become invalid
314 * when their owning context is destroyed. Any AutoObjs containing sources,
315 * effects, etc, should already be destroyed or cleared prior to the context
316 * being destroyed.
318 * Also, it is possible for resource destruction to fail if the destroy()
319 * method is called incorrectly (e.g. destroying a source when a different
320 * context is current). This normally results in an exception, but because
321 * destructors aren't allowed to let exceptions leave the function body,
322 * std::terminate will be called as a fatal error instead.
324 template<typename T>
325 class AutoObj {
326 static_assert(IsAutoable<T>::value, "Invalid type for AutoObj");
328 T mObj;
330 public:
331 using element_type = T;
333 AutoObj() noexcept = default;
334 AutoObj(const AutoObj&) = delete;
335 AutoObj(AutoObj &&rhs) noexcept : mObj(rhs.mObj) { rhs.mObj = nullptr; }
336 AutoObj(std::nullptr_t) noexcept : mObj(nullptr) { }
337 explicit AutoObj(const element_type &rhs) noexcept : mObj(rhs) { }
338 ~AutoObj() { if(mObj) mObj.destroy(); }
340 AutoObj& operator=(const AutoObj&) = delete;
341 AutoObj& operator=(AutoObj &&rhs)
343 if(mObj) mObj.destroy();
344 mObj = rhs.mObj;
345 rhs.mObj = nullptr;
346 return *this;
349 AutoObj& reset(const element_type &obj)
351 if(mObj) mObj.destroy();
352 mObj = obj;
353 return *this;
356 element_type release() noexcept
358 element_type ret = mObj;
359 mObj = nullptr;
360 return ret;
363 element_type& get() noexcept { return mObj; }
365 element_type& operator*() noexcept { return mObj; }
366 element_type* operator->() noexcept { return &mObj; }
368 operator bool() const noexcept { return static_cast<bool>(mObj); }
371 /** Creates an AutoObj for the given input object type. */
372 template<typename T>
373 inline AutoObj<T> MakeAuto(const T &obj) { return AutoObj<T>(obj); }
376 enum class DeviceEnumeration {
377 Basic = ALC_DEVICE_SPECIFIER,
378 Full = ALC_ALL_DEVICES_SPECIFIER,
379 Capture = ALC_CAPTURE_DEVICE_SPECIFIER
382 enum class DefaultDeviceType {
383 Basic = ALC_DEFAULT_DEVICE_SPECIFIER,
384 Full = ALC_DEFAULT_ALL_DEVICES_SPECIFIER,
385 Capture = ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER
389 * A class managing Device objects and other related functionality. This class
390 * is a singleton, only one instance will exist in a process at a time.
392 class ALURE_API DeviceManager {
393 SharedPtr<DeviceManagerImpl> pImpl;
395 DeviceManager(SharedPtr<DeviceManagerImpl>&& impl) noexcept;
397 public:
399 * Retrieves a reference-counted DeviceManager instance. When the last
400 * reference goes out of scope, the DeviceManager and any remaining managed
401 * resources are automatically cleaned up. Multiple calls will return the
402 * same instance as long as there is still a pre-existing reference to the
403 * instance, or else a new instance will be created.
405 static DeviceManager getInstance();
407 DeviceManager() noexcept = default;
408 DeviceManager(const DeviceManager&) noexcept = default;
409 DeviceManager(DeviceManager&& rhs) noexcept = default;
410 ~DeviceManager();
412 DeviceManager& operator=(const DeviceManager&) noexcept = default;
413 DeviceManager& operator=(DeviceManager&&) noexcept = default;
414 DeviceManager& operator=(std::nullptr_t) noexcept { pImpl = nullptr; return *this; };
416 operator bool() const noexcept { return pImpl != nullptr; }
418 /** Queries the existence of a non-device-specific ALC extension. */
419 bool queryExtension(const String &name) const;
420 bool queryExtension(const char *name) const;
422 /** Enumerates available device names of the given type. */
423 Vector<String> enumerate(DeviceEnumeration type) const;
424 /** Retrieves the default device of the given type. */
425 String defaultDeviceName(DefaultDeviceType type) const;
428 * Opens the playback device given by name, or the default if blank. Throws
429 * an exception on error.
431 Device openPlayback(const String &name={});
432 Device openPlayback(const char *name);
435 * Opens the playback device given by name, or the default if blank.
436 * Returns an empty Device on error.
438 Device openPlayback(const String &name, const std::nothrow_t&) noexcept;
439 Device openPlayback(const char *name, const std::nothrow_t&) noexcept;
441 /** Opens the default playback device. Returns an empty Device on error. */
442 Device openPlayback(const std::nothrow_t&) noexcept;
446 #define MAKE_PIMPL(BaseT, ImplT) \
447 private: \
448 ImplT *pImpl; \
450 public: \
451 using handle_type = ImplT*; \
453 BaseT() noexcept : pImpl(nullptr) { } \
454 BaseT(ImplT *impl) noexcept : pImpl(impl) { } \
455 BaseT(const BaseT&) noexcept = default; \
456 BaseT(BaseT&& rhs) noexcept : pImpl(rhs.pImpl) { rhs.pImpl = nullptr; } \
458 BaseT& operator=(const BaseT&) noexcept = default; \
459 BaseT& operator=(BaseT&& rhs) noexcept \
461 pImpl = rhs.pImpl; rhs.pImpl = nullptr; \
462 return *this; \
465 bool operator==(const BaseT &rhs) const noexcept \
466 { return pImpl == rhs.pImpl; } \
467 bool operator!=(const BaseT &rhs) const noexcept \
468 { return pImpl != rhs.pImpl; } \
469 bool operator<=(const BaseT &rhs) const noexcept \
470 { return pImpl <= rhs.pImpl; } \
471 bool operator>=(const BaseT &rhs) const noexcept \
472 { return pImpl >= rhs.pImpl; } \
473 bool operator<(const BaseT &rhs) const noexcept \
474 { return pImpl < rhs.pImpl; } \
475 bool operator>(const BaseT &rhs) const noexcept \
476 { return pImpl > rhs.pImpl; } \
478 operator bool() const noexcept { return !!pImpl; } \
480 handle_type getHandle() const noexcept { return pImpl; }
482 enum class PlaybackName {
483 Basic = ALC_DEVICE_SPECIFIER,
484 Full = ALC_ALL_DEVICES_SPECIFIER
487 class ALURE_API Device {
488 MAKE_PIMPL(Device, DeviceImpl)
490 public:
491 /** Retrieves the device name as given by type. */
492 String getName(PlaybackName type=PlaybackName::Full) const;
493 /** Queries the existence of an ALC extension on this device. */
494 bool queryExtension(const String &name) const;
495 bool queryExtension(const char *name) const;
497 /** Retrieves the ALC version supported by this device. */
498 Version getALCVersion() const;
501 * Retrieves the EFX version supported by this device. If the ALC_EXT_EFX
502 * extension is unsupported, this will be 0.0.
504 Version getEFXVersion() const;
506 /** Retrieves the device's playback frequency, in hz. */
507 ALCuint getFrequency() const;
510 * Retrieves the maximum number of auxiliary source sends. If ALC_EXT_EFX
511 * is unsupported, this will be 0.
513 ALCuint getMaxAuxiliarySends() const;
516 * Enumerates available HRTF names. The names are sorted as OpenAL gives
517 * them, such that the index of a given name is the ID to use with
518 * ALC_HRTF_ID_SOFT.
520 * If the ALC_SOFT_HRTF extension is unavailable, this will return an empty
521 * vector.
523 Vector<String> enumerateHRTFNames() const;
526 * Retrieves whether HRTF is enabled on the device or not.
528 * If the ALC_SOFT_HRTF extension is unavailable, this will return false
529 * although there could still be HRTF applied at a lower hardware level.
531 bool isHRTFEnabled() const;
534 * Retrieves the name of the HRTF currently being used by this device.
536 * If HRTF is not currently enabled, this will be empty.
538 String getCurrentHRTF() const;
541 * Resets the device, using the specified attributes.
543 * If the ALC_SOFT_HRTF extension is unavailable, this will be a no-op.
545 void reset(ArrayView<AttributePair> attributes);
548 * Creates a new Context on this device, using the specified attributes.
549 * Throws an exception if context creation fails.
551 Context createContext(ArrayView<AttributePair> attributes={});
553 * Creates a new Context on this device, using the specified attributes.
554 * Returns an empty Context if context creation fails.
556 Context createContext(ArrayView<AttributePair> attributes, const std::nothrow_t&) noexcept;
557 Context createContext(const std::nothrow_t&) noexcept;
560 * Pauses device processing, stopping updates for its contexts. Multiple
561 * calls are allowed but it is not reference counted, so the device will
562 * resume after one resumeDSP call.
564 * Requires the ALC_SOFT_pause_device extension.
566 void pauseDSP();
569 * Resumes device processing, restarting updates for its contexts. Multiple
570 * calls are allowed and will no-op.
572 void resumeDSP();
575 * Retrieves the current clock time for the device. This starts relative to
576 * the device being opened, and does not increment while there are no
577 * contexts nor while processing is paused. This is currently based on
578 * std::chrono::steady_clock, and so may not exactly match the rate that
579 * sources play at. In the future it may utilize an OpenAL extension to
580 * retrieve the audio device's real clock which may tic at a subtly
581 * different rate than the main clock(s).
583 std::chrono::nanoseconds getClockTime();
586 * Closes and frees the device. All previously-created contexts must first
587 * be destroyed.
589 void close();
593 enum class DistanceModel {
594 InverseClamped = AL_INVERSE_DISTANCE_CLAMPED,
595 LinearClamped = AL_LINEAR_DISTANCE_CLAMPED,
596 ExponentClamped = AL_EXPONENT_DISTANCE_CLAMPED,
597 Inverse = AL_INVERSE_DISTANCE,
598 Linear = AL_LINEAR_DISTANCE,
599 Exponent = AL_EXPONENT_DISTANCE,
600 None = AL_NONE,
603 class ALURE_API Context {
604 MAKE_PIMPL(Context, ContextImpl)
606 public:
607 /** Makes the specified context current for OpenAL operations. */
608 static void MakeCurrent(Context context);
609 /** Retrieves the current context used for OpenAL operations. */
610 static Context GetCurrent();
613 * Makes the specified context current for OpenAL operations on the calling
614 * thread only. Requires the ALC_EXT_thread_local_context extension on both
615 * the context's device and the DeviceManager.
617 static void MakeThreadCurrent(Context context);
618 /** Retrieves the thread-specific context used for OpenAL operations. */
619 static Context GetThreadCurrent();
622 * Destroys the context. The context must not be current when this is
623 * called.
625 void destroy();
627 /** Retrieves the Device this context was created from. */
628 Device getDevice();
630 void startBatch();
631 void endBatch();
634 * Retrieves a Listener instance for this context. Each context will only
635 * have one listener, which is automatically destroyed with the context.
637 Listener getListener();
640 * Sets a MessageHandler instance which will be used to provide certain
641 * messages back to the application. Only one handler may be set for a
642 * context at a time. The previously set handler will be returned.
644 SharedPtr<MessageHandler> setMessageHandler(SharedPtr<MessageHandler> handler);
646 /** Gets the currently-set message handler. */
647 SharedPtr<MessageHandler> getMessageHandler() const;
650 * Specifies the desired interval that the background thread will be woken
651 * up to process tasks, e.g. keeping streaming sources filled. An interval
652 * of 0 means the background thread will only be woken up manually with
653 * calls to update. The default is 0.
655 void setAsyncWakeInterval(std::chrono::milliseconds interval);
658 * Retrieves the current interval used for waking up the background thread.
660 std::chrono::milliseconds getAsyncWakeInterval() const;
662 // Functions below require the context to be current
665 * Creates a Decoder instance for the given audio file or resource name.
667 SharedPtr<Decoder> createDecoder(StringView name);
670 * Queries if the channel configuration and sample type are supported by
671 * the context.
673 bool isSupported(ChannelConfig channels, SampleType type) const;
676 * Queries the list of resamplers supported by the context. If the
677 * AL_SOFT_source_resampler extension is unsupported this will be an empty
678 * array, otherwise there will be at least one entry.
680 ArrayView<String> getAvailableResamplers();
682 * Queries the context's default resampler index. Be aware, if the
683 * AL_SOFT_source_resampler extension is unsupported the resampler list
684 * will be empty and this will resturn 0. If you try to access the
685 * resampler list with this index without the extension, undefined behavior
686 * will occur (accessing an out of bounds array index).
688 ALsizei getDefaultResamplerIndex() const;
691 * Creates and caches a Buffer for the given audio file or resource name.
692 * Multiple calls with the same name will return the same Buffer object.
693 * Cached buffers must be freed using removeBuffer before destroying the
694 * context. If the buffer can't be loaded it will throw an exception.
696 Buffer getBuffer(StringView name);
699 * Asynchronously prepares a cached Buffer for the given audio file or
700 * resource name. Multiple calls with the same name will return multiple
701 * SharedFutures for the same Buffer object. Once called, the buffer must
702 * be freed using removeBuffer before destroying the context, even if you
703 * never get the Buffer from the SharedFuture.
705 * The Buffer will be scheduled to load asynchronously, and the caller gets
706 * back a SharedFuture that can be checked later (or waited on) to get the
707 * actual Buffer when it's ready. The application must take care to handle
708 * exceptions from the SharedFuture in case an unrecoverable error ocurred
709 * during the load.
711 * If the Buffer is already fully loaded and cached, a SharedFuture is
712 * returned in a ready state containing it.
714 SharedFuture<Buffer> getBufferAsync(StringView name);
717 * Asynchronously prepares cached Buffers for the given audio file or
718 * resource names. Duplicate names and buffers already cached are ignored.
719 * Cached buffers must be freed using removeBuffer before destroying the
720 * context.
722 * The Buffer objects will be scheduled for loading asynchronously, and
723 * should be retrieved later when needed using getBufferAsync or getBuffer.
724 * Buffers that cannot be loaded, for example due to an unsupported format,
725 * will be ignored and a later call to getBuffer or getBufferAsync will
726 * throw an exception.
728 void precacheBuffersAsync(ArrayView<StringView> names);
731 * Creates and caches a Buffer using the given name by reading the given
732 * decoder. The name may alias an audio file, but it must not currently
733 * exist in the buffer cache.
735 Buffer createBufferFrom(StringView name, SharedPtr<Decoder> decoder);
738 * Asynchronously prepares a cached Buffer using the given name by reading
739 * the given decoder. The name may alias an audio file, but it must not
740 * currently exist in the buffer cache. Once called, the buffer must be
741 * freed using removeBuffer before destroying the context, even if you
742 * never get the Buffer from the SharedFuture.
744 * The Buffer will be scheduled to load asynchronously, and the caller gets
745 * back a SharedFuture that can be checked later (or waited on) to get the
746 * actual Buffer when it's ready. The application must take care to handle
747 * exceptions from the SharedFuture in case an unrecoverable error ocurred
748 * during the load. The decoder must not have its read or seek methods
749 * called while the buffer is not ready.
751 SharedFuture<Buffer> createBufferAsyncFrom(StringView name, SharedPtr<Decoder> decoder);
754 * Looks for a cached buffer using the given name and returns it. If the
755 * given name does not exist in the cache, a null buffer is returned.
757 Buffer findBuffer(StringView name);
760 * Looks for an asynchronously-loading buffer using the given name and
761 * returns a SharedFuture for it. If the given name does not exist in the
762 * cache, an invalid SharedFuture is returned (check with a call to
763 * \c SharedFuture::valid).
765 * If the Buffer is already fully loaded and cached, a SharedFuture is
766 * returned in a ready state containing it.
768 SharedFuture<Buffer> findBufferAsync(StringView name);
771 * Deletes the cached Buffer object for the given audio file or resource
772 * name, invalidating all Buffer objects with this name. If a source is
773 * currently playing the buffer, it will be stopped first.
775 void removeBuffer(StringView name);
777 * Deletes the given cached buffer, invalidating all other Buffer objects
778 * with the same name. Equivalent to calling
779 * removeBuffer(buffer.getName()).
781 void removeBuffer(Buffer buffer);
784 * Creates a new Source for playing audio. There is no practical limit to
785 * the number of sources you may create. You must call Source::destroy when
786 * the source is no longer needed.
788 Source createSource();
790 AuxiliaryEffectSlot createAuxiliaryEffectSlot();
792 Effect createEffect();
794 SourceGroup createSourceGroup();
796 /** Sets the doppler factor to apply to all source doppler calculations. */
797 void setDopplerFactor(ALfloat factor);
800 * Sets the speed of sound propagation, in units per second, to calculate
801 * the doppler effect along with other distance-related time effects. The
802 * default is 343.3 units per second (a realistic speed assuming 1 meter
803 * per unit). If this is adjusted for a different unit scale,
804 * Listener::setMetersPerUnit should also be adjusted.
806 void setSpeedOfSound(ALfloat speed);
809 * Sets the distance model used to attenuate sources given their distance
810 * from the listener. The default, InverseClamped, provides a realistic 1/r
811 * reduction in volume (that is, every doubling of distance causes the gain
812 * to reduce by half).
814 * The Clamped distance models restrict the source distance for the purpose
815 * of distance attenuation, so a source won't sound closer than its
816 * reference distance or farther than its max distance.
818 void setDistanceModel(DistanceModel model);
820 /** Updates the context and all sources belonging to this context. */
821 void update();
824 class ALURE_API Listener {
825 MAKE_PIMPL(Listener, ListenerImpl)
827 public:
828 /** Sets the "master" gain for all context output. */
829 void setGain(ALfloat gain);
832 * Specifies the listener's 3D position, velocity, and orientation
833 * together (see: setPosition, setVelocity, and setOrientation).
835 void set3DParameters(const Vector3 &position, const Vector3 &velocity, const std::pair<Vector3,Vector3> &orientation);
837 /** Specifies the listener's 3D position. */
838 void setPosition(const Vector3 &position);
839 void setPosition(const ALfloat *pos);
842 * Specifies the listener's 3D velocity, in units per second. As with
843 * OpenAL, this does not actually alter the listener's position, and
844 * instead just alters the pitch as determined by the doppler effect.
846 void setVelocity(const Vector3 &velocity);
847 void setVelocity(const ALfloat *vel);
850 * Specifies the listener's 3D orientation, using position-relative 'at'
851 * and 'up' direction vectors.
853 void setOrientation(const std::pair<Vector3,Vector3> &orientation);
854 void setOrientation(const ALfloat *at, const ALfloat *up);
855 void setOrientation(const ALfloat *ori);
858 * Sets the number of meters per unit, used for various effects that rely
859 * on the distance in meters including air absorption and initial reverb
860 * decay. If this is changed, it's strongly recommended to also set the
861 * speed of sound (e.g. context.setSpeedOfSound(343.3 / m_u) to maintain a
862 * realistic 343.3m/s for sound propagation).
864 void setMetersPerUnit(ALfloat m_u);
868 class ALURE_API Buffer {
869 MAKE_PIMPL(Buffer, BufferImpl)
871 public:
872 /** Retrieves the length of the buffer in sample frames. */
873 ALuint getLength() const;
875 /** Retrieves the buffer's frequency in hz. */
876 ALuint getFrequency() const;
878 /** Retrieves the buffer's sample configuration. */
879 ChannelConfig getChannelConfig() const;
881 /** Retrieves the buffer's sample type. */
882 SampleType getSampleType() const;
885 * Retrieves the storage size used by the buffer, in bytes. Note that the
886 * size in bytes may not be what you expect from the length, as it may take
887 * more space internally than the ChannelConfig and SampleType suggest to
888 * be more efficient.
890 ALuint getSize() const;
893 * Sets the buffer's loop points, used for looping sources. If the current
894 * context does not support the AL_SOFT_loop_points extension, start and
895 * end must be 0 and getLength() respectively. Otherwise, start must be
896 * less than end, and end must be less than or equal to getLength().
898 * The buffer must not be in use when this method is called.
900 * \param start The starting point, in sample frames (inclusive).
901 * \param end The ending point, in sample frames (exclusive).
903 void setLoopPoints(ALuint start, ALuint end);
905 /** Retrieves the current loop points as a [start,end) pair. */
906 std::pair<ALuint,ALuint> getLoopPoints() const;
908 /** Retrieves the Source objects currently playing the buffer. */
909 Vector<Source> getSources() const;
911 /** Retrieves the name the buffer was created with. */
912 StringView getName() const;
915 * Queries the number of sources currently using the buffer. Be aware that
916 * you need to call \c Context::update to reliably ensure the count is kept
917 * updated for when sources reach their end. This is equivalent to calling
918 * getSources().size().
920 size_t getSourceCount() const;
924 enum class Spatialize {
925 Off = AL_FALSE,
926 On = AL_TRUE,
927 Auto = 0x0002 /* AL_AUTO_SOFT */
930 class ALURE_API Source {
931 MAKE_PIMPL(Source, SourceImpl)
933 public:
935 * Plays the source using a buffer. The same buffer may be played from
936 * multiple sources simultaneously.
938 void play(Buffer buffer);
940 * Plays the source by asynchronously streaming audio from a decoder. The
941 * given decoder must *NOT* have its read or seek methods called from
942 * elsewhere while in use.
944 * \param decoder The decoder object to play audio from.
945 * \param chunk_len The number of sample frames to read for each chunk
946 * update. Smaller values will require more frequent updates and
947 * larger values will handle more data with each chunk.
948 * \param queue_size The number of chunks to keep queued during playback.
949 * Smaller values use less memory while larger values improve
950 * protection against underruns.
952 void play(SharedPtr<Decoder> decoder, ALsizei chunk_len, ALsizei queue_size);
955 * Prepares to play a source using a future buffer. The method will return
956 * right away and the source will begin playing once the future buffer
957 * becomes ready. If the future buffer is already ready, it begins playing
958 * immediately as if you called play(future_buffer.get()).
960 * The future buffer is checked during calls to \c Context::update and the
961 * source will start playback once the future buffer reports it's ready.
962 * Use the isPending method to check if the source is still waiting for the
963 * future buffer.
965 void play(SharedFuture<Buffer> future_buffer);
968 * Stops playback, releasing the buffer or decoder reference. Any pending
969 * playback from a future buffer is canceled.
971 void stop();
974 * Fades the source to the specified gain over the given duration, at which
975 * point playback will stop. This gain is in addition to the base gain, and
976 * must be greater than 0 and less than 1. The duration must also be
977 * greater than 0.
979 * The fading is logarithmic. As a result, the initial drop-off may happen
980 * faster than expected but the fading is more perceptually consistant over
981 * the given duration. It will take just as much time to go from -6dB to
982 * -12dB as it will to go from -40dB to -46dB, for example.
984 * Pending playback from a future buffer is not immediately canceled, but
985 * the fade timer starts with this call. If the future buffer then becomes
986 * ready, it will start mid-fade. Pending playback will be canceled if the
987 * fade out completes before the future buffer becomes ready.
989 * Fading is updated during calls to \c Context::update, which should be
990 * called regularly (30 to 50 times per second) for the fading to be
991 * smooth.
993 void fadeOutToStop(ALfloat gain, std::chrono::milliseconds duration);
995 /** Pauses the source if it is playing. */
996 void pause();
998 /** Resumes the source if it is paused. */
999 void resume();
1001 /** Specifies if the source is waiting to play a future buffer. */
1002 bool isPending() const;
1004 /** Specifies if the source is currently playing. */
1005 bool isPlaying() const;
1007 /** Specifies if the source is currently paused. */
1008 bool isPaused() const;
1011 * Specifies if the source is currently playing or waiting to play a future
1012 * buffer.
1014 bool isPlayingOrPending() const;
1017 * Sets this source as a child of the given source group. The given source
1018 * group's parameters will influence this and all other sources that belong
1019 * to it. A source can only be the child of one source group at a time,
1020 * although that source group may belong to another source group.
1022 * Passing in a null group removes it from its current source group.
1024 void setGroup(SourceGroup group);
1026 /** Retrieves the source group this source belongs to. */
1027 SourceGroup getGroup() const;
1030 * Specifies the source's playback priority. The lowest priority sources
1031 * will be forcefully stopped when no more mixing sources are available and
1032 * higher priority sources are played.
1034 void setPriority(ALuint priority);
1035 /** Retrieves the source's priority. */
1036 ALuint getPriority() const;
1039 * Sets the source's offset, in sample frames. If the source is playing or
1040 * paused, it will go to that offset immediately, otherwise the source will
1041 * start at the specified offset the next time it's played.
1043 void setOffset(uint64_t offset);
1045 * Retrieves the source offset in sample frames and its latency in nano-
1046 * seconds. For streaming sources this will be the offset based on the
1047 * decoder's read position.
1049 * If the AL_SOFT_source_latency extension is unsupported, the latency will
1050 * be 0.
1052 std::pair<uint64_t,std::chrono::nanoseconds> getSampleOffsetLatency() const;
1053 uint64_t getSampleOffset() const { return std::get<0>(getSampleOffsetLatency()); }
1055 * Retrieves the source offset and latency in seconds. For streaming
1056 * sources this will be the offset based on the decoder's read position.
1058 * If the AL_SOFT_source_latency extension is unsupported, the latency will
1059 * be 0.
1061 std::pair<Seconds,Seconds> getSecOffsetLatency() const;
1062 Seconds getSecOffset() const { return std::get<0>(getSecOffsetLatency()); }
1065 * Specifies if the source should loop on the Buffer or Decoder object's
1066 * loop points.
1068 void setLooping(bool looping);
1069 bool getLooping() const;
1072 * Specifies a linear pitch shift base. A value of 1.0 is the default
1073 * normal speed.
1075 void setPitch(ALfloat pitch);
1076 ALfloat getPitch() const;
1079 * Specifies the base linear gain. A value of 1.0 is the default normal
1080 * volume.
1082 void setGain(ALfloat gain);
1083 ALfloat getGain() const;
1086 * Specifies the minimum and maximum gain. The source's gain is clamped to
1087 * this range after distance attenuation and cone attenuation are applied
1088 * to the gain base, although before the filter gain adjustements.
1090 void setGainRange(ALfloat mingain, ALfloat maxgain);
1091 std::pair<ALfloat,ALfloat> getGainRange() const;
1092 ALfloat getMinGain() const { return std::get<0>(getGainRange()); }
1093 ALfloat getMaxGain() const { return std::get<1>(getGainRange()); }
1096 * Specifies the reference distance and maximum distance the source will
1097 * use for the current distance model. For Clamped distance models, the
1098 * source's calculated distance is clamped to the specified range before
1099 * applying distance-related attenuation.
1101 * For all distance models, the reference distance is the distance at which
1102 * the source's volume will not have any extra attenuation (an effective
1103 * gain multiplier of 1).
1105 void setDistanceRange(ALfloat refdist, ALfloat maxdist);
1106 std::pair<ALfloat,ALfloat> getDistanceRange() const;
1107 ALfloat getReferenceDistance() const { return std::get<0>(getDistanceRange()); }
1108 ALfloat getMaxDistance() const { return std::get<1>(getDistanceRange()); }
1111 * Specifies the source's 3D position, velocity, and direction together
1112 * (see: setPosition, setVelocity, and setDirection).
1114 void set3DParameters(const Vector3 &position, const Vector3 &velocity, const Vector3 &direction);
1117 * Specifies the source's 3D position, velocity, and orientation together
1118 * (see: setPosition, setVelocity, and setOrientation).
1120 void set3DParameters(const Vector3 &position, const Vector3 &velocity, const std::pair<Vector3,Vector3> &orientation);
1122 /** Specifies the source's 3D position. */
1123 void setPosition(const Vector3 &position);
1124 void setPosition(const ALfloat *pos);
1125 Vector3 getPosition() const;
1128 * Specifies the source's 3D velocity, in units per second. As with OpenAL,
1129 * this does not actually alter the source's position, and instead just
1130 * alters the pitch as determined by the doppler effect.
1132 void setVelocity(const Vector3 &velocity);
1133 void setVelocity(const ALfloat *vel);
1134 Vector3 getVelocity() const;
1137 * Specifies the source's 3D facing direction. Deprecated in favor of
1138 * setOrientation.
1140 void setDirection(const Vector3 &direction);
1141 void setDirection(const ALfloat *dir);
1142 Vector3 getDirection() const;
1145 * Specifies the source's 3D orientation, using position-relative 'at' and
1146 * 'up' direction vectors. Note: unlike the AL_EXT_BFORMAT extension this
1147 * property comes from, this also affects the facing direction, superceding
1148 * setDirection.
1150 void setOrientation(const std::pair<Vector3,Vector3> &orientation);
1151 void setOrientation(const ALfloat *at, const ALfloat *up);
1152 void setOrientation(const ALfloat *ori);
1153 std::pair<Vector3,Vector3> getOrientation() const;
1156 * Specifies the source's cone angles, in degrees. The inner angle is the
1157 * area within which the listener will hear the source with no extra
1158 * attenuation, while the listener being outside of the outer angle will
1159 * hear the source attenuated according to the outer cone gains. The area
1160 * follows the facing direction, so for example an inner angle of 180 means
1161 * the entire front face of the source is in the inner cone.
1163 void setConeAngles(ALfloat inner, ALfloat outer);
1164 std::pair<ALfloat,ALfloat> getConeAngles() const;
1165 ALfloat getInnerConeAngle() const { return std::get<0>(getConeAngles()); }
1166 ALfloat getOuterConeAngle() const { return std::get<1>(getConeAngles()); }
1169 * Specifies the linear gain multiplier when the listener is outside of the
1170 * source's outer cone area. The specified gain applies to all frequencies,
1171 * while gainhf applies extra attenuation to high frequencies creating a
1172 * low-pass effect.
1174 * \param gainhf has no effect without the ALC_EXT_EFX extension.
1176 void setOuterConeGains(ALfloat gain, ALfloat gainhf=1.0f);
1177 std::pair<ALfloat,ALfloat> getOuterConeGains() const;
1178 ALfloat getOuterConeGain() const { return std::get<0>(getOuterConeGains()); }
1179 ALfloat getOuterConeGainHF() const { return std::get<1>(getOuterConeGains()); }
1182 * Specifies the rolloff factors for the direct and send paths. This is
1183 * effectively a distance scaling relative to the reference distance. Note:
1184 * the room rolloff factor is 0 by default, disabling distance attenuation
1185 * for send paths. This is because the reverb engine will, by default,
1186 * apply a more realistic room decay based on the reverb decay time and
1187 * distance.
1189 void setRolloffFactors(ALfloat factor, ALfloat roomfactor=0.0f);
1190 std::pair<ALfloat,ALfloat> getRolloffFactors() const;
1191 ALfloat getRolloffFactor() const { return std::get<0>(getRolloffFactors()); }
1192 ALfloat getRoomRolloffFactor() const { return std::get<1>(getRolloffFactors()); }
1195 * Specifies the doppler factor for the doppler effect's pitch shift. This
1196 * effectively scales the source and listener velocities for the doppler
1197 * calculation.
1199 void setDopplerFactor(ALfloat factor);
1200 ALfloat getDopplerFactor() const;
1203 * Specifies if the source's position, velocity, and direction/orientation
1204 * are relative to the listener.
1206 void setRelative(bool relative);
1207 bool getRelative() const;
1210 * Specifies the source's radius. This causes the source to behave as if
1211 * every point within the spherical area emits sound.
1213 * Has no effect without the AL_EXT_SOURCE_RADIUS extension.
1215 void setRadius(ALfloat radius);
1216 ALfloat getRadius() const;
1219 * Specifies the left and right channel angles, in radians, when playing a
1220 * stereo buffer or stream. The angles go counter-clockwise, with 0 being
1221 * in front and positive values going left.
1223 * Has no effect without the AL_EXT_STEREO_ANGLES extension.
1225 void setStereoAngles(ALfloat leftAngle, ALfloat rightAngle);
1226 std::pair<ALfloat,ALfloat> getStereoAngles() const;
1229 * Specifies if the source always has 3D spatialization features (On),
1230 * never has 3D spatialization features (Off), or if spatialization is
1231 * enabled based on playing a mono sound or not (Auto, default).
1233 * Has no effect without the AL_SOFT_source_spatialize extension.
1235 void set3DSpatialize(Spatialize spatialize);
1236 Spatialize get3DSpatialize() const;
1239 * Specifies the index of the resampler to use for this source. The index
1240 * is from the resamplers returned by \c Context::getAvailableResamplers,
1241 * and must be 0 or greater.
1243 * Has no effect without the AL_SOFT_source_resampler extension.
1245 void setResamplerIndex(ALsizei index);
1246 ALsizei getResamplerIndex() const;
1249 * Specifies a multiplier for the amount of atmospheric high-frequency
1250 * absorption, ranging from 0 to 10. A factor of 1 results in a nominal
1251 * -0.05dB per meter, with higher values simulating foggy air and lower
1252 * values simulating dryer air. The default is 0.
1254 void setAirAbsorptionFactor(ALfloat factor);
1255 ALfloat getAirAbsorptionFactor() const;
1258 * Specifies to automatically apply adjustments to the direct path's high-
1259 * frequency gain, and the send paths' gain and high-frequency gain. The
1260 * default is true for all.
1262 void setGainAuto(bool directhf, bool send, bool sendhf);
1263 std::tuple<bool,bool,bool> getGainAuto() const;
1264 bool getDirectGainHFAuto() const { return std::get<0>(getGainAuto()); }
1265 bool getSendGainAuto() const { return std::get<1>(getGainAuto()); }
1266 bool getSendGainHFAuto() const { return std::get<2>(getGainAuto()); }
1268 /** Sets the filter properties on the direct path signal. */
1269 void setDirectFilter(const FilterParams &filter);
1271 * Sets the filter properties on the given send path signal. Any auxiliary
1272 * effect slot on the send path remains in place.
1274 void setSendFilter(ALuint send, const FilterParams &filter);
1276 * Connects the effect slot to the given send path. Any filter properties
1277 * on the send path remain as they were.
1279 void setAuxiliarySend(AuxiliaryEffectSlot slot, ALuint send);
1281 * Connects the effect slot to the given send path, using the filter
1282 * properties.
1284 void setAuxiliarySendFilter(AuxiliaryEffectSlot slot, ALuint send, const FilterParams &filter);
1286 /** Destroys the source, stopping playback and releasing resources. */
1287 void destroy();
1291 class ALURE_API SourceGroup {
1292 MAKE_PIMPL(SourceGroup, SourceGroupImpl)
1294 public:
1296 * Adds this source group as a subgroup of the specified source group. This
1297 * method will throw an exception if this group is being added to a group
1298 * it has as a sub-group (i.e. it would create a circular sub-group chain).
1300 void setParentGroup(SourceGroup group);
1302 /** Retrieves the source group this source group is a child of. */
1303 SourceGroup getParentGroup() const;
1305 /** Returns the list of sources currently in the group. */
1306 Vector<Source> getSources() const;
1308 /** Returns the list of subgroups currently in the group. */
1309 Vector<SourceGroup> getSubGroups() const;
1312 * Sets the source group gain, which accumulates with its sources' and
1313 * sub-groups' gain.
1315 void setGain(ALfloat gain);
1316 /** Gets the source group gain. */
1317 ALfloat getGain() const;
1320 * Sets the source group pitch, which accumulates with its sources' and
1321 * sub-groups' pitch.
1323 void setPitch(ALfloat pitch);
1324 /** Gets the source group pitch. */
1325 ALfloat getPitch() const;
1328 * Pauses all currently-playing sources that are under this group,
1329 * including sub-groups.
1331 void pauseAll() const;
1333 * Resumes all paused sources that are under this group, including
1334 * sub-groups.
1336 void resumeAll() const;
1338 /** Stops all sources that are under this group, including sub-groups. */
1339 void stopAll() const;
1342 * Destroys the source group, removing all sources from it before being
1343 * freed.
1345 void destroy();
1349 struct SourceSend {
1350 Source mSource;
1351 ALuint mSend;
1354 class ALURE_API AuxiliaryEffectSlot {
1355 MAKE_PIMPL(AuxiliaryEffectSlot, AuxiliaryEffectSlotImpl)
1357 public:
1358 void setGain(ALfloat gain);
1360 * If set to true, the reverb effect will automatically apply adjustments
1361 * to the source's send slot gains based on the effect properties.
1363 * Has no effect when using non-reverb effects. Default is true.
1365 void setSendAuto(bool sendauto);
1368 * Updates the effect slot with a new effect. The given effect object may
1369 * be altered or destroyed without affecting the effect slot.
1371 void applyEffect(Effect effect);
1374 * Destroys the effect slot, returning it to the system. If the effect slot
1375 * is currently set on a source send, it will be removed first.
1377 void destroy();
1380 * Retrieves each Source object and its pairing send this effect slot is
1381 * set on.
1383 Vector<SourceSend> getSourceSends() const;
1386 * Queries the number of source sends the effect slot is used by. This is
1387 * equivalent to calling getSourceSends().size().
1389 size_t getUseCount() const;
1393 class ALURE_API Effect {
1394 MAKE_PIMPL(Effect, EffectImpl)
1396 public:
1398 * Updates the effect with the specified reverb properties. If the
1399 * EAXReverb effect is not supported, it will automatically attempt to
1400 * downgrade to the Standard Reverb effect.
1402 void setReverbProperties(const EFXEAXREVERBPROPERTIES &props);
1405 * Updates the effect with the specified chorus properties. If the chorus
1406 * effect is not supported, an exception will be thrown.
1408 void setChorusProperties(const EFXCHORUSPROPERTIES &props);
1410 void destroy();
1415 * Audio decoder interface. Applications may derive from this, implementing the
1416 * necessary methods, and use it in places the API wants a Decoder object.
1418 class ALURE_API Decoder {
1419 public:
1420 virtual ~Decoder();
1422 /** Retrieves the sample frequency, in hz, of the audio being decoded. */
1423 virtual ALuint getFrequency() const noexcept = 0;
1424 /** Retrieves the channel configuration of the audio being decoded. */
1425 virtual ChannelConfig getChannelConfig() const noexcept = 0;
1426 /** Retrieves the sample type of the audio being decoded. */
1427 virtual SampleType getSampleType() const noexcept = 0;
1430 * Retrieves the total length of the audio, in sample frames. If unknown,
1431 * returns 0. Note that if the returned length is 0, the decoder may not be
1432 * used to load a Buffer.
1434 virtual uint64_t getLength() const noexcept = 0;
1436 * Seek to pos, specified in sample frames. Returns true if the seek was
1437 * successful.
1439 virtual bool seek(uint64_t pos) noexcept = 0;
1442 * Retrieves the loop points, in sample frames, as a [start,end) pair. If
1443 * start >= end, all available samples are included in the loop.
1445 virtual std::pair<uint64_t,uint64_t> getLoopPoints() const noexcept = 0;
1448 * Decodes count sample frames, writing them to ptr, and returns the number
1449 * of sample frames written. Returning less than the requested count
1450 * indicates the end of the audio.
1452 virtual ALuint read(ALvoid *ptr, ALuint count) noexcept = 0;
1456 * Audio decoder factory interface. Applications may derive from this,
1457 * implementing the necessary methods, and use it in places the API wants a
1458 * DecoderFactory object.
1460 class ALURE_API DecoderFactory {
1461 public:
1462 virtual ~DecoderFactory();
1465 * Creates and returns a Decoder instance for the given resource file. If
1466 * the decoder needs to retain the file handle for reading as-needed, it
1467 * should move the UniquePtr to internal storage.
1469 * \return nullptr if a decoder can't be created from the file.
1471 virtual SharedPtr<Decoder> createDecoder(UniquePtr<std::istream> &file) noexcept = 0;
1475 * Registers a decoder factory for decoding audio. Registered factories are
1476 * used in lexicographical order, e.g. if Factory1 is registered with name1 and
1477 * Factory2 is registered with name2, Factory1 will be used before Factory2 if
1478 * name1 < name2. Internal decoder factories are always used after registered
1479 * ones.
1481 * Alure retains a reference to the DecoderFactory instance and will release it
1482 * (destructing the object) when the library unloads.
1484 * \param name A unique name identifying this decoder factory.
1485 * \param factory A DecoderFactory instance used to create Decoder instances.
1487 ALURE_API void RegisterDecoder(StringView name, UniquePtr<DecoderFactory> factory);
1490 * Unregisters a decoder factory by name. Alure returns the instance back to
1491 * the application.
1493 * \param name The unique name identifying a previously-registered decoder
1494 * factory.
1496 * \return The unregistered decoder factory instance, or 0 (nullptr) if a
1497 * decoder factory with the given name doesn't exist.
1499 ALURE_API UniquePtr<DecoderFactory> UnregisterDecoder(StringView name) noexcept;
1503 * A file I/O factory interface. Applications may derive from this and set an
1504 * instance to be used by the audio decoders. By default, the library uses
1505 * standard I/O.
1507 class ALURE_API FileIOFactory {
1508 public:
1510 * Sets the factory instance to be used by the audio decoders. If a
1511 * previous factory was set, it's returned to the application. Passing in a
1512 * nullptr reverts to the default.
1514 static UniquePtr<FileIOFactory> set(UniquePtr<FileIOFactory> factory) noexcept;
1517 * Gets the current FileIOFactory instance being used by the audio
1518 * decoders.
1520 static FileIOFactory &get() noexcept;
1522 virtual ~FileIOFactory();
1524 /** Opens a read-only binary file for the given name. */
1525 virtual UniquePtr<std::istream> openFile(const String &name) noexcept = 0;
1530 * A message handler interface. Applications may derive from this and set an
1531 * instance on a context to receive messages. The base methods are no-ops, so
1532 * derived classes only need to implement methods for relevant messages.
1534 * It's recommended that applications mark their handler methods using the
1535 * override keyword, to ensure they're properly overriding the base methods in
1536 * case they change.
1538 class ALURE_API MessageHandler {
1539 public:
1540 virtual ~MessageHandler();
1543 * Called when the given device has been disconnected and is no longer
1544 * usable for output. As per the ALC_EXT_disconnect specification,
1545 * disconnected devices remain valid, however all playing sources are
1546 * automatically stopped, any sources that are attempted to play will
1547 * immediately stop, and new contexts may not be created on the device.
1549 * Note that connection status is checked during Context::update calls, so
1550 * that method must be called regularly to be notified when a device is
1551 * disconnected. This method may not be called if the device lacks support
1552 * for the ALC_EXT_disconnect extension.
1554 virtual void deviceDisconnected(Device device) noexcept;
1557 * Called when the given source reaches the end of the buffer or stream.
1559 * Sources that stopped automatically will be detected upon a call to
1560 * Context::update.
1562 virtual void sourceStopped(Source source) noexcept;
1565 * Called when the given source was forced to stop. This can be because
1566 * either there were no more mixing sources and a higher-priority source
1567 * preempted it, it's part of a SourceGroup (or sub-group thereof) that had
1568 * its SourceGroup::stopAll method called, or it was playing a buffer
1569 * that's getting removed.
1571 virtual void sourceForceStopped(Source source) noexcept;
1574 * Called when a new buffer is about to be created and loaded. May be
1575 * called asynchronously for buffers being loaded asynchronously.
1577 * \param name The resource name, as passed to Context::getBuffer.
1578 * \param channels Channel configuration of the given audio data.
1579 * \param type Sample type of the given audio data.
1580 * \param samplerate Sample rate of the given audio data.
1581 * \param data The audio data that is about to be fed to the OpenAL buffer.
1583 virtual void bufferLoading(StringView name, ChannelConfig channels, SampleType type, ALuint samplerate, ArrayView<ALbyte> data) noexcept;
1586 * Called when a resource isn't found, allowing the app to substitute in a
1587 * different resource. For buffers being cached, the original name will
1588 * still be used for the cache entry so the app doesn't have to keep track
1589 * of substituted resource names.
1591 * This will be called again if the new name also isn't found.
1593 * \param name The resource name that was not found.
1594 * \return The replacement resource name to use instead. Returning an empty
1595 * string means to stop trying.
1597 virtual String resourceNotFound(StringView name) noexcept;
1600 #undef MAKE_PIMPL
1602 } // namespace alure
1604 #endif /* AL_ALURE2_H */