Take String refs for functions that construct Strings anyway
[alure.git] / include / AL / alure2.h
blob7ef98246aaa3cfa1b05805bbe7c5ae8dc1215a4f
1 #ifndef AL_ALURE2_H
2 #define AL_ALURE2_H
4 #include <vector>
5 #include <string>
6 #include <memory>
7 #include <cstring>
8 #include <utility>
9 #include <future>
10 #include <chrono>
11 #include <array>
12 #include <cmath>
14 #include "alc.h"
15 #include "al.h"
17 #ifndef ALURE_API
18 #if defined(ALURE_STATIC_LIB)
19 #define ALURE_API
20 #elif defined(_WIN32)
21 #define ALURE_API __declspec(dllimport)
22 #elif defined(__GNUC__) || (defined(__has_attribute) && __has_attribute(visibility))
23 #define ALURE_API __attribute__((visibility("default")))
24 #else
25 #define ALURE_API
26 #endif
27 #endif /* ALURE_API */
29 #ifndef EFXEAXREVERBPROPERTIES_DEFINED
30 #define EFXEAXREVERBPROPERTIES_DEFINED
31 typedef struct {
32 float flDensity;
33 float flDiffusion;
34 float flGain;
35 float flGainHF;
36 float flGainLF;
37 float flDecayTime;
38 float flDecayHFRatio;
39 float flDecayLFRatio;
40 float flReflectionsGain;
41 float flReflectionsDelay;
42 float flReflectionsPan[3];
43 float flLateReverbGain;
44 float flLateReverbDelay;
45 float flLateReverbPan[3];
46 float flEchoTime;
47 float flEchoDepth;
48 float flModulationTime;
49 float flModulationDepth;
50 float flAirAbsorptionGainHF;
51 float flHFReference;
52 float flLFReference;
53 float flRoomRolloffFactor;
54 int iDecayHFLimit;
55 } EFXEAXREVERBPROPERTIES, *LPEFXEAXREVERBPROPERTIES;
56 #endif
58 namespace alure {
60 class DeviceManager;
61 class DeviceManagerImpl;
62 class Device;
63 class DeviceImpl;
64 class Context;
65 class ContextImpl;
66 class Listener;
67 class ListenerImpl;
68 class Buffer;
69 class BufferImpl;
70 class Source;
71 class SourceImpl;
72 class SourceGroup;
73 class SourceGroupImpl;
74 class AuxiliaryEffectSlot;
75 class AuxiliaryEffectSlotImpl;
76 class Effect;
77 class EffectImpl;
78 class Decoder;
79 class DecoderFactory;
80 class MessageHandler;
82 // Convenience aliases
83 template<typename T> using RemoveRefT = typename std::remove_reference<T>::type;
84 template<bool B> using EnableIfT = typename std::enable_if<B>::type;
87 // Duration in seconds, using double precision
88 using Seconds = std::chrono::duration<double>;
90 // A SharedPtr implementation, defaults to C++11's std::shared_ptr. If this is
91 // changed, you must recompile the library.
92 template<typename... Args> using SharedPtr = std::shared_ptr<Args...>;
93 template<typename T, typename... Args>
94 constexpr inline SharedPtr<T> MakeShared(Args&&... args)
96 return std::make_shared<T>(std::forward<Args>(args)...);
99 // A UniquePtr implementation, defaults to C++11's std::unique_ptr. If this is
100 // changed, you must recompile the library.
101 template<typename... Args> using UniquePtr = std::unique_ptr<Args...>;
102 template<typename T, typename... Args>
103 constexpr inline UniquePtr<T> MakeUnique(Args&&... args)
105 #if __cplusplus >= 201402L
106 return std::make_unique<T>(std::forward<Args>(args)...);
107 #else
108 return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
109 #endif
112 // A Promise/Future (+SharedFuture) implementation, defaults to C++11's
113 // std::promise, std::future, and std::shared_future. If this is changed, you
114 // must recompile the library.
115 template<typename... Args> using Promise = std::promise<Args...>;
116 template<typename... Args> using Future = std::future<Args...>;
117 template<typename... Args> using SharedFuture = std::shared_future<Args...>;
119 // A Vector implementation, defaults to C++'s std::vector. If this is changed,
120 // you must recompile the library.
121 template<typename... Args> using Vector = std::vector<Args...>;
123 // A static-sized Array implementation, defaults to C++11's std::array. If this
124 // is changed, you must recompile the library.
125 template<typename T, std::size_t N> using Array = std::array<T, N>;
127 // A String implementation, default's to C++'s std::string. If this is changed,
128 // you must recompile the library.
129 template<typename... Args> using BasicString = std::basic_string<Args...>;
130 using String = BasicString<std::string::value_type>;
132 // Tag specific containers that guarantee contiguous storage. The standard
133 // provides no such mechanism, so we have to manually specify which are
134 // acceptable.
135 template<typename T> struct IsContiguousTag : std::false_type {};
136 template<typename T, size_t N> struct IsContiguousTag<Array<T,N>> : std::true_type {};
137 template<typename T> struct IsContiguousTag<Vector<T>> : std::true_type {};
138 template<typename T> struct IsContiguousTag<BasicString<T>> : std::true_type {};
140 // A rather simple ArrayView container. This allows accepting various array
141 // types (Array, Vector, a static-sized array, a dynamic array + size) without
142 // copying its elements.
143 template<typename T>
144 class ArrayView {
145 public:
146 using value_type = T;
147 using iterator = const value_type*;
148 using const_iterator = const value_type*;
150 private:
151 const value_type *mElems;
152 size_t mNumElems;
154 public:
155 ArrayView() noexcept : mElems(nullptr), mNumElems(0) { }
156 ArrayView(const ArrayView&) noexcept = default;
157 ArrayView(ArrayView&&) noexcept = default;
158 ArrayView(const value_type *elems, size_t num_elems) noexcept
159 : mElems(elems), mNumElems(num_elems) { }
160 template<typename OtherT> ArrayView(RemoveRefT<OtherT>&&) = delete;
161 template<typename OtherT,
162 typename = EnableIfT<IsContiguousTag<RemoveRefT<OtherT>>::value>>
163 ArrayView(const OtherT &rhs) noexcept : mElems(rhs.data()), mNumElems(rhs.size()) { }
164 template<size_t N>
165 ArrayView(const value_type (&elems)[N]) noexcept : mElems(elems), mNumElems(N) { }
167 ArrayView& operator=(const ArrayView&) noexcept = default;
169 const value_type *data() const noexcept { return mElems; }
171 size_t size() const noexcept { return mNumElems; }
172 bool empty() const noexcept { return mNumElems == 0; }
174 const value_type& operator[](size_t i) const { return mElems[i]; }
176 const value_type& front() const { return mElems[0]; }
177 const value_type& back() const { return mElems[mNumElems-1]; }
179 const value_type& at(size_t i) const
181 if(i >= mNumElems)
182 throw std::out_of_range("alure::ArrayView::at: element out of range");
183 return mElems[i];
186 const_iterator begin() const noexcept { return mElems; }
187 const_iterator cbegin() const noexcept { return mElems; }
189 const_iterator end() const noexcept { return mElems + mNumElems; }
190 const_iterator cend() const noexcept { return mElems + mNumElems; }
193 template<typename T, typename Tr=std::char_traits<T>>
194 class BasicStringView : public ArrayView<T> {
195 using BaseT = ArrayView<T>;
196 using StringT = BasicString<T,Tr>;
198 public:
199 using typename BaseT::value_type;
200 using traits_type = Tr;
202 BasicStringView() noexcept = default;
203 BasicStringView(const BasicStringView&) noexcept = default;
204 BasicStringView(const value_type *elems, size_t num_elems) noexcept
205 : ArrayView<T>(elems, num_elems) { }
206 BasicStringView(const value_type *elems) : ArrayView<T>(elems, std::strlen(elems)) { }
207 BasicStringView(StringT&&) = delete;
208 BasicStringView(const StringT &rhs) noexcept : ArrayView<T>(rhs) { }
209 #if __cplusplus >= 201703L
210 BasicStringView(const std::basic_string_view<T> &rhs) noexcept
211 : ArrayView<T>(rhs.data(), rhs.length()) { }
212 #endif
214 BasicStringView& operator=(const BasicStringView&) noexcept = default;
216 size_t length() const { return BaseT::size(); }
218 explicit operator StringT() const { return StringT(BaseT::data(), length()); }
219 #if __cplusplus >= 201703L
220 operator std::basic_string_view<T,Tr>() const noexcept
221 { return std::basic_string_view<T,Tr>(BaseT::data(), length()); }
222 #endif
224 StringT operator+(const StringT &rhs) const
226 StringT ret = StringT(*this);
227 ret += rhs;
228 return ret;
230 StringT operator+(const typename StringT::value_type *rhs) const
232 StringT ret = StringT(*this);
233 ret += rhs;
234 return ret;
237 int compare(BasicStringView other) const noexcept
239 int ret = traits_type::compare(
240 BaseT::data(), other.data(), std::min<size_t>(length(), other.length())
242 if(ret == 0)
244 if(length() > other.length())
245 return 1;
246 if(length() < other.length())
247 return -1;
248 return 0;
250 return ret;
252 bool operator==(BasicStringView rhs) const noexcept
253 { return compare(rhs) == 0; }
254 bool operator!=(BasicStringView rhs) const noexcept
255 { return compare(rhs) != 0; }
257 using StringView = BasicStringView<String::value_type>;
259 // Inline operators to concat String and C-style strings with StringViews.
260 template<typename T, typename Tr>
261 inline BasicString<T,Tr> operator+(const BasicString<T,Tr> &lhs, BasicStringView<T,Tr> rhs)
262 { return BasicString<T,Tr>(lhs).append(rhs.data(), rhs.size()); }
263 template<typename T, typename Tr>
264 inline BasicString<T,Tr> operator+(BasicString<T,Tr> lhs, BasicStringView<T,Tr> rhs)
265 { return std::move(lhs.append(rhs.data(), rhs.size())); }
266 template<typename T, typename Tr>
267 inline BasicString<T,Tr> operator+(const typename BasicString<T,Tr>::value_type *lhs, BasicStringView<T,Tr> rhs)
268 { return lhs + BasicString<T,Tr>(rhs); }
269 template<typename T, typename Tr>
270 inline BasicString<T,Tr>& operator+=(BasicString<T,Tr> &lhs, BasicStringView<T,Tr> rhs)
271 { return lhs.append(rhs.data(), rhs.size()); }
273 // Inline operators to compare String and C-style strings with StringViews.
274 template<typename T, typename Tr>
275 inline bool operator==(const BasicString<T,Tr> &lhs, BasicStringView<T,Tr> rhs)
276 { return BasicStringView<T,Tr>(lhs) == rhs; }
277 template<typename T, typename Tr>
278 inline bool operator!=(const BasicString<T,Tr> &lhs, BasicStringView<T,Tr> rhs)
279 { return BasicStringView<T,Tr>(lhs) != rhs; }
280 template<typename T, typename Tr>
281 inline bool operator==(const typename BasicString<T,Tr>::value_type *lhs, BasicStringView<T,Tr> rhs)
282 { return BasicStringView<T,Tr>(lhs) == rhs; }
283 template<typename T, typename Tr>
284 inline bool operator!=(const typename BasicString<T,Tr>::value_type *lhs, BasicStringView<T,Tr> rhs)
285 { return BasicStringView<T,Tr>(lhs) != rhs; }
287 // Inline operator to write out a StringView to an ostream
288 template<typename T, typename Tr>
289 inline std::basic_ostream<T>& operator<<(std::basic_ostream<T,Tr> &lhs, BasicStringView<T,Tr> rhs)
291 for(auto ch : rhs)
292 lhs << ch;
293 return lhs;
298 * An attribute pair, for passing attributes to Device::createContext and
299 * Device::reset.
301 using AttributePair = std::pair<ALCint,ALCint>;
302 static_assert(sizeof(AttributePair) == sizeof(ALCint[2]), "Bad AttributePair size");
305 struct FilterParams {
306 ALfloat mGain;
307 ALfloat mGainHF; // For low-pass and band-pass filters
308 ALfloat mGainLF; // For high-pass and band-pass filters
312 class Vector3 {
313 Array<ALfloat,3> mValue;
315 public:
316 constexpr Vector3() noexcept
317 : mValue{{0.0f, 0.0f, 0.0f}}
319 constexpr Vector3(const Vector3 &rhs) noexcept
320 : mValue{{rhs.mValue[0], rhs.mValue[1], rhs.mValue[2]}}
322 constexpr Vector3(ALfloat val) noexcept
323 : mValue{{val, val, val}}
325 constexpr Vector3(ALfloat x, ALfloat y, ALfloat z) noexcept
326 : mValue{{x, y, z}}
328 Vector3(const ALfloat *vec) noexcept
329 : mValue{{vec[0], vec[1], vec[2]}}
332 const ALfloat *getPtr() const noexcept
333 { return mValue.data(); }
335 ALfloat& operator[](size_t i) noexcept
336 { return mValue[i]; }
337 constexpr const ALfloat& operator[](size_t i) const noexcept
338 { return mValue[i]; }
340 #define ALURE_DECL_OP(op) \
341 constexpr Vector3 operator op(const Vector3 &rhs) const noexcept \
343 return Vector3(mValue[0] op rhs.mValue[0], \
344 mValue[1] op rhs.mValue[1], \
345 mValue[2] op rhs.mValue[2]); \
347 ALURE_DECL_OP(+)
348 ALURE_DECL_OP(-)
349 ALURE_DECL_OP(*)
350 ALURE_DECL_OP(/)
351 #undef ALURE_DECL_OP
352 #define ALURE_DECL_OP(op) \
353 Vector3& operator op(const Vector3 &rhs) noexcept \
355 mValue[0] op rhs.mValue[0]; \
356 mValue[1] op rhs.mValue[1]; \
357 mValue[2] op rhs.mValue[2]; \
358 return *this; \
360 ALURE_DECL_OP(+=)
361 ALURE_DECL_OP(-=)
362 ALURE_DECL_OP(*=)
363 ALURE_DECL_OP(/=)
365 #undef ALURE_DECL_OP
366 #define ALURE_DECL_OP(op) \
367 constexpr Vector3 operator op(ALfloat scale) const noexcept \
369 return Vector3(mValue[0] op scale, \
370 mValue[1] op scale, \
371 mValue[2] op scale); \
373 ALURE_DECL_OP(*)
374 ALURE_DECL_OP(/)
375 #undef ALURE_DECL_OP
376 #define ALURE_DECL_OP(op) \
377 Vector3& operator op(ALfloat scale) noexcept \
379 mValue[0] op scale; \
380 mValue[1] op scale; \
381 mValue[2] op scale; \
382 return *this; \
384 ALURE_DECL_OP(*=)
385 ALURE_DECL_OP(/=)
386 #undef ALURE_DECL_OP
388 constexpr ALfloat getLengthSquared() const noexcept
389 { return mValue[0]*mValue[0] + mValue[1]*mValue[1] + mValue[2]*mValue[2]; }
390 ALfloat getLength() const noexcept
391 { return std::sqrt(getLengthSquared()); }
393 constexpr ALfloat getDistanceSquared(const Vector3 &pos) const noexcept
394 { return (pos - *this).getLengthSquared(); }
395 ALfloat getDistance(const Vector3 &pos) const noexcept
396 { return (pos - *this).getLength(); }
398 static_assert(sizeof(Vector3) == sizeof(ALfloat[3]), "Bad Vector3 size");
401 enum class SampleType {
402 UInt8,
403 Int16,
404 Float32,
405 Mulaw
407 ALURE_API const char *GetSampleTypeName(SampleType type);
409 enum class ChannelConfig {
410 /** 1-channel mono sound. */
411 Mono,
412 /** 2-channel stereo sound. */
413 Stereo,
414 /** 2-channel rear sound (back-left and back-right). */
415 Rear,
416 /** 4-channel surround sound. */
417 Quad,
418 /** 5.1 surround sound. */
419 X51,
420 /** 6.1 surround sound. */
421 X61,
422 /** 7.1 surround sound. */
423 X71,
424 /** 3-channel B-Format, using FuMa channel ordering and scaling. */
425 BFormat2D,
426 /** 4-channel B-Format, using FuMa channel ordering and scaling. */
427 BFormat3D
429 ALURE_API const char *GetChannelConfigName(ChannelConfig cfg);
431 ALURE_API ALuint FramesToBytes(ALuint frames, ChannelConfig chans, SampleType type);
432 ALURE_API ALuint BytesToFrames(ALuint bytes, ChannelConfig chans, SampleType type);
435 /** Class for storing a major.minor version number. */
436 class Version {
437 ALuint mMajor : 16;
438 ALuint mMinor : 16;
440 public:
441 constexpr Version(ALuint _maj, ALuint _min) : mMajor(_maj), mMinor(_min) { }
443 constexpr ALuint getMajor() const noexcept { return mMajor; }
444 constexpr ALuint getMinor() const noexcept { return mMinor; }
445 constexpr bool isZero() const noexcept { return mMajor == 0 && mMinor == 0; }
448 #define MAKE_PIMPL(BaseT, ImplT) \
449 private: \
450 ImplT *pImpl; \
452 public: \
453 using handle_type = ImplT*; \
455 BaseT() : pImpl(nullptr) { } \
456 BaseT(ImplT *impl) : pImpl(impl) { } \
457 BaseT(const BaseT&) = default; \
458 BaseT(BaseT&& rhs) : pImpl(rhs.pImpl) { rhs.pImpl = nullptr; } \
460 BaseT& operator=(const BaseT&) = default; \
461 BaseT& operator=(BaseT&& rhs) \
463 pImpl = rhs.pImpl; rhs.pImpl = nullptr; \
464 return *this; \
467 bool operator==(const BaseT &rhs) const { return pImpl == rhs.pImpl; } \
468 bool operator==(BaseT&& rhs) const { return pImpl == rhs.pImpl; } \
470 operator bool() const { return !!pImpl; } \
472 handle_type getHandle() const { return pImpl; }
474 enum class DeviceEnumeration {
475 Basic = ALC_DEVICE_SPECIFIER,
476 Full = ALC_ALL_DEVICES_SPECIFIER,
477 Capture = ALC_CAPTURE_DEVICE_SPECIFIER
480 enum class DefaultDeviceType {
481 Basic = ALC_DEFAULT_DEVICE_SPECIFIER,
482 Full = ALC_DEFAULT_ALL_DEVICES_SPECIFIER,
483 Capture = ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER
487 * A class managing Device objects and other related functionality. This class
488 * is a singleton, only one instance will exist in a process.
490 class ALURE_API DeviceManager {
491 DeviceManagerImpl *pImpl;
493 DeviceManager(DeviceManagerImpl *impl) : pImpl(impl) { }
494 friend class ALDeviceManager;
496 public:
497 DeviceManager(const DeviceManager&) = default;
498 DeviceManager(DeviceManager&& rhs) : pImpl(rhs.pImpl) { }
500 /** Retrieves the DeviceManager instance. */
501 static DeviceManager get();
503 /** Queries the existence of a non-device-specific ALC extension. */
504 bool queryExtension(const String &name) const;
505 bool queryExtension(const char *name) const;
507 /** Enumerates available device names of the given type. */
508 Vector<String> enumerate(DeviceEnumeration type) const;
509 /** Retrieves the default device of the given type. */
510 String defaultDeviceName(DefaultDeviceType type) const;
513 * Opens the playback device given by name, or the default if blank. Throws
514 * an exception on error.
516 Device openPlayback(const String &name=String());
517 Device openPlayback(const char *name);
520 * Opens the playback device given by name, or the default if blank.
521 * Returns an empty Device on error.
523 Device openPlayback(const String &name, const std::nothrow_t&);
524 Device openPlayback(const char *name, const std::nothrow_t&);
526 /** Opens the default playback device. Returns an empty Device on error. */
527 Device openPlayback(const std::nothrow_t&);
531 enum class PlaybackName {
532 Basic = ALC_DEVICE_SPECIFIER,
533 Full = ALC_ALL_DEVICES_SPECIFIER
536 class ALURE_API Device {
537 MAKE_PIMPL(Device, DeviceImpl)
539 public:
540 /** Retrieves the device name as given by type. */
541 String getName(PlaybackName type=PlaybackName::Full) const;
542 /** Queries the existence of an ALC extension on this device. */
543 bool queryExtension(const String &name) const;
544 bool queryExtension(const char *name) const;
546 /** Retrieves the ALC version supported by this device. */
547 Version getALCVersion() const;
550 * Retrieves the EFX version supported by this device. If the ALC_EXT_EFX
551 * extension is unsupported, this will be 0.0.
553 Version getEFXVersion() const;
555 /** Retrieves the device's playback frequency, in hz. */
556 ALCuint getFrequency() const;
559 * Retrieves the maximum number of auxiliary source sends. If ALC_EXT_EFX
560 * is unsupported, this will be 0.
562 ALCuint getMaxAuxiliarySends() const;
565 * Enumerates available HRTF names. The names are sorted as OpenAL gives
566 * them, such that the index of a given name is the ID to use with
567 * ALC_HRTF_ID_SOFT.
569 * Requires the ALC_SOFT_HRTF extension.
571 Vector<String> enumerateHRTFNames() const;
574 * Retrieves whether HRTF is enabled on the device or not.
576 * Requires the ALC_SOFT_HRTF extension.
578 bool isHRTFEnabled() const;
581 * Retrieves the name of the HRTF currently being used by this device.
583 * Requires the ALC_SOFT_HRTF extension.
585 String getCurrentHRTF() const;
588 * Resets the device, using the specified attributes.
590 * Requires the ALC_SOFT_HRTF extension.
592 void reset(ArrayView<AttributePair> attributes);
595 * Creates a new Context on this device, using the specified attributes.
597 Context createContext(ArrayView<AttributePair> attributes=ArrayView<AttributePair>());
600 * Pauses device processing, stopping updates for its contexts. Multiple
601 * calls are allowed but it is not reference counted, so the device will
602 * resume after one resumeDSP call.
604 * Requires the ALC_SOFT_pause_device extension.
606 void pauseDSP();
609 * Resumes device processing, restarting updates for its contexts. Multiple
610 * calls are allowed and will no-op.
612 void resumeDSP();
615 * Closes and frees the device. All previously-created contexts must first
616 * be destroyed.
618 void close();
622 enum class DistanceModel {
623 InverseClamped = AL_INVERSE_DISTANCE_CLAMPED,
624 LinearClamped = AL_LINEAR_DISTANCE_CLAMPED,
625 ExponentClamped = AL_EXPONENT_DISTANCE_CLAMPED,
626 Inverse = AL_INVERSE_DISTANCE,
627 Linear = AL_LINEAR_DISTANCE,
628 Exponent = AL_EXPONENT_DISTANCE,
629 None = AL_NONE,
632 class ALURE_API Context {
633 MAKE_PIMPL(Context, ContextImpl)
635 public:
636 /** Makes the specified context current for OpenAL operations. */
637 static void MakeCurrent(Context context);
638 /** Retrieves the current context used for OpenAL operations. */
639 static Context GetCurrent();
642 * Makes the specified context current for OpenAL operations on the calling
643 * thread only. Requires the ALC_EXT_thread_local_context extension on both
644 * the context's device and the DeviceManager.
646 static void MakeThreadCurrent(Context context);
647 /** Retrieves the thread-specific context used for OpenAL operations. */
648 static Context GetThreadCurrent();
651 * Destroys the context. The context must not be current when this is
652 * called.
654 void destroy();
656 /** Retrieves the Device this context was created from. */
657 Device getDevice();
659 void startBatch();
660 void endBatch();
663 * Retrieves a Listener instance for this context. Each context will only
664 * have one listener, which is automatically destroyed with the context.
666 Listener getListener();
669 * Sets a MessageHandler instance which will be used to provide certain
670 * messages back to the application. Only one handler may be set for a
671 * context at a time. The previously set handler will be returned.
673 SharedPtr<MessageHandler> setMessageHandler(SharedPtr<MessageHandler> handler);
675 /** Gets the currently-set message handler. */
676 SharedPtr<MessageHandler> getMessageHandler() const;
679 * Specifies the desired interval that the background thread will be woken
680 * up to process tasks, e.g. keeping streaming sources filled. An interval
681 * of 0 means the background thread will only be woken up manually with
682 * calls to update. The default is 0.
684 void setAsyncWakeInterval(std::chrono::milliseconds interval);
687 * Retrieves the current interval used for waking up the background thread.
689 std::chrono::milliseconds getAsyncWakeInterval() const;
691 // Functions below require the context to be current
694 * Creates a Decoder instance for the given audio file or resource name.
696 SharedPtr<Decoder> createDecoder(StringView name);
699 * Queries if the channel configuration and sample type are supported by
700 * the context.
702 bool isSupported(ChannelConfig channels, SampleType type) const;
705 * Queries the list of resamplers supported by the context. If the
706 * AL_SOFT_source_resampler extension is unsupported this will be an empty
707 * array, otherwise there will be at least one entry.
709 ArrayView<String> getAvailableResamplers();
711 * Queries the context's default resampler index. Be aware, if the
712 * AL_SOFT_source_resampler extension is unsupported the resampler list
713 * will be empty and this will resturn 0. If you try to access the
714 * resampler list with this index without the extension, undefined behavior
715 * will occur (accessing an out of bounds array index).
717 ALsizei getDefaultResamplerIndex() const;
720 * Creates and caches a Buffer for the given audio file or resource name.
721 * Multiple calls with the same name will return the same Buffer object.
722 * Cached buffers must be freed using removeBuffer before destroying the
723 * context. If the buffer can't be loaded it will throw an exception.
725 Buffer getBuffer(StringView name);
728 * Asynchronously prepares a cached Buffer for the given audio file or
729 * resource name. Multiple calls with the same name will return multiple
730 * SharedFutures for the same Buffer object. Once called, the buffer must
731 * be freed using removeBuffer before destroying the context, even if you
732 * never get the Buffer from the SharedFuture.
734 * The Buffer will be scheduled to load asynchronously, and the caller gets
735 * back a SharedFuture that can be checked later (or waited on) to get the
736 * actual Buffer when it's ready. The application must take care to handle
737 * exceptions from the SharedFuture in case an unrecoverable error ocurred
738 * during the load.
740 SharedFuture<Buffer> getBufferAsync(StringView name);
743 * Asynchronously prepares cached Buffers for the given audio file or
744 * resource names. Duplicate names and buffers already cached are ignored.
745 * Cached buffers must be freed using removeBuffer before destroying the
746 * context.
748 * The Buffer objects will be scheduled for loading asynchronously, and
749 * should be retrieved later when needed using getBufferAsync or getBuffer.
750 * Buffers that cannot be loaded, for example due to an unsupported format,
751 * will be ignored and a later call to getBuffer or getBufferAsync will
752 * throw an exception.
754 * Note that you should avoid trying to asynchronously cache more than 16
755 * buffers at a time. The internal ringbuffer used to communicate with the
756 * background thread can only hold 16 async load requests, and trying to
757 * add more will cause the call to stall until the background thread
758 * completes some loads for more to be filled in.
760 void precacheBuffersAsync(ArrayView<StringView> names);
763 * Creates and caches a Buffer using the given name. The name may alias an
764 * audio file, but it must not currently exist in the buffer cache.
766 Buffer createBufferFrom(StringView name, SharedPtr<Decoder> decoder);
769 * Asynchronously prepares a cached Buffer using the given name. The name
770 * may alias an audio file, but it must not currently exist in the buffer
771 * cache. Once called, the buffer must be freed using removeBuffer before
772 * destroying the context, even if you never get the Buffer from the
773 * SharedFuture.
775 * The Buffer will be scheduled to load asynchronously, and the caller gets
776 * back a SharedFuture that can be checked later (or waited on) to get the
777 * actual Buffer when it's ready. The application must take care to handle
778 * exceptions from the SharedFuture in case an unrecoverable error ocurred
779 * during the load. The decoder must not have its read or seek methods
780 * called while the buffer is not ready.
782 SharedFuture<Buffer> createBufferAsyncFrom(StringView name, SharedPtr<Decoder> decoder);
785 * Deletes the cached Buffer object for the given audio file or resource
786 * name. The buffer must not be in use by a Source.
788 void removeBuffer(StringView name);
790 * Deletes the given cached buffer. The buffer must not be in use by a
791 * Source.
793 void removeBuffer(Buffer buffer);
796 * Creates a new Source. There is no practical limit to the number of
797 * sources you may create. You must call Source::release when the source is
798 * no longer needed.
800 Source createSource();
802 AuxiliaryEffectSlot createAuxiliaryEffectSlot();
804 Effect createEffect();
806 SourceGroup createSourceGroup(StringView name);
807 SourceGroup getSourceGroup(StringView name);
809 /** Sets the doppler factor to apply to all source calculations. */
810 void setDopplerFactor(ALfloat factor);
813 * Sets the speed of sound propagation, in units per second, to calculate
814 * the doppler effect along with other distance-related time effects. The
815 * default is 343.3 units per second (a realistic speed assuming 1 meter
816 * per unit). If this is adjusted for a different unit scale,
817 * Listener::setMetersPerUnit should also be adjusted.
819 void setSpeedOfSound(ALfloat speed);
821 void setDistanceModel(DistanceModel model);
823 /** Updates the context and all sources belonging to this context. */
824 void update();
827 class ALURE_API Listener {
828 MAKE_PIMPL(Listener, ListenerImpl)
830 public:
831 /** Sets the "master" gain for all context output. */
832 void setGain(ALfloat gain);
835 * Specifies the listener's 3D position, velocity, and orientation
836 * together.
838 void set3DParameters(const Vector3 &position, const Vector3 &velocity, std::pair<Vector3,Vector3> orientation);
840 /** Specifies the listener's 3D position. */
841 void setPosition(ALfloat x, ALfloat y, ALfloat z);
842 void setPosition(const ALfloat *pos);
845 * Specifies the listener's 3D velocity, in units per second. As with
846 * OpenAL, this does not actually alter the listener's position, and
847 * instead just alters the pitch as determined by the doppler effect.
849 void setVelocity(ALfloat x, ALfloat y, ALfloat z);
850 void setVelocity(const ALfloat *vel);
853 * Specifies the listener's 3D orientation, using position-relative 'at'
854 * and 'up' direction vectors.
856 void setOrientation(ALfloat x1, ALfloat y1, ALfloat z1, ALfloat x2, ALfloat y2, ALfloat z2);
857 void setOrientation(const ALfloat *at, const ALfloat *up);
858 void setOrientation(const ALfloat *ori);
861 * Sets the number of meters per unit, used for various effects that rely
862 * on the distance in meters (including air absorption and initial reverb
863 * decay). If this is changed, it's strongly recommended to also set the
864 * speed of sound (e.g. context.setSpeedOfSound(343.3 / m_u) to maintain a
865 * realistic 343.3m/s for sound propagation).
867 void setMetersPerUnit(ALfloat m_u);
871 class ALURE_API Buffer {
872 MAKE_PIMPL(Buffer, BufferImpl)
874 public:
875 /** Retrieves the length of the buffer in sample frames. */
876 ALuint getLength() const;
878 /** Retrieves the buffer's frequency in hz. */
879 ALuint getFrequency() const;
881 /** Retrieves the buffer's sample configuration. */
882 ChannelConfig getChannelConfig() const;
884 /** Retrieves the buffer's sample type. */
885 SampleType getSampleType() const;
887 /** Retrieves the storage size used by the buffer, in bytes. */
888 ALuint getSize() const;
891 * Sets the buffer's loop points, used for looping sources. If the current
892 * context does not support the AL_SOFT_loop_points extension, start and
893 * end must be 0 and getLength() respectively. Otherwise, start must be
894 * less than end, and end must be less than or equal to getLength().
896 * The buffer must not be in use when this method is called.
898 * \param start The starting point, in sample frames (inclusive).
899 * \param end The ending point, in sample frames (exclusive).
901 void setLoopPoints(ALuint start, ALuint end);
903 /** Retrieves the current loop points as a [start,end) pair. */
904 std::pair<ALuint,ALuint> getLoopPoints() const;
907 * Retrieves the Source objects currently playing the buffer. Stopping the
908 * returned sources will allow the buffer to be removed from the context.
910 Vector<Source> getSources() const;
912 /** Retrieves the name the buffer was created with. */
913 const String &getName() const;
915 /** Queries if the buffer is in use and can't be removed. */
916 bool isInUse() const;
920 enum class Spatialize {
921 Off = AL_FALSE,
922 On = AL_TRUE,
923 Auto = 0x0002 /* AL_AUTO_SOFT */
926 class ALURE_API Source {
927 MAKE_PIMPL(Source, SourceImpl)
929 public:
931 * Plays the source using buffer. The same buffer may be played from
932 * multiple sources simultaneously.
934 void play(Buffer buffer);
936 * Plays the source by streaming audio from decoder. This will use
937 * queuesize buffers, each with updatelen sample frames. The given decoder
938 * must *NOT* have its read or seek methods called from elsewhere while in
939 * use.
941 void play(SharedPtr<Decoder> decoder, ALuint updatelen, ALuint queuesize);
942 /** Stops playback, releasing the buffer or decoder reference. */
943 void stop();
945 /** Pauses the source if it is playing. */
946 void pause();
948 /** Resumes the source if it is paused. */
949 void resume();
951 /** Specifies if the source is currently playing. */
952 bool isPlaying() const;
954 /** Specifies if the source is currently paused. */
955 bool isPaused() const;
958 * Specifies the source's playback priority. Lowest priority sources will
959 * be evicted first when higher priority sources are played.
961 void setPriority(ALuint priority);
962 /** Retrieves the source's priority. */
963 ALuint getPriority() const;
966 * Sets the source's offset, in sample frames. If the source is playing or
967 * paused, it will go to that offset immediately, otherwise the source will
968 * start at the specified offset the next time it's played.
970 void setOffset(uint64_t offset);
972 * Retrieves the source offset in sample frames and its latency in nano-
973 * seconds. For streaming sources this will be the offset based on the
974 * decoder's read position.
976 * If the AL_SOFT_source_latency extension is unsupported, the latency will
977 * be 0.
979 std::pair<uint64_t,std::chrono::nanoseconds> getSampleOffsetLatency() const;
980 uint64_t getSampleOffset() const { return std::get<0>(getSampleOffsetLatency()); }
982 * Retrieves the source offset and latency in seconds. For streaming
983 * sources this will be the offset based on the decoder's read position.
985 * If the AL_SOFT_source_latency extension is unsupported, the latency will
986 * be 0.
988 std::pair<Seconds,Seconds> getSecOffsetLatency() const;
989 Seconds getSecOffset() const { return std::get<0>(getSecOffsetLatency()); }
992 * Specifies if the source should loop on the Buffer or Decoder object's
993 * loop points.
995 void setLooping(bool looping);
996 bool getLooping() const;
999 * Specifies a linear pitch shift base. A value of 1.0 is the default
1000 * normal speed.
1002 void setPitch(ALfloat pitch);
1003 ALfloat getPitch() const;
1006 * Specifies the base linear gain. A value of 1.0 is the default normal
1007 * volume.
1009 void setGain(ALfloat gain);
1010 ALfloat getGain() const;
1013 * Specifies the minimum and maximum gain. The source's gain is clamped to
1014 * this range after distance attenuation and cone attenuation are applied
1015 * to the gain base, although before the filter gain adjustements.
1017 void setGainRange(ALfloat mingain, ALfloat maxgain);
1018 std::pair<ALfloat,ALfloat> getGainRange() const;
1019 ALfloat getMinGain() const { return std::get<0>(getGainRange()); }
1020 ALfloat getMaxGain() const { return std::get<1>(getGainRange()); }
1023 * Specifies the reference distance and maximum distance the source will
1024 * use for the current distance model. For Clamped distance models, the
1025 * source's calculated distance is clamped to the specified range before
1026 * applying distance-related attenuation.
1028 * For all distance models, the reference distance is the distance at which
1029 * the source's volume will not have any extra attenuation (an effective
1030 * gain multiplier of 1).
1032 void setDistanceRange(ALfloat refdist, ALfloat maxdist);
1033 std::pair<ALfloat,ALfloat> getDistanceRange() const;
1034 ALfloat getReferenceDistance() const { return std::get<0>(getDistanceRange()); }
1035 ALfloat getMaxDistance() const { return std::get<1>(getDistanceRange()); }
1037 /** Specifies the source's 3D position, velocity, and direction together. */
1038 void set3DParameters(const Vector3 &position, const Vector3 &velocity, const Vector3 &direction);
1040 /** Specifies the source's 3D position, velocity, and orientation together. */
1041 void set3DParameters(const Vector3 &position, const Vector3 &velocity, std::pair<Vector3,Vector3> orientation);
1043 /** Specifies the source's 3D position. */
1044 void setPosition(ALfloat x, ALfloat y, ALfloat z);
1045 void setPosition(const ALfloat *pos);
1046 Vector3 getPosition() const;
1049 * Specifies the source's 3D velocity, in units per second. As with OpenAL,
1050 * this does not actually alter the source's position, and instead just
1051 * alters the pitch as determined by the doppler effect.
1053 void setVelocity(ALfloat x, ALfloat y, ALfloat z);
1054 void setVelocity(const ALfloat *vel);
1055 Vector3 getVelocity() const;
1058 * Specifies the source's 3D facing direction. Deprecated in favor of
1059 * setOrientation.
1061 void setDirection(ALfloat x, ALfloat y, ALfloat z);
1062 void setDirection(const ALfloat *dir);
1063 Vector3 getDirection() const;
1066 * Specifies the source's 3D orientation. Note: unlike the AL_EXT_BFORMAT
1067 * extension this property comes from, this also affects the facing
1068 * direction, superceding setDirection.
1070 void setOrientation(ALfloat x1, ALfloat y1, ALfloat z1, ALfloat x2, ALfloat y2, ALfloat z2);
1071 void setOrientation(const ALfloat *at, const ALfloat *up);
1072 void setOrientation(const ALfloat *ori);
1073 std::pair<Vector3,Vector3> getOrientation() const;
1076 * Specifies the source's cone angles, in degrees. The inner angle is the
1077 * area within which the listener will hear the source with no extra
1078 * attenuation, while the listener being outside of the outer angle will
1079 * hear the source attenuated according to the outer cone gains.
1081 void setConeAngles(ALfloat inner, ALfloat outer);
1082 std::pair<ALfloat,ALfloat> getConeAngles() const;
1083 ALfloat getInnerConeAngle() const { return std::get<0>(getConeAngles()); }
1084 ALfloat getOuterConeAngle() const { return std::get<1>(getConeAngles()); }
1087 * Specifies the linear gain multiplier when the listener is outside of the
1088 * source's outer cone area. The specified gain applies to all frequencies,
1089 * while gainhf applies extra attenuation to high frequencies.
1091 * \param gainhf has no effect without the ALC_EXT_EFX extension.
1093 void setOuterConeGains(ALfloat gain, ALfloat gainhf=1.0f);
1094 std::pair<ALfloat,ALfloat> getOuterConeGains() const;
1095 ALfloat getOuterConeGain() const { return std::get<0>(getOuterConeGains()); }
1096 ALfloat getOuterConeGainHF() const { return std::get<1>(getOuterConeGains()); }
1099 * Specifies the rolloff factors for the direct and send paths. This is
1100 * effectively a distance scaling relative to the reference distance. Note:
1101 * the room rolloff factor is 0 by default, disabling distance attenuation
1102 * for send paths. This is because the reverb engine will, by default,
1103 * apply a more realistic room decay based on the reverb decay time and
1104 * distance.
1106 void setRolloffFactors(ALfloat factor, ALfloat roomfactor=0.0f);
1107 std::pair<ALfloat,ALfloat> getRolloffFactors() const;
1108 ALfloat getRolloffFactor() const { return std::get<0>(getRolloffFactors()); }
1109 ALfloat getRoomRolloffFactor() const { return std::get<1>(getRolloffFactors()); }
1112 * Specifies the doppler factor for the doppler effect's pitch shift. This
1113 * effectively scales the source and listener velocities for the doppler
1114 * calculation.
1116 void setDopplerFactor(ALfloat factor);
1117 ALfloat getDopplerFactor() const;
1120 * Specifies if the source's position, velocity, and direction/orientation
1121 * are relative to the listener.
1123 void setRelative(bool relative);
1124 bool getRelative() const;
1127 * Specifies the source's radius. This causes the source to behave as if
1128 * every point within the spherical area emits sound.
1130 * Has no effect without the AL_EXT_SOURCE_RADIUS extension.
1132 void setRadius(ALfloat radius);
1133 ALfloat getRadius() const;
1136 * Specifies the left and right channel angles, in radians, when playing a
1137 * stereo buffer or stream. The angles go counter-clockwise, with 0 being
1138 * in front and positive values going left.
1140 * Has no effect without the AL_EXT_STEREO_ANGLES extension.
1142 void setStereoAngles(ALfloat leftAngle, ALfloat rightAngle);
1143 std::pair<ALfloat,ALfloat> getStereoAngles() const;
1146 * Specifies if the source always has 3D spatialization features (On),
1147 * never has 3D spatialization features (Off), or if spatialization is
1148 * enabled based on playing a mono sound or not (Auto, default).
1150 * Has no effect without the AL_SOFT_source_spatialize extension.
1152 void set3DSpatialize(Spatialize spatialize);
1153 Spatialize get3DSpatialize() const;
1155 void setResamplerIndex(ALsizei index);
1156 ALsizei getResamplerIndex() const;
1159 * Specifies a multiplier for the amount of atmospheric high-frequency
1160 * absorption, ranging from 0 to 10. A factor of 1 results in a nominal
1161 * -0.05dB per meter, with higher values simulating foggy air and lower
1162 * values simulating dryer air. The default is 0.
1164 void setAirAbsorptionFactor(ALfloat factor);
1165 ALfloat getAirAbsorptionFactor() const;
1167 void setGainAuto(bool directhf, bool send, bool sendhf);
1168 std::tuple<bool,bool,bool> getGainAuto() const;
1169 bool getDirectGainHFAuto() const { return std::get<0>(getGainAuto()); }
1170 bool getSendGainAuto() const { return std::get<1>(getGainAuto()); }
1171 bool getSendGainHFAuto() const { return std::get<2>(getGainAuto()); }
1173 /** Sets the filter properties on the direct path signal. */
1174 void setDirectFilter(const FilterParams &filter);
1176 * Sets the filter properties on the given send path signal. Any auxiliary
1177 * effect slot on the send path remains in place.
1179 void setSendFilter(ALuint send, const FilterParams &filter);
1181 * Connects the effect slot to the given send path. Any filter properties
1182 * on the send path remain as they were.
1184 void setAuxiliarySend(AuxiliaryEffectSlot slot, ALuint send);
1186 * Connects the effect slot to the given send path, using the filter
1187 * properties.
1189 void setAuxiliarySendFilter(AuxiliaryEffectSlot slot, ALuint send, const FilterParams &filter);
1192 * Releases the source, stopping playback, releasing resources, and
1193 * returning it to the system.
1195 void release();
1199 class ALURE_API SourceGroup {
1200 MAKE_PIMPL(SourceGroup, SourceGroupImpl)
1202 public:
1203 /** Retrieves the associated name of the source group. */
1204 const String &getName() const;
1207 * Adds source to the source group. A source may only be part of one group
1208 * at a time, and will automatically be removed from its current group as
1209 * needed.
1211 void addSource(Source source);
1212 /** Removes source from the source group. */
1213 void removeSource(Source source);
1215 /** Adds a list of sources to the group at once. */
1216 void addSources(ArrayView<Source> sources);
1217 /** Removes a list of sources from the source group. */
1218 void removeSources(ArrayView<Source> sources);
1221 * Adds group as a subgroup of the source group. This method will throw an
1222 * exception if group is being added to a group it has as a sub-group (i.e.
1223 * it would create a circular sub-group chain).
1225 void addSubGroup(SourceGroup group);
1226 /** Removes group from the source group. */
1227 void removeSubGroup(SourceGroup group);
1229 /** Returns the list of sources currently in the group. */
1230 Vector<Source> getSources() const;
1232 /** Returns the list of subgroups currently in the group. */
1233 Vector<SourceGroup> getSubGroups() const;
1235 /** Sets the source group gain, which accumulates with its sources. */
1236 void setGain(ALfloat gain);
1237 /** Gets the source group gain. */
1238 ALfloat getGain() const;
1240 /** Sets the source group pitch, which accumulates with its sources. */
1241 void setPitch(ALfloat pitch);
1242 /** Gets the source group pitch. */
1243 ALfloat getPitch() const;
1246 * Pauses all currently-playing sources that are under this group,
1247 * including sub-groups.
1249 void pauseAll() const;
1251 * Resumes all paused sources that are under this group, including
1252 * sub-groups.
1254 void resumeAll() const;
1256 /** Stops all sources that are under this group, including sub-groups. */
1257 void stopAll() const;
1260 * Releases the source group, removing all sources from it before being
1261 * freed.
1263 void release();
1267 struct SourceSend {
1268 Source mSource;
1269 ALuint mSend;
1272 class ALURE_API AuxiliaryEffectSlot {
1273 MAKE_PIMPL(AuxiliaryEffectSlot, AuxiliaryEffectSlotImpl)
1275 public:
1276 void setGain(ALfloat gain);
1278 * If set to true, the reverb effect will automatically apply adjustments
1279 * to the source's send slot gains based on the effect properties.
1281 * Has no effect when using non-reverb effects. Default is true.
1283 void setSendAuto(bool sendauto);
1286 * Updates the effect slot with a new effect. The given effect object may
1287 * be altered or destroyed without affecting the effect slot.
1289 void applyEffect(Effect effect);
1292 * Releases the effect slot, returning it to the system. It must not be in
1293 * use by a source.
1295 void release();
1298 * Retrieves each Source object and its pairing send this effect slot is
1299 * set on. Setting a different (or null) effect slot on each source's given
1300 * send will allow the effect slot to be released.
1302 Vector<SourceSend> getSourceSends() const;
1304 /** Determines if the effect slot is in use by a source. */
1305 bool isInUse() const;
1309 class ALURE_API Effect {
1310 MAKE_PIMPL(Effect, EffectImpl)
1312 public:
1314 * Updates the effect with the specified reverb properties. If the
1315 * EAXReverb effect is not supported, it will automatically attempt to
1316 * downgrade to the Standard Reverb effect.
1318 void setReverbProperties(const EFXEAXREVERBPROPERTIES &props);
1320 void destroy();
1325 * Audio decoder interface. Applications may derive from this, implementing the
1326 * necessary methods, and use it in places the API wants a Decoder object.
1328 class ALURE_API Decoder {
1329 public:
1330 virtual ~Decoder();
1332 /** Retrieves the sample frequency, in hz, of the audio being decoded. */
1333 virtual ALuint getFrequency() const = 0;
1334 /** Retrieves the channel configuration of the audio being decoded. */
1335 virtual ChannelConfig getChannelConfig() const = 0;
1336 /** Retrieves the sample type of the audio being decoded. */
1337 virtual SampleType getSampleType() const = 0;
1340 * Retrieves the total length of the audio, in sample frames. If unknown,
1341 * returns 0. Note that if the returned length is 0, the decoder may not be
1342 * used to load a Buffer.
1344 virtual uint64_t getLength() const = 0;
1346 * Seek to pos, specified in sample frames. Returns true if the seek was
1347 * successful.
1349 virtual bool seek(uint64_t pos) = 0;
1352 * Retrieves the loop points, in sample frames, as a [start,end) pair. If
1353 * start >= end, use all available data.
1355 virtual std::pair<uint64_t,uint64_t> getLoopPoints() const = 0;
1358 * Decodes count sample frames, writing them to ptr, and returns the number
1359 * of sample frames written. Returning less than the requested count
1360 * indicates the end of the audio.
1362 virtual ALuint read(ALvoid *ptr, ALuint count) = 0;
1366 * Audio decoder factory interface. Applications may derive from this,
1367 * implementing the necessary methods, and use it in places the API wants a
1368 * DecoderFactory object.
1370 class ALURE_API DecoderFactory {
1371 public:
1372 virtual ~DecoderFactory();
1375 * Creates and returns a Decoder instance for the given resource file. If
1376 * the decoder needs to retain the file handle for reading as-needed, it
1377 * should move the UniquePtr to internal storage.
1379 * \return nullptr if a decoder can't be created from the file.
1381 virtual SharedPtr<Decoder> createDecoder(UniquePtr<std::istream> &file) = 0;
1385 * Registers a decoder factory for decoding audio. Registered factories are
1386 * used in lexicographical order, e.g. if Factory1 is registered with name1 and
1387 * Factory2 is registered with name2, Factory1 will be used before Factory2 if
1388 * name1 < name2. Internal decoder factories are always used after registered
1389 * ones.
1391 * Alure retains a reference to the DecoderFactory instance and will release it
1392 * (destructing the object) when the library unloads.
1394 * \param name A unique name identifying this decoder factory.
1395 * \param factory A DecoderFactory instance used to create Decoder instances.
1397 ALURE_API void RegisterDecoder(const String &name, UniquePtr<DecoderFactory> factory);
1400 * Unregisters a decoder factory by name. Alure returns the instance back to
1401 * the application.
1403 * \param name The unique name identifying a previously-registered decoder
1404 * factory.
1406 * \return The unregistered decoder factory instance, or 0 (nullptr) if a
1407 * decoder factory with the given name doesn't exist.
1409 ALURE_API UniquePtr<DecoderFactory> UnregisterDecoder(const String &name);
1413 * A file I/O factory interface. Applications may derive from this and set an
1414 * instance to be used by the audio decoders. By default, the library uses
1415 * standard I/O.
1417 class ALURE_API FileIOFactory {
1418 public:
1420 * Sets the factory instance to be used by the audio decoders. If a
1421 * previous factory was set, it's returned to the application. Passing in a
1422 * nullptr reverts to the default.
1424 static UniquePtr<FileIOFactory> set(UniquePtr<FileIOFactory> factory);
1427 * Gets the current FileIOFactory instance being used by the audio
1428 * decoders.
1430 static FileIOFactory &get();
1432 virtual ~FileIOFactory();
1434 /** Opens a read-only binary file for the given name. */
1435 virtual UniquePtr<std::istream> openFile(const String &name) = 0;
1440 * A message handler interface. Applications may derive from this and set an
1441 * instance on a context to receive messages. The base methods are no-ops, so
1442 * derived classes only need to implement methods for relevant messages.
1444 * It's recommended that applications mark their handler methods using the
1445 * override keyword, to ensure they're properly overriding the base methods in
1446 * case they change.
1448 class ALURE_API MessageHandler {
1449 public:
1450 virtual ~MessageHandler();
1453 * Called when the given device has been disconnected and is no longer
1454 * usable for output. As per the ALC_EXT_disconnect specification,
1455 * disconnected devices remain valid, however all playing sources are
1456 * automatically stopped, any sources that are attempted to play will
1457 * immediately stop, and new contexts may not be created on the device.
1459 * Note that connection status is checked during Context::update calls, so
1460 * that method must be called regularly to be notified when a device is
1461 * disconnected. This method may not be called if the device lacks support
1462 * for the ALC_EXT_disconnect extension.
1464 virtual void deviceDisconnected(Device device);
1467 * Called when the given source reaches the end of the buffer or stream.
1469 * Sources that stopped automatically will be detected upon a call to
1470 * Context::update.
1472 virtual void sourceStopped(Source source);
1475 * Called when the given source was forced to stop. This can be because
1476 * either there were no more system sources and a higher-priority source
1477 * preempted it, or it's part of a SourceGroup (or sub-group thereof) that
1478 * had its SourceGroup::stopAll method called.
1480 virtual void sourceForceStopped(Source source);
1483 * Called when a new buffer is about to be created and loaded. May be
1484 * called asynchronously for buffers being loaded asynchronously.
1486 * \param name The resource name, as passed to Context::getBuffer.
1487 * \param channels Channel configuration of the given audio data.
1488 * \param type Sample type of the given audio data.
1489 * \param samplerate Sample rate of the given audio data.
1490 * \param data The audio data that is about to be fed to the OpenAL buffer.
1492 virtual void bufferLoading(StringView name, ChannelConfig channels, SampleType type, ALuint samplerate, ArrayView<ALbyte> data);
1495 * Called when a resource isn't found, allowing the app to substitute in a
1496 * different resource. For buffers created with Context::getBuffer or
1497 * Context::getBufferAsync, the original name will still be used for the
1498 * cache map so the app doesn't have to keep track of substituted resource
1499 * names.
1501 * This will be called again if the new name isn't found.
1503 * \param name The resource name that was not found.
1504 * \return The replacement resource name to use instead. Returning an empty
1505 * string means to stop trying.
1507 virtual String resourceNotFound(StringView name);
1510 #undef MAKE_PIMPL
1512 } // namespace alure
1514 #endif /* AL_ALURE2_H */