Properly handle buffer name hash collisions
[alure.git] / src / context.cpp
blob6d12b5a4de804bf7bf41796f230a0ac936e25e4d
2 #include "config.h"
4 #include "context.h"
6 #include <stdexcept>
7 #include <algorithm>
8 #include <functional>
9 #include <memory>
10 #include <iostream>
11 #include <fstream>
12 #include <cstring>
13 #include <map>
14 #include <new>
16 #include "alc.h"
18 #ifdef HAVE_WAVE
19 #include "decoders/wave.hpp"
20 #endif
21 #ifdef HAVE_VORBISFILE
22 #include "decoders/vorbisfile.hpp"
23 #endif
24 #ifdef HAVE_LIBFLAC
25 #include "decoders/flac.hpp"
26 #endif
27 #ifdef HAVE_OPUSFILE
28 #include "decoders/opusfile.hpp"
29 #endif
30 #ifdef HAVE_LIBSNDFILE
31 #include "decoders/sndfile.hpp"
32 #endif
33 #ifdef HAVE_MPG123
34 #include "decoders/mpg123.hpp"
35 #endif
37 #include "devicemanager.h"
38 #include "device.h"
39 #include "buffer.h"
40 #include "source.h"
41 #include "auxeffectslot.h"
42 #include "effect.h"
43 #include "sourcegroup.h"
45 #ifdef _WIN32
46 #define WIN32_LEAN_AND_MEAN
47 #include <windows.h>
48 #endif
50 namespace std {
52 // Implements a FNV-1a hash for StringView. NOTE: This is *NOT* guaranteed
53 // compatible with std::hash<String>! The standard does not give any specific
54 // hash implementation, nor a way for applications to access the same hash
55 // function as std::string (short of copying into a string and hashing that).
56 // So if you need Strings and StringViews to result in the same hash for the
57 // same set of characters, hash StringViews created from the Strings.
58 template<>
59 struct hash<alure::StringView> {
60 size_t operator()(const alure::StringView &str) const noexcept
62 using traits_type = alure::StringView::traits_type;
64 if /*constexpr*/ (sizeof(size_t) == 8)
66 static constexpr size_t hash_offset = 0xcbf29ce484222325;
67 static constexpr size_t hash_prime = 0x100000001b3;
69 size_t val = hash_offset;
70 for(auto ch : str)
71 val = (val^traits_type::to_int_type(ch)) * hash_prime;
72 return val;
74 else
76 static constexpr size_t hash_offset = 0x811c9dc5;
77 static constexpr size_t hash_prime = 0x1000193;
79 size_t val = hash_offset;
80 for(auto ch : str)
81 val = (val^traits_type::to_int_type(ch)) * hash_prime;
82 return val;
89 namespace {
91 // Global mutex to protect global context changes
92 std::mutex gGlobalCtxMutex;
94 #ifdef _WIN32
95 // Windows' std::ifstream fails with non-ANSI paths since the standard only
96 // specifies names using const char* (or std::string). MSVC has a non-standard
97 // extension using const wchar_t* (or std::wstring?) to handle Unicode paths,
98 // but not all Windows compilers support it. So we have to make our own istream
99 // that accepts UTF-8 paths and forwards to Unicode-aware I/O functions.
100 class StreamBuf final : public std::streambuf {
101 alure::Array<char_type,4096> mBuffer;
102 HANDLE mFile{INVALID_HANDLE_VALUE};
104 int_type underflow() override
106 if(mFile != INVALID_HANDLE_VALUE && gptr() == egptr())
108 // Read in the next chunk of data, and set the pointers on success
109 DWORD got = 0;
110 if(ReadFile(mFile, mBuffer.data(), (DWORD)mBuffer.size(), &got, NULL))
111 setg(mBuffer.data(), mBuffer.data(), mBuffer.data()+got);
113 if(gptr() == egptr())
114 return traits_type::eof();
115 return traits_type::to_int_type(*gptr());
118 pos_type seekoff(off_type offset, std::ios_base::seekdir whence, std::ios_base::openmode mode) override
120 if(mFile == INVALID_HANDLE_VALUE || (mode&std::ios_base::out) || !(mode&std::ios_base::in))
121 return traits_type::eof();
123 LARGE_INTEGER fpos;
124 switch(whence)
126 case std::ios_base::beg:
127 fpos.QuadPart = offset;
128 if(!SetFilePointerEx(mFile, fpos, &fpos, FILE_BEGIN))
129 return traits_type::eof();
130 break;
132 case std::ios_base::cur:
133 // If the offset remains in the current buffer range, just
134 // update the pointer.
135 if((offset >= 0 && offset < off_type(egptr()-gptr())) ||
136 (offset < 0 && -offset <= off_type(gptr()-eback())))
138 // Get the current file offset to report the correct read
139 // offset.
140 fpos.QuadPart = 0;
141 if(!SetFilePointerEx(mFile, fpos, &fpos, FILE_CURRENT))
142 return traits_type::eof();
143 setg(eback(), gptr()+offset, egptr());
144 return fpos.QuadPart - off_type(egptr()-gptr());
146 // Need to offset for the file offset being at egptr() while
147 // the requested offset is relative to gptr().
148 offset -= off_type(egptr()-gptr());
149 fpos.QuadPart = offset;
150 if(!SetFilePointerEx(mFile, fpos, &fpos, FILE_CURRENT))
151 return traits_type::eof();
152 break;
154 case std::ios_base::end:
155 fpos.QuadPart = offset;
156 if(!SetFilePointerEx(mFile, fpos, &fpos, FILE_END))
157 return traits_type::eof();
158 break;
160 default:
161 return traits_type::eof();
163 setg(nullptr, nullptr, nullptr);
164 return fpos.QuadPart;
167 pos_type seekpos(pos_type pos, std::ios_base::openmode mode) override
169 // Simplified version of seekoff
170 if(mFile == INVALID_HANDLE_VALUE || (mode&std::ios_base::out) || !(mode&std::ios_base::in))
171 return traits_type::eof();
173 LARGE_INTEGER fpos;
174 fpos.QuadPart = pos;
175 if(!SetFilePointerEx(mFile, fpos, &fpos, FILE_BEGIN))
176 return traits_type::eof();
178 setg(nullptr, nullptr, nullptr);
179 return fpos.QuadPart;
182 public:
183 bool open(const char *filename)
185 alure::Vector<wchar_t> wname;
186 int wnamelen;
188 wnamelen = MultiByteToWideChar(CP_UTF8, 0, filename, -1, NULL, 0);
189 if(wnamelen <= 0) return false;
191 wname.resize(wnamelen);
192 MultiByteToWideChar(CP_UTF8, 0, filename, -1, wname.data(), wnamelen);
194 mFile = CreateFileW(wname.data(), GENERIC_READ, FILE_SHARE_READ, NULL,
195 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
196 if(mFile == INVALID_HANDLE_VALUE) return false;
197 return true;
200 bool is_open() const noexcept { return mFile != INVALID_HANDLE_VALUE; }
202 StreamBuf() = default;
203 ~StreamBuf() override
205 if(mFile != INVALID_HANDLE_VALUE)
206 CloseHandle(mFile);
207 mFile = INVALID_HANDLE_VALUE;
211 // Inherit from std::istream to use our custom streambuf
212 class Stream final : public std::istream {
213 StreamBuf mStreamBuf;
215 public:
216 Stream(const char *filename) : std::istream(nullptr)
218 init(&mStreamBuf);
220 // Set the failbit if the file failed to open.
221 if(!mStreamBuf.open(filename)) clear(failbit);
224 bool is_open() const noexcept { return mStreamBuf.is_open(); }
226 #endif
228 using DecoderEntryPair = std::pair<alure::String,alure::UniquePtr<alure::DecoderFactory>>;
229 const DecoderEntryPair sDefaultDecoders[] = {
230 #ifdef HAVE_WAVE
231 { "_alure_int_wave", alure::MakeUnique<alure::WaveDecoderFactory>() },
232 #endif
233 #ifdef HAVE_VORBISFILE
234 { "_alure_int_vorbis", alure::MakeUnique<alure::VorbisFileDecoderFactory>() },
235 #endif
236 #ifdef HAVE_LIBFLAC
237 { "_alure_int_flac", alure::MakeUnique<alure::FlacDecoderFactory>() },
238 #endif
239 #ifdef HAVE_OPUSFILE
240 { "_alure_int_opus", alure::MakeUnique<alure::OpusFileDecoderFactory>() },
241 #endif
242 #ifdef HAVE_LIBSNDFILE
243 { "_alure_int_sndfile", alure::MakeUnique<alure::SndFileDecoderFactory>() },
244 #endif
245 #ifdef HAVE_MPG123
246 { "_alure_int_mpg123", alure::MakeUnique<alure::Mpg123DecoderFactory>() },
247 #endif
249 alure::Vector<DecoderEntryPair> sDecoders;
252 alure::DecoderOrExceptT GetDecoder(alure::UniquePtr<std::istream> &file,
253 alure::ArrayView<DecoderEntryPair> decoders)
255 while(!decoders.empty())
257 alure::DecoderFactory *factory = decoders.front().second.get();
258 auto decoder = factory->createDecoder(file);
259 if(decoder) return std::move(decoder);
261 if(!file || !(file->clear(),file->seekg(0)))
262 return std::make_exception_ptr(
263 std::runtime_error("Failed to rewind file for the next decoder factory")
266 decoders = decoders.slice(1);
269 return alure::SharedPtr<alure::Decoder>(nullptr);
272 static alure::DecoderOrExceptT GetDecoder(alure::UniquePtr<std::istream> file)
274 auto decoder = GetDecoder(file, sDecoders);
275 if(std::holds_alternative<std::exception_ptr>(decoder)) return decoder;
276 if(std::get<alure::SharedPtr<alure::Decoder>>(decoder)) return decoder;
277 decoder = GetDecoder(file, sDefaultDecoders);
278 if(std::holds_alternative<std::exception_ptr>(decoder)) return decoder;
279 if(std::get<alure::SharedPtr<alure::Decoder>>(decoder)) return decoder;
280 return (decoder = std::make_exception_ptr(std::runtime_error("No decoder found")));
283 class DefaultFileIOFactory final : public alure::FileIOFactory {
284 alure::UniquePtr<std::istream> openFile(const alure::String &name) noexcept override
286 #ifdef _WIN32
287 auto file = alure::MakeUnique<Stream>(name.c_str());
288 #else
289 auto file = alure::MakeUnique<std::ifstream>(name.c_str(), std::ios::binary);
290 #endif
291 if(!file->is_open()) file = nullptr;
292 return std::move(file);
295 DefaultFileIOFactory sDefaultFileFactory;
297 alure::UniquePtr<alure::FileIOFactory> sFileFactory;
301 namespace alure {
303 static inline void CheckContext(const ContextImpl *ctx)
305 auto count = ContextImpl::sContextSetCount.load(std::memory_order_acquire);
306 if(UNLIKELY(count != ctx->mContextSetCounter))
308 if(UNLIKELY(ctx != ContextImpl::GetCurrent()))
309 throw std::runtime_error("Called context is not current");
310 ctx->mContextSetCounter = count;
314 std::variant<std::monostate,uint64_t> ParseTimeval(StringView strval, double srate) noexcept
316 try {
317 size_t endpos;
318 size_t cpos = strval.find_first_of(':');
319 if(cpos == StringView::npos)
321 // No colon is present, treat it as a plain sample offset
322 uint64_t val = std::stoull(String(strval), &endpos);
323 if(endpos != strval.length()) return {};
324 return val;
327 // Value is not a sample offset. Its format is [[HH:]MM]:SS[.sss] (at
328 // least one colon must exist to be interpreted this way).
329 uint64_t val = 0;
331 if(cpos != 0)
333 // If a non-empty first value, parse it (may be hours or minutes)
334 val = std::stoul(String(strval.data(), cpos), &endpos);
335 if(endpos != cpos) return {};
338 strval = strval.substr(cpos+1);
339 cpos = strval.find_first_of(':');
340 if(cpos != StringView::npos)
342 // If a second colon is present, the first value was hours and this is
343 // minutes, otherwise the first value was minutes.
344 uint64_t val2 = 0;
346 if(cpos != 0)
348 val2 = std::stoul(String(strval.data(), cpos), &endpos);
349 if(endpos != cpos || val2 >= 60) return {};
352 // Combines hours and minutes into the full minute count
353 if(val > std::numeric_limits<uint64_t>::max()/60)
354 return {};
355 val = val*60 + val2;
356 strval = strval.substr(cpos+1);
359 double secs = 0.0;
360 if(!strval.empty())
362 // Parse the seconds and its fraction. Only include the first 3 decimal
363 // places for millisecond precision.
364 size_t dpos = strval.find_first_of('.');
365 String str = (dpos == StringView::npos) ?
366 String(strval) : String(strval.substr(0, dpos+4));
367 secs = std::stod(str, &endpos);
368 if(endpos != str.length() || !(secs >= 0.0 && secs < 60.0))
369 return {};
372 // Convert minutes to seconds, add the seconds, then convert to samples.
373 return static_cast<uint64_t>((val*60.0 + secs) * srate);
375 catch(...) {
378 return {};
382 Decoder::~Decoder() { }
383 DecoderFactory::~DecoderFactory() { }
385 void RegisterDecoder(StringView name, UniquePtr<DecoderFactory> factory)
387 auto iter = std::lower_bound(sDecoders.begin(), sDecoders.end(), name,
388 [](const DecoderEntryPair &entry, StringView rhs) -> bool
389 { return entry.first < rhs; }
391 if(iter != sDecoders.end())
392 throw std::runtime_error("Decoder factory already registered");
393 sDecoders.insert(iter, std::make_pair(String(name), std::move(factory)));
396 UniquePtr<DecoderFactory> UnregisterDecoder(StringView name) noexcept
398 UniquePtr<DecoderFactory> factory;
399 auto iter = std::lower_bound(sDecoders.begin(), sDecoders.end(), name,
400 [](const DecoderEntryPair &entry, StringView rhs) noexcept -> bool
401 { return entry.first < rhs; }
403 if(iter != sDecoders.end())
405 factory = std::move(iter->second);
406 sDecoders.erase(iter);
407 return factory;
409 return factory;
413 FileIOFactory::~FileIOFactory() { }
415 UniquePtr<FileIOFactory> FileIOFactory::set(UniquePtr<FileIOFactory> factory) noexcept
417 sFileFactory.swap(factory);
418 return factory;
421 FileIOFactory &FileIOFactory::get() noexcept
423 FileIOFactory *factory = sFileFactory.get();
424 if(factory) return *factory;
425 return sDefaultFileFactory;
429 // Default message handler methods are no-ops.
430 MessageHandler::~MessageHandler()
434 void MessageHandler::deviceDisconnected(Device) noexcept
438 void MessageHandler::sourceStopped(Source) noexcept
442 void MessageHandler::sourceForceStopped(Source) noexcept
446 void MessageHandler::bufferLoading(StringView, ChannelConfig, SampleType, ALuint, ArrayView<ALbyte>) noexcept
450 String MessageHandler::resourceNotFound(StringView) noexcept
452 return String();
456 template<typename T>
457 static inline void LoadALFunc(T **func, const char *name)
458 { *func = reinterpret_cast<T*>(alGetProcAddress(name)); }
460 static void LoadNothing(ContextImpl*) { }
462 static void LoadEFX(ContextImpl *ctx)
464 LoadALFunc(&ctx->alGenEffects, "alGenEffects");
465 LoadALFunc(&ctx->alDeleteEffects, "alDeleteEffects");
466 LoadALFunc(&ctx->alIsEffect, "alIsEffect");
467 LoadALFunc(&ctx->alEffecti, "alEffecti");
468 LoadALFunc(&ctx->alEffectiv, "alEffectiv");
469 LoadALFunc(&ctx->alEffectf, "alEffectf");
470 LoadALFunc(&ctx->alEffectfv, "alEffectfv");
471 LoadALFunc(&ctx->alGetEffecti, "alGetEffecti");
472 LoadALFunc(&ctx->alGetEffectiv, "alGetEffectiv");
473 LoadALFunc(&ctx->alGetEffectf, "alGetEffectf");
474 LoadALFunc(&ctx->alGetEffectfv, "alGetEffectfv");
476 LoadALFunc(&ctx->alGenFilters, "alGenFilters");
477 LoadALFunc(&ctx->alDeleteFilters, "alDeleteFilters");
478 LoadALFunc(&ctx->alIsFilter, "alIsFilter");
479 LoadALFunc(&ctx->alFilteri, "alFilteri");
480 LoadALFunc(&ctx->alFilteriv, "alFilteriv");
481 LoadALFunc(&ctx->alFilterf, "alFilterf");
482 LoadALFunc(&ctx->alFilterfv, "alFilterfv");
483 LoadALFunc(&ctx->alGetFilteri, "alGetFilteri");
484 LoadALFunc(&ctx->alGetFilteriv, "alGetFilteriv");
485 LoadALFunc(&ctx->alGetFilterf, "alGetFilterf");
486 LoadALFunc(&ctx->alGetFilterfv, "alGetFilterfv");
488 LoadALFunc(&ctx->alGenAuxiliaryEffectSlots, "alGenAuxiliaryEffectSlots");
489 LoadALFunc(&ctx->alDeleteAuxiliaryEffectSlots, "alDeleteAuxiliaryEffectSlots");
490 LoadALFunc(&ctx->alIsAuxiliaryEffectSlot, "alIsAuxiliaryEffectSlot");
491 LoadALFunc(&ctx->alAuxiliaryEffectSloti, "alAuxiliaryEffectSloti");
492 LoadALFunc(&ctx->alAuxiliaryEffectSlotiv, "alAuxiliaryEffectSlotiv");
493 LoadALFunc(&ctx->alAuxiliaryEffectSlotf, "alAuxiliaryEffectSlotf");
494 LoadALFunc(&ctx->alAuxiliaryEffectSlotfv, "alAuxiliaryEffectSlotfv");
495 LoadALFunc(&ctx->alGetAuxiliaryEffectSloti, "alGetAuxiliaryEffectSloti");
496 LoadALFunc(&ctx->alGetAuxiliaryEffectSlotiv, "alGetAuxiliaryEffectSlotiv");
497 LoadALFunc(&ctx->alGetAuxiliaryEffectSlotf, "alGetAuxiliaryEffectSlotf");
498 LoadALFunc(&ctx->alGetAuxiliaryEffectSlotfv, "alGetAuxiliaryEffectSlotfv");
501 static void LoadSourceResampler(ContextImpl *ctx)
503 LoadALFunc(&ctx->alGetStringiSOFT, "alGetStringiSOFT");
506 static void LoadSourceLatency(ContextImpl *ctx)
508 LoadALFunc(&ctx->alGetSourcei64vSOFT, "alGetSourcei64vSOFT");
509 LoadALFunc(&ctx->alGetSourcedvSOFT, "alGetSourcedvSOFT");
512 static const struct {
513 AL extension;
514 const char name[32];
515 void (&loader)(ContextImpl*);
516 } ALExtensionList[] = {
517 { AL::EXT_EFX, "ALC_EXT_EFX", LoadEFX },
519 { AL::EXT_FLOAT32, "AL_EXT_FLOAT32", LoadNothing },
520 { AL::EXT_MCFORMATS, "AL_EXT_MCFORMATS", LoadNothing },
521 { AL::EXT_BFORMAT, "AL_EXT_BFORMAT", LoadNothing },
523 { AL::EXT_MULAW, "AL_EXT_MULAW", LoadNothing },
524 { AL::EXT_MULAW_MCFORMATS, "AL_EXT_MULAW_MCFORMATS", LoadNothing },
525 { AL::EXT_MULAW_BFORMAT, "AL_EXT_MULAW_BFORMAT", LoadNothing },
527 { AL::SOFT_loop_points, "AL_SOFT_loop_points", LoadNothing },
528 { AL::SOFT_source_latency, "AL_SOFT_source_latency", LoadSourceLatency },
529 { AL::SOFT_source_resampler, "AL_SOFT_source_resampler", LoadSourceResampler },
530 { AL::SOFT_source_spatialize, "AL_SOFT_source_spatialize", LoadNothing },
532 { AL::EXT_disconnect, "ALC_EXT_disconnect", LoadNothing },
534 { AL::EXT_SOURCE_RADIUS, "AL_EXT_SOURCE_RADIUS", LoadNothing },
535 { AL::EXT_STEREO_ANGLES, "AL_EXT_STEREO_ANGLES", LoadNothing },
539 ContextImpl *ContextImpl::sCurrentCtx = nullptr;
540 thread_local ContextImpl *ContextImpl::sThreadCurrentCtx = nullptr;
542 std::atomic<uint64_t> ContextImpl::sContextSetCount{0};
544 void ContextImpl::MakeCurrent(ContextImpl *context)
546 std::unique_lock<std::mutex> ctxlock(gGlobalCtxMutex);
548 if(alcMakeContextCurrent(context ? context->getALCcontext() : nullptr) == ALC_FALSE)
549 throw std::runtime_error("Call to alcMakeContextCurrent failed");
550 if(context)
552 context->addRef();
553 std::call_once(context->mSetExts, std::mem_fn(&ContextImpl::setupExts), context);
555 std::swap(sCurrentCtx, context);
556 if(context) context->decRef();
558 if(sThreadCurrentCtx)
559 sThreadCurrentCtx->decRef();
560 sThreadCurrentCtx = nullptr;
561 sContextSetCount.fetch_add(1, std::memory_order_release);
563 if((context = sCurrentCtx) != nullptr)
565 ctxlock.unlock();
566 context->mWakeThread.notify_all();
570 void ContextImpl::MakeThreadCurrent(ContextImpl *context)
572 if(!DeviceManagerImpl::SetThreadContext)
573 throw std::runtime_error("Thread-local contexts unsupported");
574 if(DeviceManagerImpl::SetThreadContext(context ? context->getALCcontext() : nullptr) == ALC_FALSE)
575 throw std::runtime_error("Call to alcSetThreadContext failed");
576 if(context)
578 context->addRef();
579 std::call_once(context->mSetExts, std::mem_fn(&ContextImpl::setupExts), context);
581 if(sThreadCurrentCtx)
582 sThreadCurrentCtx->decRef();
583 sThreadCurrentCtx = context;
584 sContextSetCount.fetch_add(1, std::memory_order_release);
587 void ContextImpl::setupExts()
589 ALCdevice *device = mDevice.getALCdevice();
590 for(const auto &entry : ALExtensionList)
592 if((strncmp(entry.name, "ALC", 3) == 0) ? alcIsExtensionPresent(device, entry.name) :
593 alIsExtensionPresent(entry.name))
595 mHasExt.set(static_cast<size_t>(entry.extension));
596 entry.loader(this);
602 void ContextImpl::backgroundProc()
604 if(DeviceManagerImpl::SetThreadContext && mDevice.hasExtension(ALC::EXT_thread_local_context))
605 DeviceManagerImpl::SetThreadContext(getALCcontext());
607 std::chrono::steady_clock::time_point basetime = std::chrono::steady_clock::now();
608 std::chrono::milliseconds waketime(0);
609 std::unique_lock<std::mutex> ctxlock(gGlobalCtxMutex);
610 while(!mQuitThread.load(std::memory_order_acquire))
613 std::lock_guard<std::mutex> srclock(mSourceStreamMutex);
614 mStreamingSources.erase(
615 std::remove_if(mStreamingSources.begin(), mStreamingSources.end(),
616 [](SourceImpl *source) -> bool
617 { return !source->updateAsync(); }
618 ), mStreamingSources.end()
622 // Only do one pending buffer at a time. In case there's several large
623 // buffers to load, we still need to process streaming sources so they
624 // don't underrun.
625 PendingPromise *lastpb = mPendingCurrent.load(std::memory_order_acquire);
626 if(PendingPromise *pb = lastpb->mNext.load(std::memory_order_relaxed))
628 pb->mBuffer->load(pb->mFrames, pb->mFormat, std::move(pb->mDecoder), this);
629 pb->mPromise.set_value(Buffer(pb->mBuffer));
630 Promise<Buffer>().swap(pb->mPromise);
631 mPendingCurrent.store(pb, std::memory_order_release);
632 continue;
635 std::unique_lock<std::mutex> wakelock(mWakeMutex);
636 if(!mQuitThread.load(std::memory_order_acquire) && lastpb->mNext.load(std::memory_order_acquire) == nullptr)
638 ctxlock.unlock();
640 std::chrono::milliseconds interval = mWakeInterval.load(std::memory_order_relaxed);
641 if(interval.count() == 0)
642 mWakeThread.wait(wakelock);
643 else
645 auto now = std::chrono::steady_clock::now() - basetime;
646 if(now > waketime)
648 auto mult = (now-waketime + interval-std::chrono::milliseconds(1)) / interval;
649 waketime += interval * mult;
651 mWakeThread.wait_until(wakelock, waketime + basetime);
653 wakelock.unlock();
655 ctxlock.lock();
656 while(!mQuitThread.load(std::memory_order_acquire) &&
657 alcGetCurrentContext() != getALCcontext())
658 mWakeThread.wait(ctxlock);
661 ctxlock.unlock();
663 if(DeviceManagerImpl::SetThreadContext)
664 DeviceManagerImpl::SetThreadContext(nullptr);
668 ContextImpl::ContextImpl(DeviceImpl &device, ArrayView<AttributePair> attrs)
669 : mListener(this), mDevice(device), mIsConnected(true), mIsBatching(false)
671 ALCdevice *alcdev = mDevice.getALCdevice();
672 if(attrs.empty()) /* No explicit attributes. */
673 mContext = alcCreateContext(alcdev, nullptr);
674 else
675 mContext = alcCreateContext(alcdev, &std::get<0>(attrs.front()));
676 if(!mContext) throw alc_error(alcGetError(alcdev), "alcCreateContext failed");
678 mSourceIds.reserve(256);
679 mPendingHead = new PendingPromise{nullptr, {}, AL_NONE, 0, {}, {nullptr}};
680 mPendingCurrent.store(mPendingHead, std::memory_order_relaxed);
681 mPendingTail = mPendingHead;
684 ContextImpl::~ContextImpl()
686 if(mThread.joinable())
688 std::unique_lock<std::mutex> lock(mWakeMutex);
689 mQuitThread.store(true, std::memory_order_relaxed);
690 lock.unlock();
691 mWakeThread.notify_all();
692 mThread.join();
695 PendingPromise *pb = mPendingTail;
696 while(pb)
698 PendingPromise *next = pb->mNext.load(std::memory_order_relaxed);
699 delete pb;
700 pb = next;
702 mPendingCurrent.store(nullptr, std::memory_order_relaxed);
703 mPendingHead = nullptr;
704 mPendingTail = nullptr;
706 mEffectSlots.clear();
707 mEffects.clear();
709 if(mContext)
710 alcDestroyContext(mContext);
711 mContext = nullptr;
713 std::lock_guard<std::mutex> ctxlock(gGlobalCtxMutex);
714 if(sCurrentCtx == this)
716 sCurrentCtx = nullptr;
717 sContextSetCount.fetch_add(1, std::memory_order_release);
719 if(sThreadCurrentCtx == this)
721 sThreadCurrentCtx = nullptr;
722 sContextSetCount.fetch_add(1, std::memory_order_release);
727 void Context::destroy()
729 ContextImpl *i = pImpl;
730 pImpl = nullptr;
731 i->destroy();
733 void ContextImpl::destroy()
735 if(mRefs != 0)
736 throw std::runtime_error("Context is in use");
737 if(!mBuffers.empty())
738 throw std::runtime_error("Trying to destroy a context with buffers");
740 if(mThread.joinable())
742 std::unique_lock<std::mutex> lock(mWakeMutex);
743 mQuitThread.store(true, std::memory_order_release);
744 lock.unlock();
745 mWakeThread.notify_all();
746 mThread.join();
749 alcDestroyContext(mContext);
750 mContext = nullptr;
752 mDevice.removeContext(this);
756 DECL_THUNK0(void, Context, startBatch,)
757 void ContextImpl::startBatch()
759 alcSuspendContext(mContext);
760 mIsBatching = true;
763 DECL_THUNK0(void, Context, endBatch,)
764 void ContextImpl::endBatch()
766 alcProcessContext(mContext);
767 mIsBatching = false;
771 DECL_THUNK1(SharedPtr<MessageHandler>, Context, setMessageHandler,, SharedPtr<MessageHandler>)
772 SharedPtr<MessageHandler> ContextImpl::setMessageHandler(SharedPtr<MessageHandler>&& handler)
774 std::lock_guard<std::mutex> lock(gGlobalCtxMutex);
775 mMessage.swap(handler);
776 return handler;
780 DECL_THUNK1(void, Context, setAsyncWakeInterval,, std::chrono::milliseconds)
781 void ContextImpl::setAsyncWakeInterval(std::chrono::milliseconds interval)
783 if(interval.count() < 0 || interval > std::chrono::seconds(1))
784 throw std::out_of_range("Async wake interval out of range");
785 mWakeInterval.store(interval);
786 mWakeMutex.lock(); mWakeMutex.unlock();
787 mWakeThread.notify_all();
791 DecoderOrExceptT ContextImpl::findDecoder(StringView name)
793 String oldname = String(name);
794 auto file = FileIOFactory::get().openFile(oldname);
795 if(UNLIKELY(!file))
797 // Resource not found. Try to find a substitute.
798 if(!mMessage.get())
799 return std::make_exception_ptr(std::runtime_error("Failed to open file"));
800 do {
801 String newname(mMessage->resourceNotFound(oldname));
802 if(newname.empty())
803 return std::make_exception_ptr(std::runtime_error("Failed to open file"));
804 file = FileIOFactory::get().openFile(newname);
805 oldname = std::move(newname);
806 } while(!file);
808 return GetDecoder(std::move(file));
811 DECL_THUNK1(SharedPtr<Decoder>, Context, createDecoder,, StringView)
812 SharedPtr<Decoder> ContextImpl::createDecoder(StringView name)
814 CheckContext(this);
815 DecoderOrExceptT dec = findDecoder(name);
816 if(SharedPtr<Decoder> *decoder = std::get_if<SharedPtr<Decoder>>(&dec))
817 return std::move(*decoder);
818 std::rethrow_exception(std::get<std::exception_ptr>(dec));
822 DECL_THUNK2(bool, Context, isSupported, const, ChannelConfig, SampleType)
823 bool ContextImpl::isSupported(ChannelConfig channels, SampleType type) const
825 CheckContext(this);
826 return GetFormat(channels, type) != AL_NONE;
830 DECL_THUNK0(ArrayView<String>, Context, getAvailableResamplers,)
831 ArrayView<String> ContextImpl::getAvailableResamplers()
833 CheckContext(this);
834 if(mResamplers.empty() && hasExtension(AL::SOFT_source_resampler))
836 ALint num_resamplers = alGetInteger(AL_NUM_RESAMPLERS_SOFT);
837 mResamplers.reserve(num_resamplers);
838 for(int i = 0;i < num_resamplers;i++)
839 mResamplers.emplace_back(alGetStringiSOFT(AL_RESAMPLER_NAME_SOFT, i));
840 if(mResamplers.empty())
841 mResamplers.emplace_back();
843 return mResamplers;
846 DECL_THUNK0(ALsizei, Context, getDefaultResamplerIndex, const)
847 ALsizei ContextImpl::getDefaultResamplerIndex() const
849 CheckContext(this);
850 if(!hasExtension(AL::SOFT_source_resampler))
851 return 0;
852 return alGetInteger(AL_DEFAULT_RESAMPLER_SOFT);
856 ContextImpl::FutureBufferListT::const_iterator ContextImpl::findFutureBufferName(StringView name, size_t name_hash) const
858 auto iter = std::lower_bound(mFutureBuffers.begin(), mFutureBuffers.end(), name_hash,
859 [](const PendingBuffer &lhs, size_t rhs) -> bool
860 { return lhs.mBuffer->getNameHash() < rhs; }
862 while(iter != mFutureBuffers.end() && iter->mBuffer->getNameHash() == name_hash &&
863 iter->mBuffer->getName() != name)
864 ++iter;
865 return iter;
868 ContextImpl::BufferListT::const_iterator ContextImpl::findBufferName(StringView name, size_t name_hash) const
870 auto iter = std::lower_bound(mBuffers.begin(), mBuffers.end(), name_hash,
871 [](const UniquePtr<BufferImpl> &lhs, size_t rhs) -> bool
872 { return lhs->getNameHash() < rhs; }
874 while(iter != mBuffers.end() && (*iter)->getNameHash() == name_hash &&
875 (*iter)->getName() != name)
876 ++iter;
877 return iter;
880 BufferOrExceptT ContextImpl::doCreateBuffer(StringView name, size_t name_hash, BufferListT::const_iterator iter, SharedPtr<Decoder> decoder)
882 ALuint srate = decoder->getFrequency();
883 ChannelConfig chans = decoder->getChannelConfig();
884 SampleType type = decoder->getSampleType();
885 ALuint frames = static_cast<ALuint>(
886 std::min<uint64_t>(decoder->getLength(), std::numeric_limits<ALuint>::max())
889 Vector<ALbyte> data(FramesToBytes(frames, chans, type));
890 frames = decoder->read(data.data(), frames);
891 if(!frames)
892 return std::make_exception_ptr(std::runtime_error("No samples for buffer"));
893 data.resize(FramesToBytes(frames, chans, type));
895 std::pair<uint64_t,uint64_t> loop_pts = decoder->getLoopPoints();
896 if(loop_pts.first >= loop_pts.second)
897 loop_pts = std::make_pair(0, frames);
898 else
900 loop_pts.second = std::min<uint64_t>(loop_pts.second, frames);
901 loop_pts.first = std::min<uint64_t>(loop_pts.first, loop_pts.second-1);
904 // Get the format before calling the bufferLoading message handler, to
905 // ensure it's something OpenAL can handle.
906 ALenum format = GetFormat(chans, type);
907 if(UNLIKELY(format == AL_NONE))
909 auto str = String("Unsupported format (")+GetSampleTypeName(type)+", "+
910 GetChannelConfigName(chans)+")";
911 return std::make_exception_ptr(std::runtime_error(str));
914 if(mMessage.get())
915 mMessage->bufferLoading(name, chans, type, srate, data);
917 alGetError();
918 ALuint bid = 0;
919 alGenBuffers(1, &bid);
920 alBufferData(bid, format, data.data(), static_cast<ALsizei>(data.size()), srate);
921 if(hasExtension(AL::SOFT_loop_points))
923 ALint pts[2]{(ALint)loop_pts.first, (ALint)loop_pts.second};
924 alBufferiv(bid, AL_LOOP_POINTS_SOFT, pts);
926 if(ALenum err = alGetError())
928 alDeleteBuffers(1, &bid);
929 return std::make_exception_ptr(al_error(err, "Failed to buffer data"));
932 return mBuffers.insert(iter,
933 MakeUnique<BufferImpl>(*this, bid, srate, chans, type, name, name_hash)
934 )->get();
937 BufferOrExceptT ContextImpl::doCreateBufferAsync(StringView name, size_t name_hash, BufferListT::const_iterator iter, SharedPtr<Decoder> decoder, Promise<Buffer> promise)
939 ALuint srate = decoder->getFrequency();
940 ChannelConfig chans = decoder->getChannelConfig();
941 SampleType type = decoder->getSampleType();
942 ALuint frames = static_cast<ALuint>(
943 std::min<uint64_t>(decoder->getLength(), std::numeric_limits<ALuint>::max())
945 if(!frames)
946 return std::make_exception_ptr(std::runtime_error("No samples for buffer"));
948 ALenum format = GetFormat(chans, type);
949 if(UNLIKELY(format == AL_NONE))
951 auto str = String("Unsupported format (")+GetSampleTypeName(type)+", "+
952 GetChannelConfigName(chans)+")";
953 return std::make_exception_ptr(std::runtime_error(str));
956 alGetError();
957 ALuint bid = 0;
958 alGenBuffers(1, &bid);
959 if(ALenum err = alGetError())
960 return std::make_exception_ptr(al_error(err, "Failed to create buffer"));
962 auto buffer = MakeUnique<BufferImpl>(*this, bid, srate, chans, type, name, name_hash);
964 if(mThread.get_id() == std::thread::id())
965 mThread = std::thread(std::mem_fn(&ContextImpl::backgroundProc), this);
967 PendingPromise *pf = nullptr;
968 if(mPendingTail == mPendingCurrent.load(std::memory_order_acquire))
969 pf = new PendingPromise{buffer.get(), std::move(decoder), format, frames,
970 std::move(promise), {nullptr}};
971 else
973 pf = mPendingTail;
974 pf->mBuffer = buffer.get();
975 pf->mDecoder = std::move(decoder);
976 pf->mFormat = format;
977 pf->mFrames = frames;
978 pf->mPromise = std::move(promise);
979 mPendingTail = pf->mNext.exchange(nullptr, std::memory_order_relaxed);
982 mPendingHead->mNext.store(pf, std::memory_order_release);
983 mPendingHead = pf;
985 return mBuffers.insert(iter, std::move(buffer))->get();
988 DECL_THUNK1(Buffer, Context, getBuffer,, StringView)
989 Buffer ContextImpl::getBuffer(StringView name)
991 CheckContext(this);
993 auto hasher = std::hash<StringView>();
994 size_t name_hash = hasher(name);
995 if(UNLIKELY(!mFutureBuffers.empty()))
997 Buffer buffer;
999 // If the buffer is already pending for the future, wait for it
1000 auto iter = findFutureBufferName(name, name_hash);
1001 if(iter != mFutureBuffers.end() && iter->mBuffer->getNameHash() == name_hash)
1003 buffer = iter->mFuture.get();
1004 mFutureBuffers.erase(iter);
1007 // Clear out any completed futures.
1008 mFutureBuffers.erase(
1009 std::remove_if(mFutureBuffers.begin(), mFutureBuffers.end(),
1010 [](const PendingBuffer &entry) -> bool
1011 { return GetFutureState(entry.mFuture) == std::future_status::ready; }
1012 ), mFutureBuffers.end()
1015 // If we got the buffer, return it. Otherwise, go load it normally.
1016 if(buffer) return buffer;
1019 auto iter = findBufferName(name, name_hash);
1020 if(iter != mBuffers.end() && (*iter)->getNameHash() == name_hash)
1021 return Buffer(iter->get());
1023 BufferOrExceptT ret = doCreateBuffer(name, name_hash, iter, createDecoder(name));
1024 Buffer *buffer = std::get_if<Buffer>(&ret);
1025 if(UNLIKELY(!buffer))
1026 std::rethrow_exception(std::get<std::exception_ptr>(ret));
1027 return *buffer;
1030 DECL_THUNK1(SharedFuture<Buffer>, Context, getBufferAsync,, StringView)
1031 SharedFuture<Buffer> ContextImpl::getBufferAsync(StringView name)
1033 SharedFuture<Buffer> future;
1034 CheckContext(this);
1036 auto hasher = std::hash<StringView>();
1037 size_t name_hash = hasher(name);
1038 if(UNLIKELY(!mFutureBuffers.empty()))
1040 // Check if the future that's being created already exists
1041 auto iter = findFutureBufferName(name, name_hash);
1042 if(iter != mFutureBuffers.end() && iter->mBuffer->getNameHash() == name_hash)
1044 future = iter->mFuture;
1045 if(GetFutureState(future) == std::future_status::ready)
1046 mFutureBuffers.erase(iter);
1047 return future;
1050 // Clear out any fulfilled futures.
1051 mFutureBuffers.erase(
1052 std::remove_if(mFutureBuffers.begin(), mFutureBuffers.end(),
1053 [](const PendingBuffer &entry) -> bool
1054 { return GetFutureState(entry.mFuture) == std::future_status::ready; }
1055 ), mFutureBuffers.end()
1059 auto iter = findBufferName(name, name_hash);
1060 if(iter != mBuffers.end() && (*iter)->getNameHash() == name_hash)
1062 // User asked to create a future buffer that's already loaded. Just
1063 // construct a promise, fulfill the promise immediately, then return a
1064 // shared future that's already set.
1065 Promise<Buffer> promise;
1066 promise.set_value(Buffer(iter->get()));
1067 future = promise.get_future().share();
1068 return future;
1071 Promise<Buffer> promise;
1072 future = promise.get_future().share();
1074 BufferOrExceptT ret = doCreateBufferAsync(name, name_hash, iter, createDecoder(name), std::move(promise));
1075 Buffer *buffer = std::get_if<Buffer>(&ret);
1076 if(UNLIKELY(!buffer))
1077 std::rethrow_exception(std::get<std::exception_ptr>(ret));
1078 mWakeMutex.lock(); mWakeMutex.unlock();
1079 mWakeThread.notify_all();
1081 mFutureBuffers.insert(
1082 std::lower_bound(mFutureBuffers.begin(), mFutureBuffers.end(), name_hash,
1083 [](const PendingBuffer &lhs, size_t rhs) -> bool
1084 { return lhs.mBuffer->getNameHash() < rhs; }
1085 ), { buffer->getHandle(), future }
1088 return future;
1091 DECL_THUNK1(void, Context, precacheBuffersAsync,, ArrayView<StringView>)
1092 void ContextImpl::precacheBuffersAsync(ArrayView<StringView> names)
1094 CheckContext(this);
1096 if(UNLIKELY(!mFutureBuffers.empty()))
1098 // Clear out any fulfilled futures.
1099 mFutureBuffers.erase(
1100 std::remove_if(mFutureBuffers.begin(), mFutureBuffers.end(),
1101 [](const PendingBuffer &entry) -> bool
1102 { return GetFutureState(entry.mFuture) == std::future_status::ready; }
1103 ), mFutureBuffers.end()
1107 auto hasher = std::hash<StringView>();
1108 for(const StringView name : names)
1110 size_t name_hash = hasher(name);
1112 // Check if the buffer that's being created already exists
1113 auto iter = findBufferName(name, name_hash);
1114 if(iter != mBuffers.end() && (*iter)->getNameHash() == name_hash)
1115 continue;
1117 DecoderOrExceptT dec = findDecoder(name);
1118 SharedPtr<Decoder> *decoder = std::get_if<SharedPtr<Decoder>>(&dec);
1119 if(!decoder) continue;
1121 Promise<Buffer> promise;
1122 SharedFuture<Buffer> future = promise.get_future().share();
1124 BufferOrExceptT buf = doCreateBufferAsync(name, name_hash, iter, std::move(*decoder),
1125 std::move(promise));
1126 Buffer *buffer = std::get_if<Buffer>(&buf);
1127 if(UNLIKELY(!buffer)) continue;
1129 mFutureBuffers.insert(
1130 std::lower_bound(mFutureBuffers.begin(), mFutureBuffers.end(), name_hash,
1131 [](const PendingBuffer &lhs, size_t rhs) -> bool
1132 { return lhs.mBuffer->getNameHash() < rhs; }
1133 ), { buffer->getHandle(), future }
1136 mWakeMutex.lock(); mWakeMutex.unlock();
1137 mWakeThread.notify_all();
1140 DECL_THUNK2(Buffer, Context, createBufferFrom,, StringView, SharedPtr<Decoder>)
1141 Buffer ContextImpl::createBufferFrom(StringView name, SharedPtr<Decoder>&& decoder)
1143 CheckContext(this);
1145 auto hasher = std::hash<StringView>();
1146 size_t name_hash = hasher(name);
1147 auto iter = findBufferName(name, name_hash);
1148 if(iter != mBuffers.end() && (*iter)->getNameHash() == name_hash)
1149 throw std::runtime_error("Buffer already exists");
1151 BufferOrExceptT ret = doCreateBuffer(name, name_hash, iter, std::move(decoder));
1152 Buffer *buffer = std::get_if<Buffer>(&ret);
1153 if(UNLIKELY(!buffer))
1154 std::rethrow_exception(std::get<std::exception_ptr>(ret));
1155 return *buffer;
1158 DECL_THUNK2(SharedFuture<Buffer>, Context, createBufferAsyncFrom,, StringView, SharedPtr<Decoder>)
1159 SharedFuture<Buffer> ContextImpl::createBufferAsyncFrom(StringView name, SharedPtr<Decoder>&& decoder)
1161 SharedFuture<Buffer> future;
1162 CheckContext(this);
1164 if(UNLIKELY(!mFutureBuffers.empty()))
1166 // Clear out any fulfilled futures.
1167 mFutureBuffers.erase(
1168 std::remove_if(mFutureBuffers.begin(), mFutureBuffers.end(),
1169 [](const PendingBuffer &entry) -> bool
1170 { return GetFutureState(entry.mFuture) == std::future_status::ready; }
1171 ), mFutureBuffers.end()
1175 auto hasher = std::hash<StringView>();
1176 size_t name_hash = hasher(name);
1177 auto iter = findBufferName(name, name_hash);
1178 if(iter != mBuffers.end() && (*iter)->getNameHash() == name_hash)
1179 throw std::runtime_error("Buffer already exists");
1181 Promise<Buffer> promise;
1182 future = promise.get_future().share();
1184 BufferOrExceptT ret = doCreateBufferAsync(name, name_hash, iter, std::move(decoder), std::move(promise));
1185 Buffer *buffer = std::get_if<Buffer>(&ret);
1186 if(UNLIKELY(!buffer))
1187 std::rethrow_exception(std::get<std::exception_ptr>(ret));
1188 mWakeMutex.lock(); mWakeMutex.unlock();
1189 mWakeThread.notify_all();
1191 mFutureBuffers.insert(
1192 std::lower_bound(mFutureBuffers.begin(), mFutureBuffers.end(), name_hash,
1193 [](const PendingBuffer &lhs, size_t rhs) -> bool
1194 { return lhs.mBuffer->getNameHash() < rhs; }
1195 ), { buffer->getHandle(), future }
1198 return future;
1202 DECL_THUNK1(Buffer, Context, findBuffer,, StringView)
1203 Buffer ContextImpl::findBuffer(StringView name)
1205 Buffer buffer;
1206 CheckContext(this);
1208 auto hasher = std::hash<StringView>();
1209 size_t name_hash = hasher(name);
1210 if(UNLIKELY(!mFutureBuffers.empty()))
1212 // If the buffer is already pending for the future, wait for it
1213 auto iter = findFutureBufferName(name, name_hash);
1214 if(iter != mFutureBuffers.end() && iter->mBuffer->getNameHash() == name_hash)
1216 buffer = iter->mFuture.get();
1217 mFutureBuffers.erase(iter);
1220 // Clear out any completed futures.
1221 mFutureBuffers.erase(
1222 std::remove_if(mFutureBuffers.begin(), mFutureBuffers.end(),
1223 [](const PendingBuffer &entry) -> bool
1224 { return GetFutureState(entry.mFuture) == std::future_status::ready; }
1225 ), mFutureBuffers.end()
1229 if(LIKELY(!buffer))
1231 auto iter = findBufferName(name, name_hash);
1232 if(iter != mBuffers.end() && (*iter)->getNameHash() == name_hash)
1233 buffer = Buffer(iter->get());
1235 return buffer;
1238 DECL_THUNK1(SharedFuture<Buffer>, Context, findBufferAsync,, StringView)
1239 SharedFuture<Buffer> ContextImpl::findBufferAsync(StringView name)
1241 SharedFuture<Buffer> future;
1242 CheckContext(this);
1244 auto hasher = std::hash<StringView>();
1245 size_t name_hash = hasher(name);
1246 if(UNLIKELY(!mFutureBuffers.empty()))
1248 // Check if the future that's being created already exists
1249 auto iter = findFutureBufferName(name, name_hash);
1250 if(iter != mFutureBuffers.end() && iter->mBuffer->getNameHash() == name_hash)
1252 future = iter->mFuture;
1253 if(GetFutureState(future) == std::future_status::ready)
1254 mFutureBuffers.erase(iter);
1255 return future;
1258 // Clear out any fulfilled futures.
1259 mFutureBuffers.erase(
1260 std::remove_if(mFutureBuffers.begin(), mFutureBuffers.end(),
1261 [](const PendingBuffer &entry) -> bool
1262 { return GetFutureState(entry.mFuture) == std::future_status::ready; }
1263 ), mFutureBuffers.end()
1267 auto iter = findBufferName(name, name_hash);
1268 if(iter != mBuffers.end() && (*iter)->getNameHash() == name_hash)
1270 // User asked to create a future buffer that's already loaded. Just
1271 // construct a promise, fulfill the promise immediately, then return a
1272 // shared future that's already set.
1273 Promise<Buffer> promise;
1274 promise.set_value(Buffer(iter->get()));
1275 future = promise.get_future().share();
1277 return future;
1281 DECL_THUNK1(void, Context, removeBuffer,, Buffer)
1282 DECL_THUNK1(void, Context, removeBuffer,, StringView)
1283 void ContextImpl::removeBuffer(StringView name)
1285 CheckContext(this);
1287 auto hasher = std::hash<StringView>();
1288 size_t name_hash = hasher(name);
1289 if(UNLIKELY(!mFutureBuffers.empty()))
1291 // If the buffer is already pending for the future, wait for it to
1292 // finish before continuing.
1293 auto iter = findFutureBufferName(name, name_hash);
1294 if(iter != mFutureBuffers.end() && iter->mBuffer->getNameHash() == name_hash)
1296 iter->mFuture.wait();
1297 mFutureBuffers.erase(iter);
1300 // Clear out any completed futures.
1301 mFutureBuffers.erase(
1302 std::remove_if(mFutureBuffers.begin(), mFutureBuffers.end(),
1303 [](const PendingBuffer &entry) -> bool
1304 { return GetFutureState(entry.mFuture) == std::future_status::ready; }
1305 ), mFutureBuffers.end()
1309 auto iter = findBufferName(name, name_hash);
1310 if(iter != mBuffers.end() && (*iter)->getNameHash() == name_hash)
1312 // Remove pending sources whose future was waiting for this buffer.
1313 BufferImpl *buffer = iter->get();
1314 mPendingSources.erase(
1315 std::remove_if(mPendingSources.begin(), mPendingSources.end(),
1316 [buffer](PendingSource &entry) -> bool
1318 return (GetFutureState(entry.mFuture) == std::future_status::ready &&
1319 entry.mFuture.get().getHandle() == buffer);
1321 ), mPendingSources.end()
1323 (*iter)->cleanup();
1324 mBuffers.erase(iter);
1329 ALuint ContextImpl::getSourceId(ALuint maxprio)
1331 ALuint id = 0;
1332 if(mSourceIds.empty())
1334 alGetError();
1335 alGenSources(1, &id);
1336 if(alGetError() == AL_NO_ERROR)
1337 return id;
1339 SourceImpl *lowest = nullptr;
1340 for(SourceBufferUpdateEntry &entry : mPlaySources)
1342 if(!lowest || entry.mSource->getPriority() < lowest->getPriority())
1343 lowest = entry.mSource;
1345 for(SourceStreamUpdateEntry &entry : mStreamSources)
1347 if(!lowest || entry.mSource->getPriority() < lowest->getPriority())
1348 lowest = entry.mSource;
1350 if(lowest && lowest->getPriority() < maxprio)
1352 lowest->stop();
1353 if(mMessage.get())
1354 mMessage->sourceForceStopped(lowest);
1357 if(mSourceIds.empty())
1358 throw std::runtime_error("No available sources");
1360 id = mSourceIds.back();
1361 mSourceIds.pop_back();
1362 return id;
1366 DECL_THUNK0(Source, Context, createSource,)
1367 Source ContextImpl::createSource()
1369 CheckContext(this);
1371 SourceImpl *source;
1372 if(!mFreeSources.empty())
1374 source = mFreeSources.back();
1375 mFreeSources.pop_back();
1377 else
1379 mAllSources.emplace_back(*this);
1380 source = &mAllSources.back();
1382 return Source(source);
1386 void ContextImpl::addPendingSource(SourceImpl *source, SharedFuture<Buffer> future)
1388 auto iter = std::lower_bound(mPendingSources.begin(), mPendingSources.end(), source,
1389 [](const PendingSource &lhs, SourceImpl *rhs) -> bool
1390 { return lhs.mSource < rhs; }
1392 if(iter == mPendingSources.end() || iter->mSource != source)
1393 mPendingSources.insert(iter, {source, std::move(future)});
1396 void ContextImpl::removePendingSource(SourceImpl *source)
1398 auto iter = std::lower_bound(mPendingSources.begin(), mPendingSources.end(), source,
1399 [](const PendingSource &lhs, SourceImpl *rhs) -> bool
1400 { return lhs.mSource < rhs; }
1402 if(iter != mPendingSources.end() && iter->mSource == source)
1403 mPendingSources.erase(iter);
1406 bool ContextImpl::isPendingSource(const SourceImpl *source) const
1408 auto iter = std::lower_bound(mPendingSources.begin(), mPendingSources.end(), source,
1409 [](const PendingSource &lhs, const SourceImpl *rhs) -> bool
1410 { return lhs.mSource < rhs; }
1412 return (iter != mPendingSources.end() && iter->mSource == source);
1415 void ContextImpl::addFadingSource(SourceImpl *source, std::chrono::nanoseconds duration, ALfloat gain)
1417 auto iter = std::lower_bound(mFadingSources.begin(), mFadingSources.end(), source,
1418 [](const SourceFadeUpdateEntry &lhs, SourceImpl *rhs) -> bool
1419 { return lhs.mSource < rhs; }
1421 if(iter == mFadingSources.end() || iter->mSource != source)
1423 auto now = mDevice.getClockTime();
1424 mFadingSources.emplace(iter, SourceFadeUpdateEntry{source, now, now+duration, true, gain});
1428 void ContextImpl::removeFadingSource(SourceImpl *source)
1430 auto iter = std::lower_bound(mFadingSources.begin(), mFadingSources.end(), source,
1431 [](const SourceFadeUpdateEntry &lhs, SourceImpl *rhs) -> bool
1432 { return lhs.mSource < rhs; }
1434 if(iter != mFadingSources.end() && iter->mSource == source)
1435 mFadingSources.erase(iter);
1438 void ContextImpl::addPlayingSource(SourceImpl *source, ALuint id)
1440 auto iter = std::lower_bound(mPlaySources.begin(), mPlaySources.end(), source,
1441 [](const SourceBufferUpdateEntry &lhs, SourceImpl *rhs) -> bool
1442 { return lhs.mSource < rhs; }
1444 if(iter == mPlaySources.end() || iter->mSource != source)
1445 mPlaySources.insert(iter, {source,id});
1448 void ContextImpl::addPlayingSource(SourceImpl *source)
1450 auto iter = std::lower_bound(mStreamSources.begin(), mStreamSources.end(), source,
1451 [](const SourceStreamUpdateEntry &lhs, SourceImpl *rhs) -> bool
1452 { return lhs.mSource < rhs; }
1454 if(iter == mStreamSources.end() || iter->mSource != source)
1455 mStreamSources.insert(iter, {source});
1458 void ContextImpl::removePlayingSource(SourceImpl *source)
1460 auto iter0 = std::lower_bound(mPlaySources.begin(), mPlaySources.end(), source,
1461 [](const SourceBufferUpdateEntry &lhs, SourceImpl *rhs) -> bool
1462 { return lhs.mSource < rhs; }
1464 if(iter0 != mPlaySources.end() && iter0->mSource == source)
1465 mPlaySources.erase(iter0);
1466 else
1468 auto iter1 = std::lower_bound(mStreamSources.begin(), mStreamSources.end(), source,
1469 [](const SourceStreamUpdateEntry &lhs, SourceImpl *rhs) -> bool
1470 { return lhs.mSource < rhs; }
1472 if(iter1 != mStreamSources.end() && iter1->mSource == source)
1473 mStreamSources.erase(iter1);
1478 void ContextImpl::addStream(SourceImpl *source)
1480 std::lock_guard<std::mutex> lock(mSourceStreamMutex);
1481 if(mThread.get_id() == std::thread::id())
1482 mThread = std::thread(std::mem_fn(&ContextImpl::backgroundProc), this);
1483 auto iter = std::lower_bound(mStreamingSources.begin(), mStreamingSources.end(), source);
1484 if(iter == mStreamingSources.end() || *iter != source)
1485 mStreamingSources.insert(iter, source);
1488 void ContextImpl::removeStream(SourceImpl *source)
1490 std::lock_guard<std::mutex> lock(mSourceStreamMutex);
1491 auto iter = std::lower_bound(mStreamingSources.begin(), mStreamingSources.end(), source);
1492 if(iter != mStreamingSources.end() && *iter == source)
1493 mStreamingSources.erase(iter);
1496 void ContextImpl::removeStreamNoLock(SourceImpl *source)
1498 auto iter = std::lower_bound(mStreamingSources.begin(), mStreamingSources.end(), source);
1499 if(iter != mStreamingSources.end() && *iter == source)
1500 mStreamingSources.erase(iter);
1504 DECL_THUNK0(AuxiliaryEffectSlot, Context, createAuxiliaryEffectSlot,)
1505 AuxiliaryEffectSlot ContextImpl::createAuxiliaryEffectSlot()
1507 if(!hasExtension(AL::EXT_EFX))
1508 throw std::runtime_error("AuxiliaryEffectSlots not supported");
1509 CheckContext(this);
1511 auto slot = MakeUnique<AuxiliaryEffectSlotImpl>(*this);
1512 auto iter = std::lower_bound(mEffectSlots.begin(), mEffectSlots.end(), slot);
1513 return AuxiliaryEffectSlot(mEffectSlots.insert(iter, std::move(slot))->get());
1516 void ContextImpl::freeEffectSlot(AuxiliaryEffectSlotImpl *slot)
1518 auto iter = std::lower_bound(mEffectSlots.begin(), mEffectSlots.end(), slot,
1519 [](const UniquePtr<AuxiliaryEffectSlotImpl> &lhs, AuxiliaryEffectSlotImpl *rhs) -> bool
1520 { return lhs.get() < rhs; }
1522 if(iter != mEffectSlots.end() && iter->get() == slot)
1523 mEffectSlots.erase(iter);
1527 DECL_THUNK0(Effect, Context, createEffect,)
1528 Effect ContextImpl::createEffect()
1530 if(!hasExtension(AL::EXT_EFX))
1531 throw std::runtime_error("Effects not supported");
1532 CheckContext(this);
1534 auto effect = MakeUnique<EffectImpl>(*this);
1535 auto iter = std::lower_bound(mEffects.begin(), mEffects.end(), effect);
1536 return Effect(mEffects.insert(iter, std::move(effect))->get());
1539 void ContextImpl::freeEffect(EffectImpl *effect)
1541 auto iter = std::lower_bound(mEffects.begin(), mEffects.end(), effect,
1542 [](const UniquePtr<EffectImpl> &lhs, EffectImpl *rhs) -> bool
1543 { return lhs.get() < rhs; }
1545 if(iter != mEffects.end() && iter->get() == effect)
1546 mEffects.erase(iter);
1550 DECL_THUNK0(SourceGroup, Context, createSourceGroup,)
1551 SourceGroup ContextImpl::createSourceGroup()
1553 auto srcgroup = MakeUnique<SourceGroupImpl>(*this);
1554 auto iter = std::lower_bound(mSourceGroups.begin(), mSourceGroups.end(), srcgroup);
1556 iter = mSourceGroups.insert(iter, std::move(srcgroup));
1557 return SourceGroup(iter->get());
1560 void ContextImpl::freeSourceGroup(SourceGroupImpl *group)
1562 auto iter = std::lower_bound(mSourceGroups.begin(), mSourceGroups.end(), group,
1563 [](const UniquePtr<SourceGroupImpl> &lhs, SourceGroupImpl *rhs) -> bool
1564 { return lhs.get() < rhs; }
1566 if(iter != mSourceGroups.end() && iter->get() == group)
1567 mSourceGroups.erase(iter);
1571 DECL_THUNK1(void, Context, setDopplerFactor,, ALfloat)
1572 void ContextImpl::setDopplerFactor(ALfloat factor)
1574 if(!(factor >= 0.0f))
1575 throw std::out_of_range("Doppler factor out of range");
1576 CheckContext(this);
1577 alDopplerFactor(factor);
1581 DECL_THUNK1(void, Context, setSpeedOfSound,, ALfloat)
1582 void ContextImpl::setSpeedOfSound(ALfloat speed)
1584 if(!(speed > 0.0f))
1585 throw std::out_of_range("Speed of sound out of range");
1586 CheckContext(this);
1587 alSpeedOfSound(speed);
1591 DECL_THUNK1(void, Context, setDistanceModel,, DistanceModel)
1592 void ContextImpl::setDistanceModel(DistanceModel model)
1594 CheckContext(this);
1595 alDistanceModel((ALenum)model);
1599 DECL_THUNK0(void, Context, update,)
1600 void ContextImpl::update()
1602 CheckContext(this);
1603 mPendingSources.erase(
1604 std::remove_if(mPendingSources.begin(), mPendingSources.end(),
1605 [](PendingSource &entry) -> bool
1606 { return !entry.mSource->checkPending(entry.mFuture); }
1607 ), mPendingSources.end()
1609 if(!mFadingSources.empty())
1611 auto cur_time = mDevice.getClockTime();
1612 mFadingSources.erase(
1613 std::remove_if(mFadingSources.begin(), mFadingSources.end(),
1614 [cur_time](SourceFadeUpdateEntry &entry) -> bool
1615 { return !entry.mSource->fadeUpdate(cur_time, entry); }
1616 ), mFadingSources.end()
1619 mPlaySources.erase(
1620 std::remove_if(mPlaySources.begin(), mPlaySources.end(),
1621 [](const SourceBufferUpdateEntry &entry) -> bool
1622 { return !entry.mSource->playUpdate(entry.mId); }
1623 ), mPlaySources.end()
1625 mStreamSources.erase(
1626 std::remove_if(mStreamSources.begin(), mStreamSources.end(),
1627 [](const SourceStreamUpdateEntry &entry) -> bool
1628 { return !entry.mSource->playUpdate(); }
1629 ), mStreamSources.end()
1632 if(!mWakeInterval.load(std::memory_order_relaxed).count())
1634 // For performance reasons, don't wait for the thread's mutex. This
1635 // should be called often enough to keep up with any and all streams
1636 // regardless.
1637 mWakeThread.notify_all();
1640 if(hasExtension(AL::EXT_disconnect) && mIsConnected)
1642 ALCint connected;
1643 alcGetIntegerv(mDevice.getALCdevice(), ALC_CONNECTED, 1, &connected);
1644 mIsConnected = static_cast<bool>(connected);
1645 if(!mIsConnected && mMessage.get()) mMessage->deviceDisconnected(Device(&mDevice));
1649 DECL_THUNK0(Device, Context, getDevice,)
1650 DECL_THUNK0(std::chrono::milliseconds, Context, getAsyncWakeInterval, const)
1651 DECL_THUNK0(Listener, Context, getListener,)
1652 DECL_THUNK0(SharedPtr<MessageHandler>, Context, getMessageHandler, const)
1654 void Context::MakeCurrent(Context context)
1655 { ContextImpl::MakeCurrent(context.pImpl); }
1657 Context Context::GetCurrent()
1658 { return Context(ContextImpl::GetCurrent()); }
1660 void Context::MakeThreadCurrent(Context context)
1661 { ContextImpl::MakeThreadCurrent(context.pImpl); }
1663 Context Context::GetThreadCurrent()
1664 { return Context(ContextImpl::GetThreadCurrent()); }
1667 DECL_THUNK1(void, Listener, setGain,, ALfloat)
1668 void ListenerImpl::setGain(ALfloat gain)
1670 if(!(gain >= 0.0f))
1671 throw std::out_of_range("Gain out of range");
1672 CheckContext(mContext);
1673 alListenerf(AL_GAIN, gain);
1677 DECL_THUNK3(void, Listener, set3DParameters,, const Vector3&, const Vector3&, const Vector3Pair&)
1678 void ListenerImpl::set3DParameters(const Vector3 &position, const Vector3 &velocity, const std::pair<Vector3,Vector3> &orientation)
1680 static_assert(sizeof(orientation) == sizeof(ALfloat[6]), "Invalid Vector3 pair size");
1681 CheckContext(mContext);
1682 Batcher batcher = mContext->getBatcher();
1683 alListenerfv(AL_POSITION, position.getPtr());
1684 alListenerfv(AL_VELOCITY, velocity.getPtr());
1685 alListenerfv(AL_ORIENTATION, orientation.first.getPtr());
1688 DECL_THUNK1(void, Listener, setPosition,, const Vector3&)
1689 void ListenerImpl::setPosition(const Vector3 &position)
1691 CheckContext(mContext);
1692 alListenerfv(AL_POSITION, position.getPtr());
1695 DECL_THUNK1(void, Listener, setPosition,, const ALfloat*)
1696 void ListenerImpl::setPosition(const ALfloat *pos)
1698 CheckContext(mContext);
1699 alListenerfv(AL_POSITION, pos);
1702 DECL_THUNK1(void, Listener, setVelocity,, const Vector3&)
1703 void ListenerImpl::setVelocity(const Vector3 &velocity)
1705 CheckContext(mContext);
1706 alListenerfv(AL_VELOCITY, velocity.getPtr());
1709 DECL_THUNK1(void, Listener, setVelocity,, const ALfloat*)
1710 void ListenerImpl::setVelocity(const ALfloat *vel)
1712 CheckContext(mContext);
1713 alListenerfv(AL_VELOCITY, vel);
1716 DECL_THUNK1(void, Listener, setOrientation,, const Vector3Pair&)
1717 void ListenerImpl::setOrientation(const std::pair<Vector3,Vector3> &orientation)
1719 CheckContext(mContext);
1720 alListenerfv(AL_ORIENTATION, orientation.first.getPtr());
1723 DECL_THUNK2(void, Listener, setOrientation,, const ALfloat*, const ALfloat*)
1724 void ListenerImpl::setOrientation(const ALfloat *at, const ALfloat *up)
1726 CheckContext(mContext);
1727 ALfloat ori[6] = { at[0], at[1], at[2], up[0], up[1], up[2] };
1728 alListenerfv(AL_ORIENTATION, ori);
1731 DECL_THUNK1(void, Listener, setOrientation,, const ALfloat*)
1732 void ListenerImpl::setOrientation(const ALfloat *ori)
1734 CheckContext(mContext);
1735 alListenerfv(AL_ORIENTATION, ori);
1738 DECL_THUNK1(void, Listener, setMetersPerUnit,, ALfloat)
1739 void ListenerImpl::setMetersPerUnit(ALfloat m_u)
1741 if(!(m_u > 0.0f))
1742 throw std::out_of_range("Invalid meters per unit");
1743 CheckContext(mContext);
1744 if(mContext->hasExtension(AL::EXT_EFX))
1745 alListenerf(AL_METERS_PER_UNIT, m_u);