Add methods to get the source offset and latency as seconds
[alure.git] / include / AL / alure2.h
blob1463f90a758fff3742ea497781ade834998763d8
1 #ifndef AL_ALURE2_H
2 #define AL_ALURE2_H
4 #include <vector>
5 #include <string>
6 #include <memory>
7 #include <utility>
8 #include <chrono>
9 #include <array>
10 #include <cmath>
12 #include "alc.h"
13 #include "al.h"
15 #ifdef _WIN32
16 #if defined(ALURE_BUILD_STATIC) || defined(ALURE_STATIC_LIB)
17 #define ALURE_API
18 #elif defined(ALURE_BUILD_DLL)
19 #define ALURE_API __declspec(dllexport)
20 #else
21 #define ALURE_API __declspec(dllimport)
22 #endif
24 #else
26 #define ALURE_API
27 #endif
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 Device;
62 class ALDevice;
63 class Context;
64 class ALContext;
65 class Listener;
66 class ALListener;
67 class Buffer;
68 class ALBuffer;
69 class Source;
70 class ALSource;
71 class SourceGroup;
72 class ALSourceGroup;
73 class AuxiliaryEffectSlot;
74 class ALAuxiliaryEffectSlot;
75 class Effect;
76 class ALEffect;
77 class Decoder;
78 class DecoderFactory;
79 class MessageHandler;
82 // Duration in seconds, using double precision
83 using Seconds = std::chrono::duration<double>;
85 // A SharedPtr implementation, defaults to C++11's std::shared_ptr. If this is
86 // changed, you must recompile the library.
87 template<typename T>
88 using SharedPtr = std::shared_ptr<T>;
89 template<typename T, typename... Args>
90 constexpr inline SharedPtr<T> MakeShared(Args&&... args)
92 return std::make_shared<T>(std::forward<Args>(args)...);
95 // A UniquePtr implementation, defaults to C++11's std::unique_ptr. If this is
96 // changed, you must recompile the library.
97 template<typename T, typename D = std::default_delete<T>>
98 using UniquePtr = std::unique_ptr<T, D>;
99 template<typename T, typename... Args>
100 constexpr inline UniquePtr<T> MakeUnique(Args&&... args)
102 #if __cplusplus >= 201402L
103 return std::make_unique<T>(std::forward<Args>(args)...);
104 #else
105 return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
106 #endif
109 // A Vector implementation, defaults to C++'s std::vector. If this is changed,
110 // you must recompile the library.
111 template<typename T>
112 using Vector = std::vector<T>;
114 // A String implementation, default's to C++'s std::string. If this is changed,
115 // you must recompile the library.
116 using String = std::string;
118 // A rather simple ArrayView container. This allows accepting various array
119 // types (std::array, Vector, a static-sized array, a dynamic array + size)
120 // without copying its elements.
121 template<typename T>
122 class ArrayView {
123 T *mElems;
124 size_t mNumElems;
126 public:
127 typedef T *iterator;
128 typedef const T *const_iterator;
130 ArrayView() : mElems(nullptr), mNumElems(0) { }
131 ArrayView(const ArrayView &rhs) : mElems(rhs.data()), mNumElems(rhs.size()) { }
132 ArrayView(ArrayView&& rhs) : mElems(rhs.data()), mNumElems(rhs.size()) { }
133 ArrayView(T *elems, size_t num_elems) : mElems(elems), mNumElems(num_elems) { }
134 template<size_t N>
135 ArrayView(T (&elems)[N]) : mElems(elems), mNumElems(N) { }
136 template<typename OtherT>
137 ArrayView(OtherT &arr) : mElems(arr.data()), mNumElems(arr.size()) { }
139 ArrayView& operator=(const ArrayView &rhs)
141 mElems = rhs.data();
142 mNumElems = rhs.size();
144 ArrayView& operator=(ArrayView&& rhs)
146 mElems = rhs.data();
147 mNumElems = rhs.size();
149 template<size_t N>
150 ArrayView& operator=(T (&elems)[N])
152 mElems = elems;
153 mNumElems = N;
155 template<typename OtherT>
156 ArrayView& operator=(OtherT &arr)
158 mElems = arr.data();
159 mNumElems = arr.size();
163 const T *data() const { return mElems; }
164 T *data() { return mElems; }
166 size_t size() const { return mNumElems; }
167 bool empty() const { return mNumElems == 0; }
169 const T& operator[](size_t i) const { return mElems[i]; }
170 T& operator[](size_t i) { return mElems[i]; }
172 const T& front() const { return mElems[0]; }
173 T& front() { return mElems[0]; }
174 const T& back() const { return mElems[mNumElems-1]; }
175 T& back() { return mElems[mNumElems-1]; }
177 const T& at(size_t i) const
179 if(i >= mNumElems)
180 throw std::out_of_range("alure::ArrayView::at: element out of range");
181 return mElems[i];
183 T& at(size_t i)
185 if(i >= mNumElems)
186 throw std::out_of_range("alure::ArrayView::at: element out of range");
187 return mElems[i];
190 iterator begin() { return mElems; }
191 const_iterator begin() const { return mElems; }
192 const_iterator cbegin() const { return mElems; }
194 iterator end() { return mElems + mNumElems; }
195 const_iterator end() const { return mElems + mNumElems; }
196 const_iterator cend() const { return mElems + mNumElems; }
201 * An attribute pair, for passing attributes to Device::createContext and
202 * Device::reset.
204 using AttributePair = std::pair<ALCint,ALCint>;
205 static_assert(sizeof(AttributePair) == sizeof(ALCint[2]), "Bad AttributePair size");
208 struct FilterParams {
209 ALfloat mGain;
210 ALfloat mGainHF; // For low-pass and band-pass filters
211 ALfloat mGainLF; // For high-pass and band-pass filters
215 class ALURE_API Vector3 {
216 std::array<ALfloat,3> mValue;
218 public:
219 constexpr Vector3() noexcept
220 : mValue{{0.0f, 0.0f, 0.0f}}
222 constexpr Vector3(const Vector3 &rhs) noexcept
223 : mValue{{rhs.mValue[0], rhs.mValue[1], rhs.mValue[2]}}
225 constexpr Vector3(ALfloat val) noexcept
226 : mValue{{val, val, val}}
228 constexpr Vector3(ALfloat x, ALfloat y, ALfloat z) noexcept
229 : mValue{{x, y, z}}
231 Vector3(const ALfloat *vec) noexcept
232 : mValue{{vec[0], vec[1], vec[2]}}
235 const ALfloat *getPtr() const noexcept
236 { return mValue.data(); }
238 ALfloat& operator[](size_t i) noexcept
239 { return mValue[i]; }
240 constexpr const ALfloat& operator[](size_t i) const noexcept
241 { return mValue[i]; }
243 #define ALURE_DECL_OP(op) \
244 constexpr Vector3 operator op(const Vector3 &rhs) const noexcept \
246 return Vector3(mValue[0] op rhs.mValue[0], \
247 mValue[1] op rhs.mValue[1], \
248 mValue[2] op rhs.mValue[2]); \
250 ALURE_DECL_OP(+)
251 ALURE_DECL_OP(-)
252 ALURE_DECL_OP(*)
253 ALURE_DECL_OP(/)
254 #undef ALURE_DECL_OP
255 #define ALURE_DECL_OP(op) \
256 Vector3& operator op(const Vector3 &rhs) noexcept \
258 mValue[0] op rhs.mValue[0]; \
259 mValue[1] op rhs.mValue[1]; \
260 mValue[2] op rhs.mValue[2]; \
261 return *this; \
263 ALURE_DECL_OP(+=)
264 ALURE_DECL_OP(-=)
265 ALURE_DECL_OP(*=)
266 ALURE_DECL_OP(/=)
268 #undef ALURE_DECL_OP
269 #define ALURE_DECL_OP(op) \
270 constexpr Vector3 operator op(ALfloat scale) const noexcept \
272 return Vector3(mValue[0] op scale, \
273 mValue[1] op scale, \
274 mValue[2] op scale); \
276 ALURE_DECL_OP(*)
277 ALURE_DECL_OP(/)
278 #undef ALURE_DECL_OP
279 #define ALURE_DECL_OP(op) \
280 Vector3& operator op(ALfloat scale) noexcept \
282 mValue[0] op scale; \
283 mValue[1] op scale; \
284 mValue[2] op scale; \
285 return *this; \
287 ALURE_DECL_OP(*=)
288 ALURE_DECL_OP(/=)
289 #undef ALURE_DECL_OP
291 constexpr ALfloat getLengthSquared() const noexcept
292 { return mValue[0]*mValue[0] + mValue[1]*mValue[1] + mValue[2]*mValue[2]; }
293 ALfloat getLength() const noexcept
294 { return std::sqrt(getLengthSquared()); }
296 constexpr ALfloat getDistanceSquared(const Vector3 &pos) const noexcept
297 { return (pos - *this).getLengthSquared(); }
298 ALfloat getDistance(const Vector3 &pos) const noexcept
299 { return (pos - *this).getLength(); }
301 static_assert(sizeof(Vector3) == sizeof(ALfloat[3]), "Bad Vector3 size");
304 enum class SampleType {
305 UInt8,
306 Int16,
307 Float32,
308 Mulaw
310 ALURE_API const char *GetSampleTypeName(SampleType type);
312 enum class ChannelConfig {
313 /** 1-channel mono sound. */
314 Mono,
315 /** 2-channel stereo sound. */
316 Stereo,
317 /** 2-channel rear sound (back-left and back-right). */
318 Rear,
319 /** 4-channel surround sound. */
320 Quad,
321 /** 5.1 surround sound. */
322 X51,
323 /** 6.1 surround sound. */
324 X61,
325 /** 7.1 surround sound. */
326 X71,
327 /** 3-channel B-Format, using FuMa channel ordering and scaling. */
328 BFormat2D,
329 /** 4-channel B-Format, using FuMa channel ordering and scaling. */
330 BFormat3D
332 ALURE_API const char *GetChannelConfigName(ChannelConfig cfg);
334 ALURE_API ALuint FramesToBytes(ALuint frames, ChannelConfig chans, SampleType type);
335 ALURE_API ALuint BytesToFrames(ALuint bytes, ChannelConfig chans, SampleType type);
339 * Creates a version number value using the specified major and minor values.
341 constexpr inline ALCuint MakeVersion(ALCushort major, ALCushort minor)
342 { return (major<<16) | minor; }
345 * Retrieves the major version of a version number value created by
346 * MakeVersion.
348 constexpr inline ALCuint MajorVersion(ALCuint version)
349 { return version>>16; }
351 * Retrieves the minor version of a version number value created by
352 * MakeVersion.
354 constexpr inline ALCuint MinorVersion(ALCuint version)
355 { return version&0xffff; }
358 enum class DeviceEnumeration {
359 Basic = ALC_DEVICE_SPECIFIER,
360 Complete = ALC_ALL_DEVICES_SPECIFIER,
361 Capture = ALC_CAPTURE_DEVICE_SPECIFIER
364 enum class DefaultDeviceType {
365 Basic = ALC_DEFAULT_DEVICE_SPECIFIER,
366 Complete = ALC_DEFAULT_ALL_DEVICES_SPECIFIER,
367 Capture = ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER
371 * A class managing Device objects and other related functionality. This class
372 * is a singleton, only one instance will exist in a process.
374 class ALURE_API DeviceManager {
375 public:
376 /** Retrieves the DeviceManager instance. */
377 static DeviceManager &get();
379 /** Queries the existence of a non-device-specific ALC extension. */
380 virtual bool queryExtension(const String &name) const = 0;
382 /** Enumerates available device names of the given type. */
383 virtual Vector<String> enumerate(DeviceEnumeration type) const = 0;
384 /** Retrieves the default device of the given type. */
385 virtual String defaultDeviceName(DefaultDeviceType type) const = 0;
388 * Opens the playback device given by name, or the default if blank. Throws
389 * an exception on error.
391 virtual Device openPlayback(const String &name=String()) = 0;
394 * Opens the playback device given by name, or the default if blank.
395 * Returns an empty Device on error.
397 virtual Device openPlayback(const String &name, const std::nothrow_t&) = 0;
399 /** Opens the default playback device. Returns an empty Device on error. */
400 Device openPlayback(const std::nothrow_t&);
404 enum class PlaybackDeviceName {
405 Basic = ALC_DEVICE_SPECIFIER,
406 Complete = ALC_ALL_DEVICES_SPECIFIER
409 #define MAKE_PIMPL(BaseT, ImplT) \
410 private: \
411 ImplT *pImpl; \
413 public: \
414 using handle_type = ImplT*; \
416 BaseT() : pImpl(nullptr) { } \
417 BaseT(ImplT *impl) : pImpl(impl) { } \
418 BaseT(const BaseT&) = default; \
419 BaseT(BaseT&& rhs) : pImpl(rhs.pImpl) { rhs.pImpl = nullptr; } \
421 BaseT& operator=(const BaseT&) = default; \
422 BaseT& operator=(BaseT&& rhs) \
424 pImpl = rhs.pImpl; rhs.pImpl = nullptr; \
425 return *this; \
428 bool operator==(const BaseT &rhs) const { return pImpl == rhs.pImpl; } \
429 bool operator==(BaseT&& rhs) const { return pImpl == rhs.pImpl; } \
431 operator bool() const { return !!pImpl; } \
433 handle_type getHandle() const { return pImpl; }
435 class ALURE_API Device {
436 MAKE_PIMPL(Device, ALDevice)
438 public:
439 /** Retrieves the device name as given by type. */
440 String getName(PlaybackDeviceName type=PlaybackDeviceName::Basic) const;
441 /** Queries the existence of an ALC extension on this device. */
442 bool queryExtension(const String &name) const;
445 * Retrieves the ALC version supported by this device, as constructed by
446 * MakeVersion.
448 ALCuint getALCVersion() const;
451 * Retrieves the EFX version supported by this device, as constructed by
452 * MakeVersion. If the ALC_EXT_EFX extension is unsupported, this will be
453 * 0.
455 ALCuint getEFXVersion() const;
457 /** Retrieves the device's playback frequency, in hz. */
458 ALCuint getFrequency() const;
461 * Retrieves the maximum number of auxiliary source sends. If ALC_EXT_EFX
462 * is unsupported, this will be 0.
464 ALCuint getMaxAuxiliarySends() const;
467 * Enumerates available HRTF names. The names are sorted as OpenAL gives
468 * them, such that the index of a given name is the ID to use with
469 * ALC_HRTF_ID_SOFT.
471 * Requires the ALC_SOFT_HRTF extension.
473 Vector<String> enumerateHRTFNames() const;
476 * Retrieves whether HRTF is enabled on the device or not.
478 * Requires the ALC_SOFT_HRTF extension.
480 bool isHRTFEnabled() const;
483 * Retrieves the name of the HRTF currently being used by this device.
485 * Requires the ALC_SOFT_HRTF extension.
487 String getCurrentHRTF() const;
490 * Resets the device, using the specified attributes.
492 * Requires the ALC_SOFT_HRTF extension.
494 void reset(ArrayView<AttributePair> attributes);
497 * Creates a new Context on this device, using the specified attributes.
499 Context createContext(ArrayView<AttributePair> attributes=ArrayView<AttributePair>());
502 * Pauses device processing, stopping updates for its contexts. Multiple
503 * calls are allowed but it is not reference counted, so the device will
504 * resume after one resumeDSP call.
506 * Requires the ALC_SOFT_pause_device extension.
508 void pauseDSP();
511 * Resumes device processing, restarting updates for its contexts. Multiple
512 * calls are allowed and will no-op.
514 void resumeDSP();
517 * Closes and frees the device. All previously-created contexts must first
518 * be destroyed.
520 void close();
524 enum class DistanceModel {
525 InverseClamped = AL_INVERSE_DISTANCE_CLAMPED,
526 LinearClamped = AL_LINEAR_DISTANCE_CLAMPED,
527 ExponentClamped = AL_EXPONENT_DISTANCE_CLAMPED,
528 Inverse = AL_INVERSE_DISTANCE,
529 Linear = AL_LINEAR_DISTANCE,
530 Exponent = AL_EXPONENT_DISTANCE,
531 None = AL_NONE,
534 class ALURE_API Context {
535 MAKE_PIMPL(Context, ALContext)
537 public:
538 /** Makes the specified context current for OpenAL operations. */
539 static void MakeCurrent(Context context);
540 /** Retrieves the current context used for OpenAL operations. */
541 static Context GetCurrent();
544 * Makes the specified context current for OpenAL operations on the calling
545 * thread only. Requires the ALC_EXT_thread_local_context extension on both
546 * the context's device and the DeviceManager.
548 static void MakeThreadCurrent(Context context);
549 /** Retrieves the thread-specific context used for OpenAL operations. */
550 static Context GetThreadCurrent();
553 * Destroys the context. The context must not be current when this is
554 * called.
556 void destroy();
558 /** Retrieves the Device this context was created from. */
559 Device getDevice();
561 void startBatch();
562 void endBatch();
565 * Retrieves a Listener instance for this context. Each context will only
566 * have one listener.
568 Listener getListener();
571 * Sets a MessageHandler instance which will be used to provide certain
572 * messages back to the application. Only one handler may be set for a
573 * context at a time. The previously set handler will be returned.
575 SharedPtr<MessageHandler> setMessageHandler(SharedPtr<MessageHandler> handler);
577 /** Gets the currently-set message handler. */
578 SharedPtr<MessageHandler> getMessageHandler() const;
581 * Specifies the desired interval that the background thread will be woken
582 * up to process tasks, e.g. keeping streaming sources filled. An interval
583 * of 0 means the background thread will only be woken up manually with
584 * calls to update. The default is 0.
586 void setAsyncWakeInterval(std::chrono::milliseconds msec);
589 * Retrieves the current interval used for waking up the background thread.
591 std::chrono::milliseconds getAsyncWakeInterval() const;
593 // Functions below require the context to be current
596 * Creates a Decoder instance for the given audio file or resource name.
598 SharedPtr<Decoder> createDecoder(const String &name);
601 * Queries if the channel configuration and sample type are supported by
602 * the context.
604 bool isSupported(ChannelConfig channels, SampleType type) const;
607 * Queries the list of resamplers supported by the context. If the
608 * AL_SOFT_source_resampler extension is unsupported this will be an empty
609 * vector, otherwise there will be at least one entry.
611 const Vector<String> &getAvailableResamplers();
613 * Queries the context's default resampler index. Be aware, if the
614 * AL_SOFT_source_resampler extension is unsupported the resampler list
615 * will be empty and this will resturn 0. If you try to access the
616 * resampler list with this index without the extension, undefined behavior
617 * (accessing an out of bounds array index) will occur.
619 ALsizei getDefaultResamplerIndex() const;
622 * Creates and caches a Buffer for the given audio file or resource name.
623 * Multiple calls with the same name will return the same Buffer object.
625 Buffer getBuffer(const String &name);
628 * Creates and caches a Buffer for the given audio file or resource name.
629 * Multiple calls with the same name will return the same Buffer object.
631 * The returned Buffer object will be scheduled for loading asynchronously,
632 * and must be checked with a call to Buffer::getLoadStatus prior to being
633 * played.
635 Buffer getBufferAsync(const String &name);
638 * Creates and caches a Buffer using the given name. The name may alias an
639 * audio file, but it must not currently exist in the buffer cache. As with
640 * other cached buffers, removeBuffer must be used to remove it from the
641 * cache.
643 Buffer createBufferFrom(const String &name, SharedPtr<Decoder> decoder);
646 * Creates and caches a Buffer using the given name. The name may alias an
647 * audio file, but it must not currently exist in the buffer cache.
649 * The returned Buffer object will be scheduled for loading asynchronously,
650 * and must be checked with a call to Buffer::getLoadStatus prior to being
651 * played. The given decoder will be held on to and used asynchronously to
652 * load the buffer. The decoder must not have its read or seek methods
653 * called while the buffer load status is pending.
655 Buffer createBufferAsyncFrom(const String &name, SharedPtr<Decoder> decoder);
658 * Deletes the cached Buffer object for the given audio file or
659 * resource name. The buffer must not be in use by a Source.
661 void removeBuffer(const String &name);
663 * Deletes the given cached buffer. The buffer must not be in use by a
664 * Source.
666 void removeBuffer(Buffer buffer);
669 * Creates a new Source. There is no practical limit to the number of
670 * sources you may create.
672 Source createSource();
674 AuxiliaryEffectSlot createAuxiliaryEffectSlot();
676 Effect createEffect();
678 SourceGroup createSourceGroup(String name);
679 SourceGroup getSourceGroup(const String &name);
681 void setDopplerFactor(ALfloat factor);
683 void setSpeedOfSound(ALfloat speed);
685 void setDistanceModel(DistanceModel model);
688 * Updates the context and all sources belonging to this context (you do
689 * not need to call the individual sources' update method if you call this
690 * function).
692 void update();
695 class ALURE_API Listener {
696 MAKE_PIMPL(Listener, ALListener)
698 public:
699 void setGain(ALfloat gain);
701 void setPosition(ALfloat x, ALfloat y, ALfloat z);
702 void setPosition(const ALfloat *pos);
704 void setVelocity(ALfloat x, ALfloat y, ALfloat z);
705 void setVelocity(const ALfloat *vel);
707 void setOrientation(ALfloat x1, ALfloat y1, ALfloat z1, ALfloat x2, ALfloat y2, ALfloat z2);
708 void setOrientation(const ALfloat *at, const ALfloat *up);
709 void setOrientation(const ALfloat *ori);
711 void setMetersPerUnit(ALfloat m_u);
715 enum class BufferLoadStatus {
716 Pending,
717 Ready
720 class ALURE_API Buffer {
721 MAKE_PIMPL(Buffer, ALBuffer)
723 public:
725 * Retrieves the length of the buffer in sample frames. The buffer must be
726 * fully loaded before this method is called.
728 ALuint getLength() const;
730 /** Retrieves the buffer's frequency in hz. */
731 ALuint getFrequency() const;
733 /** Retrieves the buffer's sample configuration. */
734 ChannelConfig getChannelConfig() const;
736 /** Retrieves the buffer's sample type. */
737 SampleType getSampleType() const;
740 * Retrieves the storage size used by the buffer, in bytes. The buffer must
741 * be fully loaded before this method is called.
743 ALuint getSize() const;
746 * Sets the buffer's loop points, used for looping sources. If the current
747 * context does not support the AL_SOFT_loop_points extension, start and
748 * end must be 0 and getLength() respectively. Otherwise, start must be
749 * less than end, and end must be less than or equal to getLength().
751 * The buffer must not be in use when this method is called, and the buffer
752 * must be fully loaded.
754 * \param start The starting point, in sample frames (inclusive).
755 * \param end The ending point, in sample frames (exclusive).
757 void setLoopPoints(ALuint start, ALuint end);
760 * Retrieves the current loop points as a [start,end) pair. The buffer must
761 * be fully loaded before this method is called.
763 std::pair<ALuint,ALuint> getLoopPoints() const;
766 * Retrieves the Source objects currently playing the buffer. Stopping the
767 * returned sources will allow the buffer to be removed from the context.
769 Vector<Source> getSources() const;
772 * Queries the buffer's load status. A return of BufferLoadStatus::Pending
773 * indicates the buffer is not finished loading and can't be used with a
774 * call to Source::play. Buffers created with Context::getBuffer will
775 * always return BufferLoadStatus::Ready.
777 BufferLoadStatus getLoadStatus();
779 /** Retrieves the name the buffer was created with. */
780 const String &getName() const;
782 /** Queries if the buffer is in use and can't be removed. */
783 bool isInUse() const;
787 enum class Spatialize {
788 Off = AL_FALSE,
789 On = AL_TRUE,
790 Auto = 0x0002 /* AL_AUTO_SOFT */
793 class ALURE_API Source {
794 MAKE_PIMPL(Source, ALSource)
796 public:
798 * Plays the source using buffer. The same buffer may be played from
799 * multiple sources simultaneously.
801 void play(Buffer buffer);
803 * Plays the source by streaming audio from decoder. This will use
804 * queuesize buffers, each with updatelen sample frames. The given decoder
805 * must *NOT* have its read or seek methods called from elsewhere while in
806 * use.
808 void play(SharedPtr<Decoder> decoder, ALuint updatelen, ALuint queuesize);
810 * Stops playback, releasing the buffer or decoder reference.
812 void stop();
814 /** Pauses the source if it is playing. */
815 void pause();
817 /** Resumes the source if it is paused. */
818 void resume();
820 /** Specifies if the source is currently playing. */
821 bool isPlaying() const;
823 /** Specifies if the source is currently paused. */
824 bool isPaused() const;
827 * Specifies the source's playback priority. Lowest priority sources will
828 * be evicted first when higher priority sources are played.
830 void setPriority(ALuint priority);
831 /** Retrieves the source's priority. */
832 ALuint getPriority() const;
835 * Sets the source's offset, in sample frames. If the source is playing or
836 * paused, it will go to that offset immediately, otherwise the source will
837 * start at the specified offset the next time it's played.
839 void setOffset(uint64_t offset);
841 * Retrieves the source offset in sample frames and its latency in nano-
842 * seconds. For streaming sources, this will be the offset from the
843 * beginning of the stream based on the decoder's reported position.
845 * If the AL_SOFT_source_latency extension is unsupported, the latency will
846 * be 0.
848 std::pair<uint64_t,std::chrono::nanoseconds> getSampleOffsetLatency() const;
849 uint64_t getSampleOffset() const { return std::get<0>(getSampleOffsetLatency()); }
851 * Retrieves the source offset and latency in seconds. For streaming
852 * sources, this will be the offset from the beginning of the stream based
853 * on the decoder's reported position.
855 * If the AL_SOFT_source_latency extension is unsupported, the latency will
856 * be 0.
858 std::pair<Seconds,Seconds> getSecOffsetLatency() const;
859 Seconds getSecOffset() const { return std::get<0>(getSecOffsetLatency()); }
862 * Specifies if the source should loop on the Buffer or Decoder object's
863 * loop points.
865 void setLooping(bool looping);
866 bool getLooping() const;
869 * Specifies a linear pitch shift base. A value of 1.0 is the default
870 * normal speed.
872 void setPitch(ALfloat pitch);
873 ALfloat getPitch() const;
876 * Specifies the base linear gain. A value of 1.0 is the default normal
877 * volume.
879 void setGain(ALfloat gain);
880 ALfloat getGain() const;
883 * Specifies the minimum and maximum gain. The source's gain is clamped to
884 * this range after distance attenuation and cone attenuation are applied
885 * to the gain base, although before the filter gain adjustements.
887 void setGainRange(ALfloat mingain, ALfloat maxgain);
888 std::pair<ALfloat,ALfloat> getGainRange() const;
889 ALfloat getMinGain() const { return std::get<0>(getGainRange()); }
890 ALfloat getMaxGain() const { return std::get<1>(getGainRange()); }
893 * Specifies the reference distance and maximum distance the source will
894 * use for the current distance model. For Clamped distance models, the
895 * source's calculated distance is clamped to the specified range before
896 * applying distance-related attenuation.
898 * For all distance models, the reference distance is the distance at which
899 * the source's volume will not have any extra attenuation (an effective
900 * gain multiplier of 1).
902 void setDistanceRange(ALfloat refdist, ALfloat maxdist);
903 std::pair<ALfloat,ALfloat> getDistanceRange() const;
904 ALfloat getReferenceDistance() const { return std::get<0>(getDistanceRange()); }
905 ALfloat getMaxDistance() const { return std::get<1>(getDistanceRange()); }
907 /** Specifies the source's 3D position. */
908 void setPosition(ALfloat x, ALfloat y, ALfloat z);
909 void setPosition(const ALfloat *pos);
910 Vector3 getPosition() const;
913 * Specifies the source's 3D velocity, in units per second. As with OpenAL,
914 * this does not actually alter the source's position, and instead just
915 * alters the pitch as determined by the doppler effect.
917 void setVelocity(ALfloat x, ALfloat y, ALfloat z);
918 void setVelocity(const ALfloat *vel);
919 Vector3 getVelocity() const;
922 * Specifies the source's 3D facing direction. Deprecated in favor of
923 * setOrientation.
925 void setDirection(ALfloat x, ALfloat y, ALfloat z);
926 void setDirection(const ALfloat *dir);
927 Vector3 getDirection() const;
930 * Specifies the source's 3D orientation. Note: unlike the AL_EXT_BFORMAT
931 * extension this property comes from, this also affects the facing
932 * direction, superceding setDirection.
934 void setOrientation(ALfloat x1, ALfloat y1, ALfloat z1, ALfloat x2, ALfloat y2, ALfloat z2);
935 void setOrientation(const ALfloat *at, const ALfloat *up);
936 void setOrientation(const ALfloat *ori);
937 std::pair<Vector3,Vector3> getOrientation() const;
940 * Specifies the source's cone angles, in degrees. The inner angle is the
941 * area within which the listener will hear the source with no extra
942 * attenuation, while the listener being outside of the outer angle will
943 * hear the source attenuated according to the outer cone gains.
945 void setConeAngles(ALfloat inner, ALfloat outer);
946 std::pair<ALfloat,ALfloat> getConeAngles() const;
947 ALfloat getInnerConeAngle() const { return std::get<0>(getConeAngles()); }
948 ALfloat getOuterConeAngle() const { return std::get<1>(getConeAngles()); }
951 * Specifies the linear gain multiplier when the listener is outside of the
952 * source's outer cone area. The specified gain applies to all frequencies,
953 * while gainhf applies extra attenuation to high frequencies.
955 * \param gainhf has no effect without the ALC_EXT_EFX extension.
957 void setOuterConeGains(ALfloat gain, ALfloat gainhf=1.0f);
958 std::pair<ALfloat,ALfloat> getOuterConeGains() const;
959 ALfloat getOuterConeGain() const { return std::get<0>(getOuterConeGains()); }
960 ALfloat getOuterConeGainHF() const { return std::get<1>(getOuterConeGains()); }
963 * Specifies the rolloff factors for the direct and send paths. This is
964 * effectively a distance scaling relative to the reference distance. Note:
965 * the room rolloff factor is 0 by default, disabling distance attenuation
966 * for send paths. This is because the reverb engine will, by default,
967 * apply a more realistic room attenuation based on the reverb decay time
968 * and direct path attenuation.
970 void setRolloffFactors(ALfloat factor, ALfloat roomfactor=0.0f);
971 std::pair<ALfloat,ALfloat> getRolloffFactors() const;
972 ALfloat getRolloffFactor() const { return std::get<0>(getRolloffFactors()); }
973 ALfloat getRoomRolloffFactor() const { return std::get<1>(getRolloffFactors()); }
976 * Specifies the doppler factor for the doppler effect's pitch shift. This
977 * effectively scales the source and listener velocities for the doppler
978 * calculation.
980 void setDopplerFactor(ALfloat factor);
981 ALfloat getDopplerFactor() const;
983 /** Specifies if the source properties are relative to the listener. */
984 void setRelative(bool relative);
985 bool getRelative() const;
988 * Specifies the source's radius. This causes the source to behave as if
989 * every point within the spherical area emits sound.
991 * Has no effect without the AL_EXT_SOURCE_RADIUS extension.
993 void setRadius(ALfloat radius);
994 ALfloat getRadius() const;
997 * Specifies the left and right channel angles, in radians, when playing a
998 * stereo buffer or stream. The angles go counter-clockwise, with 0 being
999 * in front and positive values going left.
1001 * Has no effect without the AL_EXT_STEREO_ANGLES extension.
1003 void setStereoAngles(ALfloat leftAngle, ALfloat rightAngle);
1004 std::pair<ALfloat,ALfloat> getStereoAngles() const;
1006 void set3DSpatialize(Spatialize spatialize);
1007 Spatialize get3DSpatialize() const;
1009 void setResamplerIndex(ALsizei index);
1010 ALsizei getResamplerIndex() const;
1012 void setAirAbsorptionFactor(ALfloat factor);
1013 ALfloat getAirAbsorptionFactor() const;
1015 void setGainAuto(bool directhf, bool send, bool sendhf);
1016 std::tuple<bool,bool,bool> getGainAuto() const;
1017 bool getDirectGainHFAuto() const { return std::get<0>(getGainAuto()); }
1018 bool getSendGainAuto() const { return std::get<1>(getGainAuto()); }
1019 bool getSendGainHFAuto() const { return std::get<2>(getGainAuto()); }
1021 /** Sets the filter properties on the direct path signal. */
1022 void setDirectFilter(const FilterParams &filter);
1024 * Sets the filter properties on the given send path signal. Any auxiliary
1025 * effect slot on the send path remains in place.
1027 void setSendFilter(ALuint send, const FilterParams &filter);
1029 * Connects the effect slot slot to the given send path. Any filter
1030 * properties on the send path remain as they were.
1032 void setAuxiliarySend(AuxiliaryEffectSlot slot, ALuint send);
1034 * Connects the effect slot slot to the given send path, using the filter
1035 * properties.
1037 void setAuxiliarySendFilter(AuxiliaryEffectSlot slot, ALuint send, const FilterParams &filter);
1040 * Updates the source, ensuring that resources are released when playback
1041 * is finished.
1043 void update();
1046 * Releases the source, stopping playback, releasing resources, and
1047 * returning it to the system.
1049 void release();
1053 class ALURE_API SourceGroup {
1054 MAKE_PIMPL(SourceGroup, ALSourceGroup)
1056 public:
1057 /** Retrieves the associated name of the source group. */
1058 const String &getName() const;
1061 * Adds source to the source group. A source may only be part of one group
1062 * at a time, and will automatically be removed from its current group as
1063 * needed.
1065 void addSource(Source source);
1066 /** Removes source from the source group. */
1067 void removeSource(Source source);
1069 /** Adds a list of sources to the group at once. */
1070 void addSources(ArrayView<Source> sources);
1071 /** Removes a list of sources from the source group. */
1072 void removeSources(ArrayView<Source> sources);
1075 * Adds group as a subgroup of the source group. This method will throw an
1076 * exception if group is being added to a group it has as a sub-group (i.e.
1077 * it would create a circular sub-group chain).
1079 void addSubGroup(SourceGroup group);
1080 /** Removes group from the source group. */
1081 void removeSubGroup(SourceGroup group);
1083 /** Returns the list of sources currently in the group. */
1084 Vector<Source> getSources() const;
1086 /** Returns the list of subgroups currently in the group. */
1087 Vector<SourceGroup> getSubGroups() const;
1089 /** Sets the source group gain, which accumulates with its sources. */
1090 void setGain(ALfloat gain);
1091 /** Gets the source group gain. */
1092 ALfloat getGain() const;
1094 /** Sets the source group pitch, which accumulates with its sources. */
1095 void setPitch(ALfloat pitch);
1096 /** Gets the source group pitch. */
1097 ALfloat getPitch() const;
1100 * Pauses all currently-playing sources that are under this group,
1101 * including sub-groups.
1103 void pauseAll() const;
1105 * Resumes all paused sources that are under this group, including
1106 * sub-groups.
1108 void resumeAll() const;
1110 /** Stops all sources that are under this group, including sub-groups. */
1111 void stopAll() const;
1114 * Releases the source group, removing all sources from it before being
1115 * freed.
1117 void release();
1121 struct SourceSend {
1122 Source mSource;
1123 ALuint mSend;
1126 class ALURE_API AuxiliaryEffectSlot {
1127 MAKE_PIMPL(AuxiliaryEffectSlot, ALAuxiliaryEffectSlot)
1129 public:
1130 void setGain(ALfloat gain);
1132 * If set to true, the reverb effect will automatically apply adjustments
1133 * to the source's send slot based on the effect properties.
1135 * Has no effect when using non-reverb effects. Default is true.
1137 void setSendAuto(bool sendauto);
1140 * Updates the effect slot with a new effect. The given effect object may
1141 * be altered or destroyed without affecting the effect slot.
1143 void applyEffect(Effect effect);
1146 * Releases the effect slot, returning it to the system. It must not be in
1147 * use by a source.
1149 void release();
1152 * Retrieves each Source object and its pairing send this effect slot is
1153 * set on. Setting a different (or null) effect slot on each source's given
1154 * send will allow the effect slot to be released.
1156 Vector<SourceSend> getSourceSends() const;
1158 /** Determines if the effect slot is in use by a source. */
1159 bool isInUse() const;
1163 class ALURE_API Effect {
1164 MAKE_PIMPL(Effect, ALEffect)
1166 public:
1168 * Updates the effect with the specified reverb properties. If the
1169 * EAXReverb effect is not supported, it will automatically attempt to
1170 * downgrade to the Standard Reverb effect.
1172 void setReverbProperties(const EFXEAXREVERBPROPERTIES &props);
1174 void destroy();
1179 * Audio decoder interface. Applications may derive from this, implementing the
1180 * necessary methods, and use it in places the API wants a Decoder object.
1182 class ALURE_API Decoder {
1183 public:
1184 virtual ~Decoder() { }
1186 /** Retrieves the sample frequency, in hz, of the audio being decoded. */
1187 virtual ALuint getFrequency() const = 0;
1188 /** Retrieves the channel configuration of the audio being decoded. */
1189 virtual ChannelConfig getChannelConfig() const = 0;
1190 /** Retrieves the sample type of the audio being decoded. */
1191 virtual SampleType getSampleType() const = 0;
1194 * Retrieves the total length of the audio, in sample frames. If unknown,
1195 * returns 0. Note that if the returned length is 0, the decoder may not be
1196 * used to load a Buffer.
1198 virtual uint64_t getLength() const = 0;
1200 * Retrieves the current sample frame position (i.e. the number of sample
1201 * frames from the beginning).
1203 virtual uint64_t getPosition() const = 0;
1205 * Seek to pos, specified in sample frames. Returns true if the seek was
1206 * successful.
1208 virtual bool seek(uint64_t pos) = 0;
1211 * Retrieves the loop points, in sample frames, as a [start,end) pair. If
1212 * start >= end, use all available data.
1214 virtual std::pair<uint64_t,uint64_t> getLoopPoints() const = 0;
1217 * Decodes count sample frames, writing them to ptr, and returns the number
1218 * of sample frames written. Returning less than the requested count
1219 * indicates the end of the audio.
1221 virtual ALuint read(ALvoid *ptr, ALuint count) = 0;
1225 * Audio decoder factory interface. Applications may derive from this,
1226 * implementing the necessary methods, and use it in places the API wants a
1227 * DecoderFactory object.
1229 class ALURE_API DecoderFactory {
1230 public:
1231 virtual ~DecoderFactory() { }
1234 * Creates and returns a Decoder instance for the given resource file. If
1235 * the decoder needs to retain the file handle for reading as-needed, it
1236 * should move the UniquePtr to internal storage.
1238 * \return nullptr if a decoder can't be created from the file.
1240 virtual SharedPtr<Decoder> createDecoder(UniquePtr<std::istream> &file) = 0;
1244 * Registers a decoder factory for decoding audio. Registered factories are
1245 * used in lexicographical order, e.g. if Factory1 is registered with name1 and
1246 * Factory2 is registered with name2, Factory1 will be used before Factory2 if
1247 * name1 < name2. Internal decoder factories are always used after registered
1248 * ones.
1250 * Alure retains a reference to the DecoderFactory instance and will release it
1251 * (potentially destroying the object) when the library unloads.
1253 * \param name A unique name identifying this decoder factory.
1254 * \param factory A DecoderFactory instance used to create Decoder instances.
1256 ALURE_API void RegisterDecoder(const String &name, UniquePtr<DecoderFactory> factory);
1259 * Unregisters a decoder factory by name. Alure returns the instance back to
1260 * the application.
1262 * \param name The unique name identifying a previously-registered decoder
1263 * factory.
1265 * \return The unregistered decoder factory instance, or 0 (nullptr) if a
1266 * decoder factory with the given name doesn't exist.
1268 ALURE_API UniquePtr<DecoderFactory> UnregisterDecoder(const String &name);
1272 * A file I/O factory interface. Applications may derive from this and set an
1273 * instance to be used by the audio decoders. By default, the library uses
1274 * standard I/O.
1276 class ALURE_API FileIOFactory {
1277 public:
1279 * Sets the factory instance to be used by the audio decoders. If a
1280 * previous factory was set, it's returned to the application. Passing in a
1281 * NULL factory reverts to the default.
1283 static UniquePtr<FileIOFactory> set(UniquePtr<FileIOFactory> factory);
1286 * Gets the current FileIOFactory instance being used by the audio
1287 * decoders.
1289 static FileIOFactory &get();
1291 virtual ~FileIOFactory() { }
1293 /** Opens a read-only binary file for the given name. */
1294 virtual UniquePtr<std::istream> openFile(const String &name) = 0;
1299 * A message handler interface. Applications may derive from this and set an
1300 * instance on a context to receive messages. The base methods are no-ops, so
1301 * derived classes only need to implement methods for relevant messages.
1303 * It's recommended that applications mark their handler methods using the
1304 * override keyword, to ensure they're properly overriding the base methods in
1305 * case they change.
1307 class ALURE_API MessageHandler {
1308 public:
1309 virtual ~MessageHandler();
1312 * Called when the given device has been disconnected and is no longer
1313 * usable for output. As per the ALC_EXT_disconnect specification,
1314 * disconnected devices remain valid, however all playing sources are
1315 * automatically stopped, any sources that are attempted to play will
1316 * immediately stop, and new contexts may not be created on the device.
1318 * Note that connection status is checked during Context::update calls, so
1319 * that method must be called regularly to be notified when a device is
1320 * disconnected. This method may not be called if the device lacks support
1321 * for the ALC_EXT_disconnect extension.
1323 * WARNING: Do not attempt to clean up resources within this callback
1324 * method, as Alure is in the middle of doing updates. Instead, flag the
1325 * device as having been lost and do cleanup later.
1327 virtual void deviceDisconnected(Device device);
1330 * Called when the given source reaches the end of the buffer or stream.
1332 * Sources that stopped automatically will be detected upon a call to
1333 * Context::update or Source::update.
1335 virtual void sourceStopped(Source source);
1338 * Called when the given source was forced to stop. This can be because
1339 * either there were no more system sources and a higher-priority source
1340 * needs to play, or it's part of a SourceGroup (or sub-group thereof) that
1341 * had its SourceGroup::stopAll method called.
1343 virtual void sourceForceStopped(Source source);
1346 * Called when a new buffer is about to be created and loaded. May be
1347 * called asynchronously for buffers being loaded asynchronously.
1349 * \param name The resource name, as passed to Context::getBuffer.
1350 * \param channels Channel configuration of the given audio data.
1351 * \param type Sample type of the given audio data.
1352 * \param samplerate Sample rate of the given audio data.
1353 * \param data The audio data that is about to be fed to the OpenAL buffer.
1355 virtual void bufferLoading(const String &name, ChannelConfig channels, SampleType type, ALuint samplerate, const Vector<ALbyte> &data);
1358 * Called when a resource isn't found, allowing the app to substitute in a
1359 * different resource. For buffers created with Context::getBuffer or
1360 * Context::getBufferAsync, the original name will still be used for the
1361 * cache map so the app doesn't have to keep track of substituted resource
1362 * names.
1364 * This will be called again if the new name isn't found.
1366 * \param name The resource name that was not found.
1367 * \return The replacement resource name to use instead. Returning an empty
1368 * string means to stop trying.
1370 virtual String resourceNotFound(const String &name);
1373 } // namespace alure
1375 #endif /* AL_ALURE2_H */