19 #include "decoders/wave.hpp"
21 #ifdef HAVE_VORBISFILE
22 #include "decoders/vorbisfile.hpp"
25 #include "decoders/flac.hpp"
28 #include "decoders/opusfile.hpp"
30 #ifdef HAVE_LIBSNDFILE
31 #include "decoders/sndfile.hpp"
34 #include "decoders/mpg123.hpp"
37 #include "devicemanager.h"
41 #include "auxeffectslot.h"
43 #include "sourcegroup.h"
46 #define WIN32_LEAN_AND_MEAN
53 // Implements a FNV-1a hash for StringView. NOTE: This is *NOT* guaranteed
54 // compatible with std::hash<String>! The standard does not give any specific
55 // hash implementation, nor a way for applications to access the same hash
56 // function as std::string (short of copying into a string and hashing that).
57 // So if you need Strings and StringViews to result in the same hash for the
58 // same set of characters, hash StringViews created from the Strings.
60 struct hash
<alure::StringView
> {
61 size_t operator()(const alure::StringView
&str
) const noexcept
63 using traits_type
= alure::StringView::traits_type
;
65 if /*constexpr*/ (sizeof(size_t) == 8)
67 static constexpr size_t hash_offset
= 0xcbf29ce484222325;
68 static constexpr size_t hash_prime
= 0x100000001b3;
70 size_t val
= hash_offset
;
72 val
= (val
^traits_type::to_int_type(ch
)) * hash_prime
;
77 static constexpr size_t hash_offset
= 0x811c9dc5;
78 static constexpr size_t hash_prime
= 0x1000193;
80 size_t val
= hash_offset
;
82 val
= (val
^traits_type::to_int_type(ch
)) * hash_prime
;
93 // Global mutex to protect global context changes
94 std::mutex mGlobalCtxMutex
;
97 // Windows' std::ifstream fails with non-ANSI paths since the standard only
98 // specifies names using const char* (or std::string). MSVC has a non-standard
99 // extension using const wchar_t* (or std::wstring?) to handle Unicode paths,
100 // but not all Windows compilers support it. So we have to make our own istream
101 // that accepts UTF-8 paths and forwards to Unicode-aware I/O functions.
102 class StreamBuf final
: public std::streambuf
{
103 alure::Array
<char_type
,4096> mBuffer
;
104 HANDLE mFile
{INVALID_HANDLE_VALUE
};
106 int_type
underflow() override
108 if(mFile
!= INVALID_HANDLE_VALUE
&& gptr() == egptr())
110 // Read in the next chunk of data, and set the pointers on success
112 if(ReadFile(mFile
, mBuffer
.data(), mBuffer
.size(), &got
, NULL
))
113 setg(mBuffer
.data(), mBuffer
.data(), mBuffer
.data()+got
);
115 if(gptr() == egptr())
116 return traits_type::eof();
117 return traits_type::to_int_type(*gptr());
120 pos_type
seekoff(off_type offset
, std::ios_base::seekdir whence
, std::ios_base::openmode mode
) override
122 if(mFile
== INVALID_HANDLE_VALUE
|| (mode
&std::ios_base::out
) || !(mode
&std::ios_base::in
))
123 return traits_type::eof();
128 case std::ios_base::beg
:
129 fpos
.QuadPart
= offset
;
130 if(!SetFilePointerEx(mFile
, fpos
, &fpos
, FILE_BEGIN
))
131 return traits_type::eof();
134 case std::ios_base::cur
:
135 // If the offset remains in the current buffer range, just
136 // update the pointer.
137 if((offset
>= 0 && offset
< off_type(egptr()-gptr())) ||
138 (offset
< 0 && -offset
<= off_type(gptr()-eback())))
140 // Get the current file offset to report the correct read
143 if(!SetFilePointerEx(mFile
, fpos
, &fpos
, FILE_CURRENT
))
144 return traits_type::eof();
145 setg(eback(), gptr()+offset
, egptr());
146 return fpos
.QuadPart
- off_type(egptr()-gptr());
148 // Need to offset for the file offset being at egptr() while
149 // the requested offset is relative to gptr().
150 offset
-= off_type(egptr()-gptr());
151 fpos
.QuadPart
= offset
;
152 if(!SetFilePointerEx(mFile
, fpos
, &fpos
, FILE_CURRENT
))
153 return traits_type::eof();
156 case std::ios_base::end
:
157 fpos
.QuadPart
= offset
;
158 if(!SetFilePointerEx(mFile
, fpos
, &fpos
, FILE_END
))
159 return traits_type::eof();
163 return traits_type::eof();
166 return fpos
.QuadPart
;
169 pos_type
seekpos(pos_type pos
, std::ios_base::openmode mode
) override
171 // Simplified version of seekoff
172 if(mFile
== INVALID_HANDLE_VALUE
|| (mode
&std::ios_base::out
) || !(mode
&std::ios_base::in
))
173 return traits_type::eof();
177 if(!SetFilePointerEx(mFile
, fpos
, &fpos
, FILE_BEGIN
))
178 return traits_type::eof();
181 return fpos
.QuadPart
;
185 bool open(const char *filename
)
187 alure::Vector
<wchar_t> wname
;
190 wnamelen
= MultiByteToWideChar(CP_UTF8
, 0, filename
, -1, NULL
, 0);
191 if(wnamelen
<= 0) return false;
193 wname
.resize(wnamelen
);
194 MultiByteToWideChar(CP_UTF8
, 0, filename
, -1, wname
.data(), wnamelen
);
196 mFile
= CreateFileW(wname
.data(), GENERIC_READ
, FILE_SHARE_READ
, NULL
,
197 OPEN_EXISTING
, FILE_ATTRIBUTE_NORMAL
, nullptr);
198 if(mFile
== INVALID_HANDLE_VALUE
) return false;
202 bool is_open() const noexcept
{ return mFile
!= INVALID_HANDLE_VALUE
; }
204 StreamBuf() = default;
205 ~StreamBuf() override
207 if(mFile
!= INVALID_HANDLE_VALUE
)
209 mFile
= INVALID_HANDLE_VALUE
;
213 // Inherit from std::istream to use our custom streambuf
214 class Stream final
: public std::istream
{
216 Stream(const char *filename
) : std::istream(new StreamBuf())
218 // Set the failbit if the file failed to open.
219 if(!(static_cast<StreamBuf
*>(rdbuf())->open(filename
)))
225 bool is_open() const noexcept
{ return static_cast<StreamBuf
*>(rdbuf())->is_open(); }
229 using DecoderEntryPair
= std::pair
<alure::String
,alure::UniquePtr
<alure::DecoderFactory
>>;
230 const DecoderEntryPair sDefaultDecoders
[] = {
232 { "_alure_int_wave", alure::MakeUnique
<alure::WaveDecoderFactory
>() },
234 #ifdef HAVE_VORBISFILE
235 { "_alure_int_vorbis", alure::MakeUnique
<alure::VorbisFileDecoderFactory
>() },
238 { "_alure_int_flac", alure::MakeUnique
<alure::FlacDecoderFactory
>() },
241 { "_alure_int_opus", alure::MakeUnique
<alure::OpusFileDecoderFactory
>() },
243 #ifdef HAVE_LIBSNDFILE
244 { "_alure_int_sndfile", alure::MakeUnique
<alure::SndFileDecoderFactory
>() },
247 { "_alure_int_mpg123", alure::MakeUnique
<alure::Mpg123DecoderFactory
>() },
250 alure::Vector
<DecoderEntryPair
> sDecoders
;
253 alure::DecoderOrExceptT
GetDecoder(alure::UniquePtr
<std::istream
> &file
,
254 alure::ArrayView
<DecoderEntryPair
> decoders
)
256 while(!decoders
.empty())
258 alure::DecoderFactory
*factory
= decoders
.front().second
.get();
259 auto decoder
= factory
->createDecoder(file
);
260 if(decoder
) return std::move(decoder
);
262 if(!file
|| !(file
->clear(),file
->seekg(0)))
263 return std::make_exception_ptr(
264 std::runtime_error("Failed to rewind file for the next decoder factory")
267 decoders
= decoders
.slice(1);
270 return alure::SharedPtr
<alure::Decoder
>(nullptr);
273 static alure::DecoderOrExceptT
GetDecoder(alure::UniquePtr
<std::istream
> file
)
275 auto decoder
= GetDecoder(file
, sDecoders
);
276 if(std::holds_alternative
<std::exception_ptr
>(decoder
)) return decoder
;
277 if(std::get
<alure::SharedPtr
<alure::Decoder
>>(decoder
)) return decoder
;
278 decoder
= GetDecoder(file
, sDefaultDecoders
);
279 if(std::holds_alternative
<std::exception_ptr
>(decoder
)) return decoder
;
280 if(std::get
<alure::SharedPtr
<alure::Decoder
>>(decoder
)) return decoder
;
281 return (decoder
= std::make_exception_ptr(std::runtime_error("No decoder found")));
284 class DefaultFileIOFactory final
: public alure::FileIOFactory
{
285 alure::UniquePtr
<std::istream
> openFile(const alure::String
&name
) noexcept override
288 auto file
= alure::MakeUnique
<Stream
>(name
.c_str());
290 auto file
= alure::MakeUnique
<std::ifstream
>(name
.c_str(), std::ios::binary
);
292 if(!file
->is_open()) file
= nullptr;
293 return std::move(file
);
296 DefaultFileIOFactory sDefaultFileFactory
;
298 alure::UniquePtr
<alure::FileIOFactory
> sFileFactory
;
305 std::variant
<std::monostate
,uint64_t> ParseTimeval(StringView strval
, double srate
) noexcept
309 size_t cpos
= strval
.find_first_of(':');
310 if(cpos
== StringView::npos
)
312 // No colon is present, treat it as a plain sample offset
313 uint64_t val
= std::stoull(String(strval
), &endpos
);
314 if(endpos
!= strval
.length()) return {};
318 // Value is not a sample offset. Its format is [[HH:]MM]:SS[.sss] (at
319 // least one colon must exist to be interpreted this way).
324 // If a non-empty first value, parse it (may be hours or minutes)
325 val
= std::stoul(String(strval
.data(), cpos
), &endpos
);
326 if(endpos
!= cpos
) return {};
329 strval
= strval
.substr(cpos
+1);
330 cpos
= strval
.find_first_of(':');
331 if(cpos
!= StringView::npos
)
333 // If a second colon is present, the first value was hours and this is
334 // minutes, otherwise the first value was minutes.
339 val2
= std::stoul(String(strval
.data(), cpos
), &endpos
);
340 if(endpos
!= cpos
|| val2
>= 60) return {};
343 // Combines hours and minutes into the full minute count
344 if(val
> std::numeric_limits
<uint64_t>::max()/60)
347 strval
= strval
.substr(cpos
+1);
353 // Parse the seconds and its fraction. Only include the first 3 decimal
354 // places for millisecond precision.
355 size_t dpos
= strval
.find_first_of('.');
356 String str
= (dpos
== StringView::npos
) ?
357 String(strval
) : String(strval
.substr(0, dpos
+4));
358 secs
= std::stod(str
, &endpos
);
359 if(endpos
!= str
.length() || !(secs
>= 0.0 && secs
< 60.0))
363 // Convert minutes to seconds, add the seconds, then convert to samples.
364 return static_cast<uint64_t>((val
*60.0 + secs
) * srate
);
373 Decoder::~Decoder() { }
374 DecoderFactory::~DecoderFactory() { }
376 void RegisterDecoder(StringView name
, UniquePtr
<DecoderFactory
> factory
)
378 auto iter
= std::lower_bound(sDecoders
.begin(), sDecoders
.end(), name
,
379 [](const DecoderEntryPair
&entry
, StringView rhs
) -> bool
380 { return entry
.first
< rhs
; }
382 if(iter
!= sDecoders
.end())
383 throw std::runtime_error("Decoder factory already registered");
384 sDecoders
.insert(iter
, std::make_pair(String(name
), std::move(factory
)));
387 UniquePtr
<DecoderFactory
> UnregisterDecoder(StringView name
) noexcept
389 UniquePtr
<DecoderFactory
> factory
;
390 auto iter
= std::lower_bound(sDecoders
.begin(), sDecoders
.end(), name
,
391 [](const DecoderEntryPair
&entry
, StringView rhs
) noexcept
-> bool
392 { return entry
.first
< rhs
; }
394 if(iter
!= sDecoders
.end())
396 factory
= std::move(iter
->second
);
397 sDecoders
.erase(iter
);
404 FileIOFactory::~FileIOFactory() { }
406 UniquePtr
<FileIOFactory
> FileIOFactory::set(UniquePtr
<FileIOFactory
> factory
) noexcept
408 sFileFactory
.swap(factory
);
412 FileIOFactory
&FileIOFactory::get() noexcept
414 FileIOFactory
*factory
= sFileFactory
.get();
415 if(factory
) return *factory
;
416 return sDefaultFileFactory
;
420 // Default message handler methods are no-ops.
421 MessageHandler::~MessageHandler()
425 void MessageHandler::deviceDisconnected(Device
) noexcept
429 void MessageHandler::sourceStopped(Source
) noexcept
433 void MessageHandler::sourceForceStopped(Source
) noexcept
437 void MessageHandler::bufferLoading(StringView
, ChannelConfig
, SampleType
, ALuint
, ArrayView
<ALbyte
>) noexcept
441 String
MessageHandler::resourceNotFound(StringView
) noexcept
448 static inline void LoadALFunc(T
**func
, const char *name
)
449 { *func
= reinterpret_cast<T
*>(alGetProcAddress(name
)); }
451 static void LoadNothing(ContextImpl
*) { }
453 static void LoadEFX(ContextImpl
*ctx
)
455 LoadALFunc(&ctx
->alGenEffects
, "alGenEffects");
456 LoadALFunc(&ctx
->alDeleteEffects
, "alDeleteEffects");
457 LoadALFunc(&ctx
->alIsEffect
, "alIsEffect");
458 LoadALFunc(&ctx
->alEffecti
, "alEffecti");
459 LoadALFunc(&ctx
->alEffectiv
, "alEffectiv");
460 LoadALFunc(&ctx
->alEffectf
, "alEffectf");
461 LoadALFunc(&ctx
->alEffectfv
, "alEffectfv");
462 LoadALFunc(&ctx
->alGetEffecti
, "alGetEffecti");
463 LoadALFunc(&ctx
->alGetEffectiv
, "alGetEffectiv");
464 LoadALFunc(&ctx
->alGetEffectf
, "alGetEffectf");
465 LoadALFunc(&ctx
->alGetEffectfv
, "alGetEffectfv");
467 LoadALFunc(&ctx
->alGenFilters
, "alGenFilters");
468 LoadALFunc(&ctx
->alDeleteFilters
, "alDeleteFilters");
469 LoadALFunc(&ctx
->alIsFilter
, "alIsFilter");
470 LoadALFunc(&ctx
->alFilteri
, "alFilteri");
471 LoadALFunc(&ctx
->alFilteriv
, "alFilteriv");
472 LoadALFunc(&ctx
->alFilterf
, "alFilterf");
473 LoadALFunc(&ctx
->alFilterfv
, "alFilterfv");
474 LoadALFunc(&ctx
->alGetFilteri
, "alGetFilteri");
475 LoadALFunc(&ctx
->alGetFilteriv
, "alGetFilteriv");
476 LoadALFunc(&ctx
->alGetFilterf
, "alGetFilterf");
477 LoadALFunc(&ctx
->alGetFilterfv
, "alGetFilterfv");
479 LoadALFunc(&ctx
->alGenAuxiliaryEffectSlots
, "alGenAuxiliaryEffectSlots");
480 LoadALFunc(&ctx
->alDeleteAuxiliaryEffectSlots
, "alDeleteAuxiliaryEffectSlots");
481 LoadALFunc(&ctx
->alIsAuxiliaryEffectSlot
, "alIsAuxiliaryEffectSlot");
482 LoadALFunc(&ctx
->alAuxiliaryEffectSloti
, "alAuxiliaryEffectSloti");
483 LoadALFunc(&ctx
->alAuxiliaryEffectSlotiv
, "alAuxiliaryEffectSlotiv");
484 LoadALFunc(&ctx
->alAuxiliaryEffectSlotf
, "alAuxiliaryEffectSlotf");
485 LoadALFunc(&ctx
->alAuxiliaryEffectSlotfv
, "alAuxiliaryEffectSlotfv");
486 LoadALFunc(&ctx
->alGetAuxiliaryEffectSloti
, "alGetAuxiliaryEffectSloti");
487 LoadALFunc(&ctx
->alGetAuxiliaryEffectSlotiv
, "alGetAuxiliaryEffectSlotiv");
488 LoadALFunc(&ctx
->alGetAuxiliaryEffectSlotf
, "alGetAuxiliaryEffectSlotf");
489 LoadALFunc(&ctx
->alGetAuxiliaryEffectSlotfv
, "alGetAuxiliaryEffectSlotfv");
492 static void LoadSourceResampler(ContextImpl
*ctx
)
494 LoadALFunc(&ctx
->alGetStringiSOFT
, "alGetStringiSOFT");
497 static void LoadSourceLatency(ContextImpl
*ctx
)
499 LoadALFunc(&ctx
->alGetSourcei64vSOFT
, "alGetSourcei64vSOFT");
500 LoadALFunc(&ctx
->alGetSourcedvSOFT
, "alGetSourcedvSOFT");
503 static const struct {
506 void (&loader
)(ContextImpl
*);
507 } ALExtensionList
[] = {
508 { AL::EXT_EFX
, "ALC_EXT_EFX", LoadEFX
},
510 { AL::EXT_FLOAT32
, "AL_EXT_FLOAT32", LoadNothing
},
511 { AL::EXT_MCFORMATS
, "AL_EXT_MCFORMATS", LoadNothing
},
512 { AL::EXT_BFORMAT
, "AL_EXT_BFORMAT", LoadNothing
},
514 { AL::EXT_MULAW
, "AL_EXT_MULAW", LoadNothing
},
515 { AL::EXT_MULAW_MCFORMATS
, "AL_EXT_MULAW_MCFORMATS", LoadNothing
},
516 { AL::EXT_MULAW_BFORMAT
, "AL_EXT_MULAW_BFORMAT", LoadNothing
},
518 { AL::SOFT_loop_points
, "AL_SOFT_loop_points", LoadNothing
},
519 { AL::SOFT_source_latency
, "AL_SOFT_source_latency", LoadSourceLatency
},
520 { AL::SOFT_source_resampler
, "AL_SOFT_source_resampler", LoadSourceResampler
},
521 { AL::SOFT_source_spatialize
, "AL_SOFT_source_spatialize", LoadNothing
},
523 { AL::EXT_disconnect
, "ALC_EXT_disconnect", LoadNothing
},
525 { AL::EXT_SOURCE_RADIUS
, "AL_EXT_SOURCE_RADIUS", LoadNothing
},
526 { AL::EXT_STEREO_ANGLES
, "AL_EXT_STEREO_ANGLES", LoadNothing
},
530 ContextImpl
*ContextImpl::sCurrentCtx
= nullptr;
531 thread_local ContextImpl
*ContextImpl::sThreadCurrentCtx
= nullptr;
533 std::atomic
<uint64_t> ContextImpl::sContextSetCount
{0};
535 void ContextImpl::MakeCurrent(ContextImpl
*context
)
537 std::unique_lock
<std::mutex
> ctxlock(mGlobalCtxMutex
);
539 if(alcMakeContextCurrent(context
? context
->getALCcontext() : nullptr) == ALC_FALSE
)
540 throw std::runtime_error("Call to alcMakeContextCurrent failed");
544 std::call_once(context
->mSetExts
, std::mem_fn(&ContextImpl::setupExts
), context
);
546 std::swap(sCurrentCtx
, context
);
547 if(context
) context
->decRef();
549 if(sThreadCurrentCtx
)
550 sThreadCurrentCtx
->decRef();
551 sThreadCurrentCtx
= nullptr;
552 sContextSetCount
.fetch_add(1, std::memory_order_release
);
554 if((context
= sCurrentCtx
) != nullptr)
557 context
->mWakeThread
.notify_all();
561 void ContextImpl::MakeThreadCurrent(ContextImpl
*context
)
563 if(!DeviceManagerImpl::SetThreadContext
)
564 throw std::runtime_error("Thread-local contexts unsupported");
565 if(DeviceManagerImpl::SetThreadContext(context
? context
->getALCcontext() : nullptr) == ALC_FALSE
)
566 throw std::runtime_error("Call to alcSetThreadContext failed");
570 std::call_once(context
->mSetExts
, std::mem_fn(&ContextImpl::setupExts
), context
);
572 if(sThreadCurrentCtx
)
573 sThreadCurrentCtx
->decRef();
574 sThreadCurrentCtx
= context
;
575 sContextSetCount
.fetch_add(1, std::memory_order_release
);
578 void ContextImpl::setupExts()
580 ALCdevice
*device
= mDevice
->getALCdevice();
582 for(const auto &entry
: ALExtensionList
)
584 if((strncmp(entry
.name
, "ALC", 3) == 0) ? alcIsExtensionPresent(device
, entry
.name
) :
585 alIsExtensionPresent(entry
.name
))
587 mHasExt
.set(static_cast<size_t>(entry
.extension
));
594 void ContextImpl::backgroundProc()
596 if(DeviceManagerImpl::SetThreadContext
&& mDevice
->hasExtension(ALC::EXT_thread_local_context
))
597 DeviceManagerImpl::SetThreadContext(getALCcontext());
599 std::chrono::steady_clock::time_point basetime
= std::chrono::steady_clock::now();
600 std::chrono::milliseconds
waketime(0);
601 std::unique_lock
<std::mutex
> ctxlock(mGlobalCtxMutex
);
602 while(!mQuitThread
.load(std::memory_order_acquire
))
605 std::lock_guard
<std::mutex
> srclock(mSourceStreamMutex
);
606 mStreamingSources
.erase(
607 std::remove_if(mStreamingSources
.begin(), mStreamingSources
.end(),
608 [](SourceImpl
*source
) -> bool
609 { return !source
->updateAsync(); }
610 ), mStreamingSources
.end()
614 // Only do one pending buffer at a time. In case there's several large
615 // buffers to load, we still need to process streaming sources so they
617 PendingPromise
*lastpb
= mPendingCurrent
.load(std::memory_order_acquire
);
618 if(PendingPromise
*pb
= lastpb
->mNext
.load(std::memory_order_relaxed
))
620 pb
->mBuffer
->load(pb
->mFrames
, pb
->mFormat
, std::move(pb
->mDecoder
), this);
621 pb
->mPromise
.set_value(Buffer(pb
->mBuffer
));
622 Promise
<Buffer
>().swap(pb
->mPromise
);
623 mPendingCurrent
.store(pb
, std::memory_order_release
);
627 std::unique_lock
<std::mutex
> wakelock(mWakeMutex
);
628 if(!mQuitThread
.load(std::memory_order_acquire
) && lastpb
->mNext
.load(std::memory_order_acquire
) == nullptr)
632 std::chrono::milliseconds interval
= mWakeInterval
.load(std::memory_order_relaxed
);
633 if(interval
.count() == 0)
634 mWakeThread
.wait(wakelock
);
637 auto now
= std::chrono::steady_clock::now() - basetime
;
640 auto mult
= (now
-waketime
+ interval
-std::chrono::milliseconds(1)) / interval
;
641 waketime
+= interval
* mult
;
643 mWakeThread
.wait_until(wakelock
, waketime
+ basetime
);
648 while(!mQuitThread
.load(std::memory_order_acquire
) &&
649 alcGetCurrentContext() != getALCcontext())
650 mWakeThread
.wait(ctxlock
);
655 if(DeviceManagerImpl::SetThreadContext
)
656 DeviceManagerImpl::SetThreadContext(nullptr);
660 ContextImpl::ContextImpl(ALCcontext
*context
, DeviceImpl
*device
)
661 : mListener(this), mContext(context
), mDevice(device
), mIsConnected(true), mIsBatching(false)
664 mSourceIds
.reserve(256);
665 mPendingHead
= new PendingPromise
;
666 mPendingCurrent
.store(mPendingHead
, std::memory_order_relaxed
);
667 mPendingTail
= mPendingHead
;
670 ContextImpl::~ContextImpl()
672 PendingPromise
*pb
= mPendingTail
;
675 PendingPromise
*next
= pb
->mNext
.load(std::memory_order_relaxed
);
679 mPendingCurrent
.store(nullptr, std::memory_order_relaxed
);
680 mPendingHead
= nullptr;
681 mPendingTail
= nullptr;
685 void Context::destroy()
687 ContextImpl
*i
= pImpl
;
691 void ContextImpl::destroy()
694 throw std::runtime_error("Context is in use");
695 if(!mBuffers
.empty())
696 throw std::runtime_error("Trying to destroy a context with buffers");
698 if(mThread
.joinable())
700 std::unique_lock
<std::mutex
> lock(mWakeMutex
);
701 mQuitThread
.store(true, std::memory_order_release
);
703 mWakeThread
.notify_all();
707 alcDestroyContext(mContext
);
710 mDevice
->removeContext(this);
714 DECL_THUNK0(void, Context
, startBatch
,)
715 void ContextImpl::startBatch()
717 alcSuspendContext(mContext
);
721 DECL_THUNK0(void, Context
, endBatch
,)
722 void ContextImpl::endBatch()
724 alcProcessContext(mContext
);
729 DECL_THUNK1(SharedPtr
<MessageHandler
>, Context
, setMessageHandler
,, SharedPtr
<MessageHandler
>)
730 SharedPtr
<MessageHandler
> ContextImpl::setMessageHandler(SharedPtr
<MessageHandler
>&& handler
)
732 std::lock_guard
<std::mutex
> lock(mGlobalCtxMutex
);
733 mMessage
.swap(handler
);
738 DECL_THUNK1(void, Context
, setAsyncWakeInterval
,, std::chrono::milliseconds
)
739 void ContextImpl::setAsyncWakeInterval(std::chrono::milliseconds interval
)
741 if(interval
.count() < 0 || interval
> std::chrono::seconds(1))
742 throw std::out_of_range("Async wake interval out of range");
743 mWakeInterval
.store(interval
);
744 mWakeMutex
.lock(); mWakeMutex
.unlock();
745 mWakeThread
.notify_all();
749 DecoderOrExceptT
ContextImpl::findDecoder(StringView name
)
751 String oldname
= String(name
);
752 auto file
= FileIOFactory::get().openFile(oldname
);
755 // Resource not found. Try to find a substitute.
757 return std::make_exception_ptr(std::runtime_error("Failed to open file"));
759 String
newname(mMessage
->resourceNotFound(oldname
));
761 return std::make_exception_ptr(std::runtime_error("Failed to open file"));
762 file
= FileIOFactory::get().openFile(newname
);
763 oldname
= std::move(newname
);
766 return GetDecoder(std::move(file
));
769 DECL_THUNK1(SharedPtr
<Decoder
>, Context
, createDecoder
,, StringView
)
770 SharedPtr
<Decoder
> ContextImpl::createDecoder(StringView name
)
773 DecoderOrExceptT dec
= findDecoder(name
);
774 if(SharedPtr
<Decoder
> *decoder
= std::get_if
<SharedPtr
<Decoder
>>(&dec
))
775 return std::move(*decoder
);
776 std::rethrow_exception(std::get
<std::exception_ptr
>(dec
));
780 DECL_THUNK2(bool, Context
, isSupported
, const, ChannelConfig
, SampleType
)
781 bool ContextImpl::isSupported(ChannelConfig channels
, SampleType type
) const
784 return GetFormat(channels
, type
) != AL_NONE
;
788 DECL_THUNK0(ArrayView
<String
>, Context
, getAvailableResamplers
,)
789 ArrayView
<String
> ContextImpl::getAvailableResamplers()
792 if(mResamplers
.empty() && hasExtension(AL::SOFT_source_resampler
))
794 ALint num_resamplers
= alGetInteger(AL_NUM_RESAMPLERS_SOFT
);
795 mResamplers
.reserve(num_resamplers
);
796 for(int i
= 0;i
< num_resamplers
;i
++)
797 mResamplers
.emplace_back(alGetStringiSOFT(AL_RESAMPLER_NAME_SOFT
, i
));
798 if(mResamplers
.empty())
799 mResamplers
.emplace_back();
804 DECL_THUNK0(ALsizei
, Context
, getDefaultResamplerIndex
, const)
805 ALsizei
ContextImpl::getDefaultResamplerIndex() const
808 if(!hasExtension(AL::SOFT_source_resampler
))
810 return alGetInteger(AL_DEFAULT_RESAMPLER_SOFT
);
814 BufferOrExceptT
ContextImpl::doCreateBuffer(StringView name
, Vector
<UniquePtr
<BufferImpl
>>::iterator iter
, SharedPtr
<Decoder
> decoder
)
816 ALuint srate
= decoder
->getFrequency();
817 ChannelConfig chans
= decoder
->getChannelConfig();
818 SampleType type
= decoder
->getSampleType();
819 ALuint frames
= decoder
->getLength();
821 Vector
<ALbyte
> data(FramesToBytes(frames
, chans
, type
));
822 frames
= decoder
->read(data
.data(), frames
);
824 return std::make_exception_ptr(std::runtime_error("No samples for buffer"));
825 data
.resize(FramesToBytes(frames
, chans
, type
));
827 std::pair
<uint64_t,uint64_t> loop_pts
= decoder
->getLoopPoints();
828 if(loop_pts
.first
>= loop_pts
.second
)
829 loop_pts
= std::make_pair(0, frames
);
832 loop_pts
.second
= std::min
<uint64_t>(loop_pts
.second
, frames
);
833 loop_pts
.first
= std::min
<uint64_t>(loop_pts
.first
, loop_pts
.second
-1);
836 // Get the format before calling the bufferLoading message handler, to
837 // ensure it's something OpenAL can handle.
838 ALenum format
= GetFormat(chans
, type
);
839 if(format
== AL_NONE
)
841 String
str("Unsupported format (");
842 str
+= GetSampleTypeName(type
);
844 str
+= GetChannelConfigName(chans
);
846 return std::make_exception_ptr(std::runtime_error(str
));
850 mMessage
->bufferLoading(name
, chans
, type
, srate
, data
);
854 alGenBuffers(1, &bid
);
855 alBufferData(bid
, format
, data
.data(), data
.size(), srate
);
856 if(hasExtension(AL::SOFT_loop_points
))
858 ALint pts
[2]{(ALint
)loop_pts
.first
, (ALint
)loop_pts
.second
};
859 alBufferiv(bid
, AL_LOOP_POINTS_SOFT
, pts
);
861 if(ALenum err
= alGetError())
863 alDeleteBuffers(1, &bid
);
864 return std::make_exception_ptr(al_error(err
, "Failed to buffer data"));
867 return mBuffers
.insert(iter
,
868 MakeUnique
<BufferImpl
>(this, bid
, srate
, chans
, type
, name
)
872 BufferOrExceptT
ContextImpl::doCreateBufferAsync(StringView name
, Vector
<UniquePtr
<BufferImpl
>>::iterator iter
, SharedPtr
<Decoder
> decoder
, Promise
<Buffer
> promise
)
874 ALuint srate
= decoder
->getFrequency();
875 ChannelConfig chans
= decoder
->getChannelConfig();
876 SampleType type
= decoder
->getSampleType();
877 ALuint frames
= decoder
->getLength();
879 return std::make_exception_ptr(std::runtime_error("No samples for buffer"));
881 ALenum format
= GetFormat(chans
, type
);
882 if(format
== AL_NONE
)
884 String
str("Unsupported format (");
885 str
+= GetSampleTypeName(type
);
887 str
+= GetChannelConfigName(chans
);
889 return std::make_exception_ptr(std::runtime_error(str
));
894 alGenBuffers(1, &bid
);
895 if(ALenum err
= alGetError())
896 return std::make_exception_ptr(al_error(err
, "Failed to create buffer"));
898 auto buffer
= MakeUnique
<BufferImpl
>(this, bid
, srate
, chans
, type
, name
);
900 if(mThread
.get_id() == std::thread::id())
901 mThread
= std::thread(std::mem_fn(&ContextImpl::backgroundProc
), this);
903 PendingPromise
*pf
= nullptr;
904 if(mPendingTail
== mPendingCurrent
.load(std::memory_order_acquire
))
905 pf
= new PendingPromise
{buffer
.get(), std::move(decoder
), format
, frames
,
906 std::move(promise
), {nullptr}};
910 pf
->mBuffer
= buffer
.get();
911 pf
->mDecoder
= std::move(decoder
);
912 pf
->mFormat
= format
;
913 pf
->mFrames
= frames
;
914 pf
->mPromise
= std::move(promise
);
915 mPendingTail
= pf
->mNext
.exchange(nullptr, std::memory_order_relaxed
);
918 mPendingHead
->mNext
.store(pf
, std::memory_order_release
);
921 return mBuffers
.insert(iter
, std::move(buffer
))->get();
924 DECL_THUNK1(Buffer
, Context
, getBuffer
,, StringView
)
925 Buffer
ContextImpl::getBuffer(StringView name
)
929 auto hasher
= std::hash
<StringView
>();
930 if(UNLIKELY(!mFutureBuffers
.empty()))
934 // If the buffer is already pending for the future, wait for it
935 auto iter
= std::lower_bound(mFutureBuffers
.begin(), mFutureBuffers
.end(), hasher(name
),
936 [hasher
](const PendingBuffer
&lhs
, size_t rhs
) -> bool
937 { return hasher(lhs
.mBuffer
->getName()) < rhs
; }
939 if(iter
!= mFutureBuffers
.end() && iter
->mBuffer
->getName() == name
)
941 buffer
= iter
->mFuture
.get();
942 mFutureBuffers
.erase(iter
);
945 // Clear out any completed futures.
946 mFutureBuffers
.erase(
947 std::remove_if(mFutureBuffers
.begin(), mFutureBuffers
.end(),
948 [](const PendingBuffer
&entry
) -> bool
949 { return GetFutureState(entry
.mFuture
) == std::future_status::ready
; }
950 ), mFutureBuffers
.end()
953 // If we got the buffer, return it. Otherwise, go load it normally.
954 if(buffer
) return buffer
;
957 auto iter
= std::lower_bound(mBuffers
.begin(), mBuffers
.end(), hasher(name
),
958 [hasher
](const UniquePtr
<BufferImpl
> &lhs
, size_t rhs
) -> bool
959 { return hasher(lhs
->getName()) < rhs
; }
961 if(iter
!= mBuffers
.end() && (*iter
)->getName() == name
)
962 return Buffer(iter
->get());
964 BufferOrExceptT ret
= doCreateBuffer(name
, iter
, createDecoder(name
));
965 Buffer
*buffer
= std::get_if
<Buffer
>(&ret
);
966 if(UNLIKELY(!buffer
))
967 std::rethrow_exception(std::get
<std::exception_ptr
>(ret
));
971 DECL_THUNK1(SharedFuture
<Buffer
>, Context
, getBufferAsync
,, StringView
)
972 SharedFuture
<Buffer
> ContextImpl::getBufferAsync(StringView name
)
974 SharedFuture
<Buffer
> future
;
977 auto hasher
= std::hash
<StringView
>();
978 if(UNLIKELY(!mFutureBuffers
.empty()))
980 // Check if the future that's being created already exists
981 auto iter
= std::lower_bound(mFutureBuffers
.begin(), mFutureBuffers
.end(), hasher(name
),
982 [hasher
](const PendingBuffer
&lhs
, size_t rhs
) -> bool
983 { return hasher(lhs
.mBuffer
->getName()) < rhs
; }
985 if(iter
!= mFutureBuffers
.end() && iter
->mBuffer
->getName() == name
)
987 future
= iter
->mFuture
;
988 if(GetFutureState(future
) == std::future_status::ready
)
989 mFutureBuffers
.erase(iter
);
993 // Clear out any fulfilled futures.
994 mFutureBuffers
.erase(
995 std::remove_if(mFutureBuffers
.begin(), mFutureBuffers
.end(),
996 [](const PendingBuffer
&entry
) -> bool
997 { return GetFutureState(entry
.mFuture
) == std::future_status::ready
; }
998 ), mFutureBuffers
.end()
1002 auto iter
= std::lower_bound(mBuffers
.begin(), mBuffers
.end(), hasher(name
),
1003 [hasher
](const UniquePtr
<BufferImpl
> &lhs
, size_t rhs
) -> bool
1004 { return hasher(lhs
->getName()) < rhs
; }
1006 if(iter
!= mBuffers
.end() && (*iter
)->getName() == name
)
1008 // User asked to create a future buffer that's already loaded. Just
1009 // construct a promise, fulfill the promise immediately, then return a
1010 // shared future that's already set.
1011 Promise
<Buffer
> promise
;
1012 promise
.set_value(Buffer(iter
->get()));
1013 future
= promise
.get_future().share();
1017 Promise
<Buffer
> promise
;
1018 future
= promise
.get_future().share();
1020 BufferOrExceptT ret
= doCreateBufferAsync(name
, iter
, createDecoder(name
), std::move(promise
));
1021 Buffer
*buffer
= std::get_if
<Buffer
>(&ret
);
1022 if(UNLIKELY(!buffer
))
1023 std::rethrow_exception(std::get
<std::exception_ptr
>(ret
));
1024 mWakeMutex
.lock(); mWakeMutex
.unlock();
1025 mWakeThread
.notify_all();
1027 mFutureBuffers
.insert(
1028 std::lower_bound(mFutureBuffers
.begin(), mFutureBuffers
.end(), hasher(name
),
1029 [hasher
](const PendingBuffer
&lhs
, size_t rhs
) -> bool
1030 { return hasher(lhs
.mBuffer
->getName()) < rhs
; }
1031 ), { buffer
->getHandle(), future
}
1037 DECL_THUNK1(void, Context
, precacheBuffersAsync
,, ArrayView
<StringView
>)
1038 void ContextImpl::precacheBuffersAsync(ArrayView
<StringView
> names
)
1042 if(UNLIKELY(!mFutureBuffers
.empty()))
1044 // Clear out any fulfilled futures.
1045 mFutureBuffers
.erase(
1046 std::remove_if(mFutureBuffers
.begin(), mFutureBuffers
.end(),
1047 [](const PendingBuffer
&entry
) -> bool
1048 { return GetFutureState(entry
.mFuture
) == std::future_status::ready
; }
1049 ), mFutureBuffers
.end()
1053 auto hasher
= std::hash
<StringView
>();
1054 for(const StringView name
: names
)
1056 // Check if the buffer that's being created already exists
1057 auto iter
= std::lower_bound(mBuffers
.begin(), mBuffers
.end(), hasher(name
),
1058 [hasher
](const UniquePtr
<BufferImpl
> &lhs
, size_t rhs
) -> bool
1059 { return hasher(lhs
->getName()) < rhs
; }
1061 if(iter
!= mBuffers
.end() && (*iter
)->getName() == name
)
1064 DecoderOrExceptT dec
= findDecoder(name
);
1065 SharedPtr
<Decoder
> *decoder
= std::get_if
<SharedPtr
<Decoder
>>(&dec
);
1066 if(!decoder
) continue;
1068 Promise
<Buffer
> promise
;
1069 SharedFuture
<Buffer
> future
= promise
.get_future().share();
1071 BufferOrExceptT buf
= doCreateBufferAsync(name
, iter
, std::move(*decoder
),
1072 std::move(promise
));
1073 Buffer
*buffer
= std::get_if
<Buffer
>(&buf
);
1074 if(UNLIKELY(!buffer
)) continue;
1076 mFutureBuffers
.insert(
1077 std::lower_bound(mFutureBuffers
.begin(), mFutureBuffers
.end(), hasher(name
),
1078 [hasher
](const PendingBuffer
&lhs
, size_t rhs
) -> bool
1079 { return hasher(lhs
.mBuffer
->getName()) < rhs
; }
1080 ), { buffer
->getHandle(), future
}
1083 mWakeMutex
.lock(); mWakeMutex
.unlock();
1084 mWakeThread
.notify_all();
1087 DECL_THUNK2(Buffer
, Context
, createBufferFrom
,, StringView
, SharedPtr
<Decoder
>)
1088 Buffer
ContextImpl::createBufferFrom(StringView name
, SharedPtr
<Decoder
>&& decoder
)
1092 auto hasher
= std::hash
<StringView
>();
1093 auto iter
= std::lower_bound(mBuffers
.begin(), mBuffers
.end(), hasher(name
),
1094 [hasher
](const UniquePtr
<BufferImpl
> &lhs
, size_t rhs
) -> bool
1095 { return hasher(lhs
->getName()) < rhs
; }
1097 if(iter
!= mBuffers
.end() && (*iter
)->getName() == name
)
1098 throw std::runtime_error("Buffer already exists");
1100 BufferOrExceptT ret
= doCreateBuffer(name
, iter
, std::move(decoder
));
1101 Buffer
*buffer
= std::get_if
<Buffer
>(&ret
);
1102 if(UNLIKELY(!buffer
))
1103 std::rethrow_exception(std::get
<std::exception_ptr
>(ret
));
1107 DECL_THUNK2(SharedFuture
<Buffer
>, Context
, createBufferAsyncFrom
,, StringView
, SharedPtr
<Decoder
>)
1108 SharedFuture
<Buffer
> ContextImpl::createBufferAsyncFrom(StringView name
, SharedPtr
<Decoder
>&& decoder
)
1110 SharedFuture
<Buffer
> future
;
1113 if(UNLIKELY(!mFutureBuffers
.empty()))
1115 // Clear out any fulfilled futures.
1116 mFutureBuffers
.erase(
1117 std::remove_if(mFutureBuffers
.begin(), mFutureBuffers
.end(),
1118 [](const PendingBuffer
&entry
) -> bool
1119 { return GetFutureState(entry
.mFuture
) == std::future_status::ready
; }
1120 ), mFutureBuffers
.end()
1124 auto hasher
= std::hash
<StringView
>();
1125 auto iter
= std::lower_bound(mBuffers
.begin(), mBuffers
.end(), hasher(name
),
1126 [hasher
](const UniquePtr
<BufferImpl
> &lhs
, size_t rhs
) -> bool
1127 { return hasher(lhs
->getName()) < rhs
; }
1129 if(iter
!= mBuffers
.end() && (*iter
)->getName() == name
)
1130 throw std::runtime_error("Buffer already exists");
1132 Promise
<Buffer
> promise
;
1133 future
= promise
.get_future().share();
1135 BufferOrExceptT ret
= doCreateBufferAsync(name
, iter
, std::move(decoder
), std::move(promise
));
1136 Buffer
*buffer
= std::get_if
<Buffer
>(&ret
);
1137 if(UNLIKELY(!buffer
))
1138 std::rethrow_exception(std::get
<std::exception_ptr
>(ret
));
1139 mWakeMutex
.lock(); mWakeMutex
.unlock();
1140 mWakeThread
.notify_all();
1142 mFutureBuffers
.insert(
1143 std::lower_bound(mFutureBuffers
.begin(), mFutureBuffers
.end(), hasher(name
),
1144 [hasher
](const PendingBuffer
&lhs
, size_t rhs
) -> bool
1145 { return hasher(lhs
.mBuffer
->getName()) < rhs
; }
1146 ), { buffer
->getHandle(), future
}
1153 DECL_THUNK1(Buffer
, Context
, findBuffer
,, StringView
)
1154 Buffer
ContextImpl::findBuffer(StringView name
)
1159 auto hasher
= std::hash
<StringView
>();
1160 if(UNLIKELY(!mFutureBuffers
.empty()))
1162 // If the buffer is already pending for the future, wait for it
1163 auto iter
= std::lower_bound(mFutureBuffers
.begin(), mFutureBuffers
.end(), hasher(name
),
1164 [hasher
](const PendingBuffer
&lhs
, size_t rhs
) -> bool
1165 { return hasher(lhs
.mBuffer
->getName()) < rhs
; }
1167 if(iter
!= mFutureBuffers
.end() && iter
->mBuffer
->getName() == name
)
1169 buffer
= iter
->mFuture
.get();
1170 mFutureBuffers
.erase(iter
);
1173 // Clear out any completed futures.
1174 mFutureBuffers
.erase(
1175 std::remove_if(mFutureBuffers
.begin(), mFutureBuffers
.end(),
1176 [](const PendingBuffer
&entry
) -> bool
1177 { return GetFutureState(entry
.mFuture
) == std::future_status::ready
; }
1178 ), mFutureBuffers
.end()
1184 auto iter
= std::lower_bound(mBuffers
.begin(), mBuffers
.end(), hasher(name
),
1185 [hasher
](const UniquePtr
<BufferImpl
> &lhs
, size_t rhs
) -> bool
1186 { return hasher(lhs
->getName()) < rhs
; }
1188 if(iter
!= mBuffers
.end() && (*iter
)->getName() == name
)
1189 buffer
= Buffer(iter
->get());
1194 DECL_THUNK1(SharedFuture
<Buffer
>, Context
, findBufferAsync
,, StringView
)
1195 SharedFuture
<Buffer
> ContextImpl::findBufferAsync(StringView name
)
1197 SharedFuture
<Buffer
> future
;
1200 auto hasher
= std::hash
<StringView
>();
1201 if(UNLIKELY(!mFutureBuffers
.empty()))
1203 // Check if the future that's being created already exists
1204 auto iter
= std::lower_bound(mFutureBuffers
.begin(), mFutureBuffers
.end(), hasher(name
),
1205 [hasher
](const PendingBuffer
&lhs
, size_t rhs
) -> bool
1206 { return hasher(lhs
.mBuffer
->getName()) < rhs
; }
1208 if(iter
!= mFutureBuffers
.end() && iter
->mBuffer
->getName() == name
)
1210 future
= iter
->mFuture
;
1211 if(GetFutureState(future
) == std::future_status::ready
)
1212 mFutureBuffers
.erase(iter
);
1216 // Clear out any fulfilled futures.
1217 mFutureBuffers
.erase(
1218 std::remove_if(mFutureBuffers
.begin(), mFutureBuffers
.end(),
1219 [](const PendingBuffer
&entry
) -> bool
1220 { return GetFutureState(entry
.mFuture
) == std::future_status::ready
; }
1221 ), mFutureBuffers
.end()
1225 auto iter
= std::lower_bound(mBuffers
.begin(), mBuffers
.end(), hasher(name
),
1226 [hasher
](const UniquePtr
<BufferImpl
> &lhs
, size_t rhs
) -> bool
1227 { return hasher(lhs
->getName()) < rhs
; }
1229 if(iter
!= mBuffers
.end() && (*iter
)->getName() == name
)
1231 // User asked to create a future buffer that's already loaded. Just
1232 // construct a promise, fulfill the promise immediately, then return a
1233 // shared future that's already set.
1234 Promise
<Buffer
> promise
;
1235 promise
.set_value(Buffer(iter
->get()));
1236 future
= promise
.get_future().share();
1242 DECL_THUNK1(void, Context
, removeBuffer
,, Buffer
)
1243 DECL_THUNK1(void, Context
, removeBuffer
,, StringView
)
1244 void ContextImpl::removeBuffer(StringView name
)
1248 auto hasher
= std::hash
<StringView
>();
1249 if(UNLIKELY(!mFutureBuffers
.empty()))
1251 // If the buffer is already pending for the future, wait for it to
1252 // finish before continuing.
1253 auto iter
= std::lower_bound(mFutureBuffers
.begin(), mFutureBuffers
.end(), hasher(name
),
1254 [hasher
](const PendingBuffer
&lhs
, size_t rhs
) -> bool
1255 { return hasher(lhs
.mBuffer
->getName()) < rhs
; }
1257 if(iter
!= mFutureBuffers
.end() && iter
->mBuffer
->getName() == name
)
1259 iter
->mFuture
.wait();
1260 mFutureBuffers
.erase(iter
);
1263 // Clear out any completed futures.
1264 mFutureBuffers
.erase(
1265 std::remove_if(mFutureBuffers
.begin(), mFutureBuffers
.end(),
1266 [](const PendingBuffer
&entry
) -> bool
1267 { return GetFutureState(entry
.mFuture
) == std::future_status::ready
; }
1268 ), mFutureBuffers
.end()
1272 auto iter
= std::lower_bound(mBuffers
.begin(), mBuffers
.end(), hasher(name
),
1273 [hasher
](const UniquePtr
<BufferImpl
> &lhs
, size_t rhs
) -> bool
1274 { return hasher(lhs
->getName()) < rhs
; }
1276 if(iter
!= mBuffers
.end() && (*iter
)->getName() == name
)
1278 // Remove pending sources whose future was waiting for this buffer.
1279 mPendingSources
.erase(
1280 std::remove_if(mPendingSources
.begin(), mPendingSources
.end(),
1281 [iter
](PendingSource
&entry
) -> bool
1283 return (GetFutureState(entry
.mFuture
) == std::future_status::ready
&&
1284 entry
.mFuture
.get().getHandle() == iter
->get());
1286 ), mPendingSources
.end()
1289 mBuffers
.erase(iter
);
1294 ALuint
ContextImpl::getSourceId(ALuint maxprio
)
1297 if(mSourceIds
.empty())
1300 alGenSources(1, &id
);
1301 if(alGetError() == AL_NO_ERROR
)
1304 SourceImpl
*lowest
= nullptr;
1305 for(SourceBufferUpdateEntry
&entry
: mPlaySources
)
1307 if(!lowest
|| entry
.mSource
->getPriority() < lowest
->getPriority())
1308 lowest
= entry
.mSource
;
1310 for(SourceStreamUpdateEntry
&entry
: mStreamSources
)
1312 if(!lowest
|| entry
.mSource
->getPriority() < lowest
->getPriority())
1313 lowest
= entry
.mSource
;
1315 if(lowest
&& lowest
->getPriority() < maxprio
)
1319 mMessage
->sourceForceStopped(lowest
);
1322 if(mSourceIds
.empty())
1323 throw std::runtime_error("No available sources");
1325 id
= mSourceIds
.back();
1326 mSourceIds
.pop_back();
1331 DECL_THUNK0(Source
, Context
, createSource
,)
1332 Source
ContextImpl::createSource()
1337 if(!mFreeSources
.empty())
1339 source
= mFreeSources
.back();
1340 mFreeSources
.pop_back();
1344 mAllSources
.emplace_back(this);
1345 source
= &mAllSources
.back();
1347 return Source(source
);
1351 void ContextImpl::addPendingSource(SourceImpl
*source
, SharedFuture
<Buffer
> future
)
1353 auto iter
= std::lower_bound(mPendingSources
.begin(), mPendingSources
.end(), source
,
1354 [](const PendingSource
&lhs
, SourceImpl
*rhs
) -> bool
1355 { return lhs
.mSource
< rhs
; }
1357 if(iter
== mPendingSources
.end() || iter
->mSource
!= source
)
1358 mPendingSources
.insert(iter
, {source
, std::move(future
)});
1361 void ContextImpl::removePendingSource(SourceImpl
*source
)
1363 auto iter
= std::lower_bound(mPendingSources
.begin(), mPendingSources
.end(), source
,
1364 [](const PendingSource
&lhs
, SourceImpl
*rhs
) -> bool
1365 { return lhs
.mSource
< rhs
; }
1367 if(iter
!= mPendingSources
.end() && iter
->mSource
== source
)
1368 mPendingSources
.erase(iter
);
1371 bool ContextImpl::isPendingSource(const SourceImpl
*source
) const
1373 auto iter
= std::lower_bound(mPendingSources
.begin(), mPendingSources
.end(), source
,
1374 [](const PendingSource
&lhs
, const SourceImpl
*rhs
) -> bool
1375 { return lhs
.mSource
< rhs
; }
1377 return (iter
!= mPendingSources
.end() && iter
->mSource
== source
);
1380 void ContextImpl::addFadingSource(SourceImpl
*source
)
1382 auto iter
= std::lower_bound(mFadingSources
.begin(), mFadingSources
.end(), source
,
1383 [](SourceImpl
*lhs
, SourceImpl
*rhs
) -> bool
1384 { return lhs
< rhs
; }
1386 if(iter
== mFadingSources
.end() || *iter
!= source
)
1387 mFadingSources
.insert(iter
, source
);
1390 void ContextImpl::removeFadingSource(SourceImpl
*source
)
1392 auto iter
= std::lower_bound(mFadingSources
.begin(), mFadingSources
.end(), source
,
1393 [](SourceImpl
*lhs
, SourceImpl
*rhs
) -> bool
1394 { return lhs
< rhs
; }
1396 if(iter
!= mFadingSources
.end() && *iter
== source
)
1397 mFadingSources
.erase(iter
);
1400 void ContextImpl::addPlayingSource(SourceImpl
*source
, ALuint id
)
1402 auto iter
= std::lower_bound(mPlaySources
.begin(), mPlaySources
.end(), source
,
1403 [](const SourceBufferUpdateEntry
&lhs
, SourceImpl
*rhs
) -> bool
1404 { return lhs
.mSource
< rhs
; }
1406 if(iter
== mPlaySources
.end() || iter
->mSource
!= source
)
1407 mPlaySources
.insert(iter
, {source
,id
});
1410 void ContextImpl::addPlayingSource(SourceImpl
*source
)
1412 auto iter
= std::lower_bound(mStreamSources
.begin(), mStreamSources
.end(), source
,
1413 [](const SourceStreamUpdateEntry
&lhs
, SourceImpl
*rhs
) -> bool
1414 { return lhs
.mSource
< rhs
; }
1416 if(iter
== mStreamSources
.end() || iter
->mSource
!= source
)
1417 mStreamSources
.insert(iter
, {source
});
1420 void ContextImpl::removePlayingSource(SourceImpl
*source
)
1422 auto iter0
= std::lower_bound(mPlaySources
.begin(), mPlaySources
.end(), source
,
1423 [](const SourceBufferUpdateEntry
&lhs
, SourceImpl
*rhs
) -> bool
1424 { return lhs
.mSource
< rhs
; }
1426 if(iter0
!= mPlaySources
.end() && iter0
->mSource
== source
)
1427 mPlaySources
.erase(iter0
);
1430 auto iter1
= std::lower_bound(mStreamSources
.begin(), mStreamSources
.end(), source
,
1431 [](const SourceStreamUpdateEntry
&lhs
, SourceImpl
*rhs
) -> bool
1432 { return lhs
.mSource
< rhs
; }
1434 if(iter1
!= mStreamSources
.end() && iter1
->mSource
== source
)
1435 mStreamSources
.erase(iter1
);
1440 void ContextImpl::addStream(SourceImpl
*source
)
1442 std::lock_guard
<std::mutex
> lock(mSourceStreamMutex
);
1443 if(mThread
.get_id() == std::thread::id())
1444 mThread
= std::thread(std::mem_fn(&ContextImpl::backgroundProc
), this);
1445 auto iter
= std::lower_bound(mStreamingSources
.begin(), mStreamingSources
.end(), source
);
1446 if(iter
== mStreamingSources
.end() || *iter
!= source
)
1447 mStreamingSources
.insert(iter
, source
);
1450 void ContextImpl::removeStream(SourceImpl
*source
)
1452 std::lock_guard
<std::mutex
> lock(mSourceStreamMutex
);
1453 auto iter
= std::lower_bound(mStreamingSources
.begin(), mStreamingSources
.end(), source
);
1454 if(iter
!= mStreamingSources
.end() && *iter
== source
)
1455 mStreamingSources
.erase(iter
);
1458 void ContextImpl::removeStreamNoLock(SourceImpl
*source
)
1460 auto iter
= std::lower_bound(mStreamingSources
.begin(), mStreamingSources
.end(), source
);
1461 if(iter
!= mStreamingSources
.end() && *iter
== source
)
1462 mStreamingSources
.erase(iter
);
1466 DECL_THUNK0(AuxiliaryEffectSlot
, Context
, createAuxiliaryEffectSlot
,)
1467 AuxiliaryEffectSlot
ContextImpl::createAuxiliaryEffectSlot()
1469 if(!hasExtension(AL::EXT_EFX
) || !alGenAuxiliaryEffectSlots
)
1470 throw std::runtime_error("AuxiliaryEffectSlots not supported");
1475 alGenAuxiliaryEffectSlots(1, &id
);
1476 throw_al_error("Failed to create AuxiliaryEffectSlot");
1478 auto slot
= MakeUnique
<AuxiliaryEffectSlotImpl
>(this, id
);
1479 auto iter
= std::lower_bound(mEffectSlots
.begin(), mEffectSlots
.end(), slot
);
1480 iter
= mEffectSlots
.insert(iter
, std::move(slot
));
1481 return AuxiliaryEffectSlot(iter
->get());
1484 alDeleteAuxiliaryEffectSlots(1, &id
);
1489 void ContextImpl::freeEffectSlot(AuxiliaryEffectSlotImpl
*slot
)
1491 auto iter
= std::lower_bound(mEffectSlots
.begin(), mEffectSlots
.end(), slot
,
1492 [](const UniquePtr
<AuxiliaryEffectSlotImpl
> &lhs
, AuxiliaryEffectSlotImpl
*rhs
) -> bool
1493 { return lhs
.get() < rhs
; }
1495 if(iter
!= mEffectSlots
.end() && iter
->get() == slot
)
1496 mEffectSlots
.erase(iter
);
1500 DECL_THUNK0(Effect
, Context
, createEffect
,)
1501 Effect
ContextImpl::createEffect()
1503 if(!hasExtension(AL::EXT_EFX
))
1504 throw std::runtime_error("Effects not supported");
1509 alGenEffects(1, &id
);
1510 throw_al_error("Failed to create Effect");
1512 auto effect
= MakeUnique
<EffectImpl
>(this, id
);
1513 auto iter
= std::lower_bound(mEffects
.begin(), mEffects
.end(), effect
);
1514 iter
= mEffects
.insert(iter
, std::move(effect
));
1515 return Effect(iter
->get());
1518 alDeleteEffects(1, &id
);
1523 void ContextImpl::freeEffect(EffectImpl
*effect
)
1525 auto iter
= std::lower_bound(mEffects
.begin(), mEffects
.end(), effect
,
1526 [](const UniquePtr
<EffectImpl
> &lhs
, EffectImpl
*rhs
) -> bool
1527 { return lhs
.get() < rhs
; }
1529 if(iter
!= mEffects
.end() && iter
->get() == effect
)
1530 mEffects
.erase(iter
);
1534 DECL_THUNK0(SourceGroup
, Context
, createSourceGroup
,)
1535 SourceGroup
ContextImpl::createSourceGroup()
1537 auto srcgroup
= MakeUnique
<SourceGroupImpl
>(this);
1538 auto iter
= std::lower_bound(mSourceGroups
.begin(), mSourceGroups
.end(), srcgroup
);
1540 iter
= mSourceGroups
.insert(iter
, std::move(srcgroup
));
1541 return SourceGroup(iter
->get());
1544 void ContextImpl::freeSourceGroup(SourceGroupImpl
*group
)
1546 auto iter
= std::lower_bound(mSourceGroups
.begin(), mSourceGroups
.end(), group
,
1547 [](const UniquePtr
<SourceGroupImpl
> &lhs
, SourceGroupImpl
*rhs
) -> bool
1548 { return lhs
.get() < rhs
; }
1550 if(iter
!= mSourceGroups
.end() && iter
->get() == group
)
1551 mSourceGroups
.erase(iter
);
1555 DECL_THUNK1(void, Context
, setDopplerFactor
,, ALfloat
)
1556 void ContextImpl::setDopplerFactor(ALfloat factor
)
1558 if(!(factor
>= 0.0f
))
1559 throw std::out_of_range("Doppler factor out of range");
1561 alDopplerFactor(factor
);
1565 DECL_THUNK1(void, Context
, setSpeedOfSound
,, ALfloat
)
1566 void ContextImpl::setSpeedOfSound(ALfloat speed
)
1569 throw std::out_of_range("Speed of sound out of range");
1571 alSpeedOfSound(speed
);
1575 DECL_THUNK1(void, Context
, setDistanceModel
,, DistanceModel
)
1576 void ContextImpl::setDistanceModel(DistanceModel model
)
1579 alDistanceModel((ALenum
)model
);
1583 DECL_THUNK0(void, Context
, update
,)
1584 void ContextImpl::update()
1587 mPendingSources
.erase(
1588 std::remove_if(mPendingSources
.begin(), mPendingSources
.end(),
1589 [](PendingSource
&entry
) -> bool
1590 { return !entry
.mSource
->checkPending(entry
.mFuture
); }
1591 ), mPendingSources
.end()
1593 if(!mFadingSources
.empty())
1595 auto cur_time
= std::chrono::steady_clock::now().time_since_epoch();
1596 mFadingSources
.erase(
1597 std::remove_if(mFadingSources
.begin(), mFadingSources
.end(),
1598 [cur_time
](SourceImpl
*source
) -> bool
1599 { return !source
->fadeUpdate(cur_time
); }
1600 ), mFadingSources
.end()
1604 std::remove_if(mPlaySources
.begin(), mPlaySources
.end(),
1605 [](const SourceBufferUpdateEntry
&entry
) -> bool
1606 { return !entry
.mSource
->playUpdate(entry
.mId
); }
1607 ), mPlaySources
.end()
1609 mStreamSources
.erase(
1610 std::remove_if(mStreamSources
.begin(), mStreamSources
.end(),
1611 [](const SourceStreamUpdateEntry
&entry
) -> bool
1612 { return !entry
.mSource
->playUpdate(); }
1613 ), mStreamSources
.end()
1616 if(!mWakeInterval
.load(std::memory_order_relaxed
).count())
1618 // For performance reasons, don't wait for the thread's mutex. This
1619 // should be called often enough to keep up with any and all streams
1621 mWakeThread
.notify_all();
1624 if(hasExtension(AL::EXT_disconnect
) && mIsConnected
)
1627 alcGetIntegerv(mDevice
->getALCdevice(), ALC_CONNECTED
, 1, &connected
);
1628 mIsConnected
= connected
;
1629 if(!connected
&& mMessage
.get()) mMessage
->deviceDisconnected(Device(mDevice
));
1633 DECL_THUNK0(Device
, Context
, getDevice
,)
1634 DECL_THUNK0(std::chrono::milliseconds
, Context
, getAsyncWakeInterval
, const)
1635 DECL_THUNK0(Listener
, Context
, getListener
,)
1636 DECL_THUNK0(SharedPtr
<MessageHandler
>, Context
, getMessageHandler
, const)
1638 void Context::MakeCurrent(Context context
)
1639 { ContextImpl::MakeCurrent(context
.pImpl
); }
1641 Context
Context::GetCurrent()
1642 { return Context(ContextImpl::GetCurrent()); }
1644 void Context::MakeThreadCurrent(Context context
)
1645 { ContextImpl::MakeThreadCurrent(context
.pImpl
); }
1647 Context
Context::GetThreadCurrent()
1648 { return Context(ContextImpl::GetThreadCurrent()); }
1651 DECL_THUNK1(void, Listener
, setGain
,, ALfloat
)
1652 void ListenerImpl::setGain(ALfloat gain
)
1655 throw std::out_of_range("Gain out of range");
1656 CheckContext(mContext
);
1657 alListenerf(AL_GAIN
, gain
);
1661 DECL_THUNK3(void, Listener
, set3DParameters
,, const Vector3
&, const Vector3
&, const Vector3Pair
&)
1662 void ListenerImpl::set3DParameters(const Vector3
&position
, const Vector3
&velocity
, const std::pair
<Vector3
,Vector3
> &orientation
)
1664 static_assert(sizeof(orientation
) == sizeof(ALfloat
[6]), "Invalid Vector3 pair size");
1665 CheckContext(mContext
);
1666 Batcher batcher
= mContext
->getBatcher();
1667 alListenerfv(AL_POSITION
, position
.getPtr());
1668 alListenerfv(AL_VELOCITY
, velocity
.getPtr());
1669 alListenerfv(AL_ORIENTATION
, orientation
.first
.getPtr());
1672 DECL_THUNK1(void, Listener
, setPosition
,, const Vector3
&)
1673 void ListenerImpl::setPosition(const Vector3
&position
)
1675 CheckContext(mContext
);
1676 alListenerfv(AL_POSITION
, position
.getPtr());
1679 DECL_THUNK1(void, Listener
, setPosition
,, const ALfloat
*)
1680 void ListenerImpl::setPosition(const ALfloat
*pos
)
1682 CheckContext(mContext
);
1683 alListenerfv(AL_POSITION
, pos
);
1686 DECL_THUNK1(void, Listener
, setVelocity
,, const Vector3
&)
1687 void ListenerImpl::setVelocity(const Vector3
&velocity
)
1689 CheckContext(mContext
);
1690 alListenerfv(AL_VELOCITY
, velocity
.getPtr());
1693 DECL_THUNK1(void, Listener
, setVelocity
,, const ALfloat
*)
1694 void ListenerImpl::setVelocity(const ALfloat
*vel
)
1696 CheckContext(mContext
);
1697 alListenerfv(AL_VELOCITY
, vel
);
1700 DECL_THUNK1(void, Listener
, setOrientation
,, const Vector3Pair
&)
1701 void ListenerImpl::setOrientation(const std::pair
<Vector3
,Vector3
> &orientation
)
1703 CheckContext(mContext
);
1704 alListenerfv(AL_ORIENTATION
, orientation
.first
.getPtr());
1707 DECL_THUNK2(void, Listener
, setOrientation
,, const ALfloat
*, const ALfloat
*)
1708 void ListenerImpl::setOrientation(const ALfloat
*at
, const ALfloat
*up
)
1710 CheckContext(mContext
);
1711 ALfloat ori
[6] = { at
[0], at
[1], at
[2], up
[0], up
[1], up
[2] };
1712 alListenerfv(AL_ORIENTATION
, ori
);
1715 DECL_THUNK1(void, Listener
, setOrientation
,, const ALfloat
*)
1716 void ListenerImpl::setOrientation(const ALfloat
*ori
)
1718 CheckContext(mContext
);
1719 alListenerfv(AL_ORIENTATION
, ori
);
1722 DECL_THUNK1(void, Listener
, setMetersPerUnit
,, ALfloat
)
1723 void ListenerImpl::setMetersPerUnit(ALfloat m_u
)
1726 throw std::out_of_range("Invalid meters per unit");
1727 CheckContext(mContext
);
1728 if(mContext
->hasExtension(AL::EXT_EFX
))
1729 alListenerf(AL_METERS_PER_UNIT
, m_u
);