buffer.cpp 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665
  1. /**
  2. * OpenAL cross platform audio library
  3. * Copyright (C) 1999-2007 by authors.
  4. * This library is free software; you can redistribute it and/or
  5. * modify it under the terms of the GNU Library General Public
  6. * License as published by the Free Software Foundation; either
  7. * version 2 of the License, or (at your option) any later version.
  8. *
  9. * This library is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. * Library General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU Library General Public
  15. * License along with this library; if not, write to the
  16. * Free Software Foundation, Inc.,
  17. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  18. * Or go to http://www.gnu.org/copyleft/lgpl.html
  19. */
  20. #include "config.h"
  21. #include "buffer.h"
  22. #include <algorithm>
  23. #include <array>
  24. #include <atomic>
  25. #include <cassert>
  26. #include <cstddef>
  27. #include <cstdint>
  28. #include <cstring>
  29. #include <iterator>
  30. #include <limits>
  31. #include <memory>
  32. #include <mutex>
  33. #include <numeric>
  34. #include <optional>
  35. #include <stdexcept>
  36. #include <string>
  37. #include <unordered_map>
  38. #include <utility>
  39. #include <vector>
  40. #include "AL/al.h"
  41. #include "AL/alc.h"
  42. #include "AL/alext.h"
  43. #include "albit.h"
  44. #include "alc/context.h"
  45. #include "alc/device.h"
  46. #include "alc/inprogext.h"
  47. #include "almalloc.h"
  48. #include "alnumeric.h"
  49. #include "alspan.h"
  50. #include "core/device.h"
  51. #include "core/resampler_limits.h"
  52. #include "core/voice.h"
  53. #include "direct_defs.h"
  54. #include "error.h"
  55. #include "intrusive_ptr.h"
  56. #include "opthelpers.h"
  57. #ifdef ALSOFT_EAX
  58. #include <unordered_set>
  59. #include "eax/globals.h"
  60. #include "eax/x_ram.h"
  61. #endif // ALSOFT_EAX
  62. namespace {
  63. using SubListAllocator = al::allocator<std::array<ALbuffer,64>>;
  64. constexpr auto AmbiLayoutFromEnum(ALenum layout) noexcept -> std::optional<AmbiLayout>
  65. {
  66. switch(layout)
  67. {
  68. case AL_FUMA_SOFT: return AmbiLayout::FuMa;
  69. case AL_ACN_SOFT: return AmbiLayout::ACN;
  70. }
  71. return std::nullopt;
  72. }
  73. constexpr auto EnumFromAmbiLayout(AmbiLayout layout) -> ALenum
  74. {
  75. switch(layout)
  76. {
  77. case AmbiLayout::FuMa: return AL_FUMA_SOFT;
  78. case AmbiLayout::ACN: return AL_ACN_SOFT;
  79. }
  80. throw std::runtime_error{"Invalid AmbiLayout: "+std::to_string(int(layout))};
  81. }
  82. constexpr auto AmbiScalingFromEnum(ALenum scale) noexcept -> std::optional<AmbiScaling>
  83. {
  84. switch(scale)
  85. {
  86. case AL_FUMA_SOFT: return AmbiScaling::FuMa;
  87. case AL_SN3D_SOFT: return AmbiScaling::SN3D;
  88. case AL_N3D_SOFT: return AmbiScaling::N3D;
  89. }
  90. return std::nullopt;
  91. }
  92. constexpr auto EnumFromAmbiScaling(AmbiScaling scale) -> ALenum
  93. {
  94. switch(scale)
  95. {
  96. case AmbiScaling::FuMa: return AL_FUMA_SOFT;
  97. case AmbiScaling::SN3D: return AL_SN3D_SOFT;
  98. case AmbiScaling::N3D: return AL_N3D_SOFT;
  99. case AmbiScaling::UHJ: break;
  100. }
  101. throw std::runtime_error{"Invalid AmbiScaling: "+std::to_string(int(scale))};
  102. }
  103. #ifdef ALSOFT_EAX
  104. constexpr auto EaxStorageFromEnum(ALenum scale) noexcept -> std::optional<EaxStorage>
  105. {
  106. switch(scale)
  107. {
  108. case AL_STORAGE_AUTOMATIC: return EaxStorage::Automatic;
  109. case AL_STORAGE_ACCESSIBLE: return EaxStorage::Accessible;
  110. case AL_STORAGE_HARDWARE: return EaxStorage::Hardware;
  111. }
  112. return std::nullopt;
  113. }
  114. constexpr auto EnumFromEaxStorage(EaxStorage storage) -> ALenum
  115. {
  116. switch(storage)
  117. {
  118. case EaxStorage::Automatic: return AL_STORAGE_AUTOMATIC;
  119. case EaxStorage::Accessible: return AL_STORAGE_ACCESSIBLE;
  120. case EaxStorage::Hardware: return AL_STORAGE_HARDWARE;
  121. }
  122. throw std::runtime_error{"Invalid EaxStorage: "+std::to_string(int(storage))};
  123. }
  124. bool eax_x_ram_check_availability(const ALCdevice &device, const ALbuffer &buffer,
  125. const ALuint newsize) noexcept
  126. {
  127. ALuint freemem{device.eax_x_ram_free_size};
  128. /* If the buffer is currently in "hardware", add its memory to the free
  129. * pool since it'll be "replaced".
  130. */
  131. if(buffer.eax_x_ram_is_hardware)
  132. freemem += buffer.OriginalSize;
  133. return freemem >= newsize;
  134. }
  135. void eax_x_ram_apply(ALCdevice &device, ALbuffer &buffer) noexcept
  136. {
  137. if(buffer.eax_x_ram_is_hardware)
  138. return;
  139. if(device.eax_x_ram_free_size >= buffer.OriginalSize)
  140. {
  141. device.eax_x_ram_free_size -= buffer.OriginalSize;
  142. buffer.eax_x_ram_is_hardware = true;
  143. }
  144. }
  145. void eax_x_ram_clear(ALCdevice& al_device, ALbuffer& al_buffer) noexcept
  146. {
  147. if(al_buffer.eax_x_ram_is_hardware)
  148. al_device.eax_x_ram_free_size += al_buffer.OriginalSize;
  149. al_buffer.eax_x_ram_is_hardware = false;
  150. }
  151. #endif // ALSOFT_EAX
  152. constexpr ALbitfieldSOFT INVALID_STORAGE_MASK{~unsigned(AL_MAP_READ_BIT_SOFT |
  153. AL_MAP_WRITE_BIT_SOFT | AL_MAP_PERSISTENT_BIT_SOFT | AL_PRESERVE_DATA_BIT_SOFT)};
  154. constexpr ALbitfieldSOFT MAP_READ_WRITE_FLAGS{AL_MAP_READ_BIT_SOFT | AL_MAP_WRITE_BIT_SOFT};
  155. constexpr ALbitfieldSOFT INVALID_MAP_FLAGS{~unsigned(AL_MAP_READ_BIT_SOFT | AL_MAP_WRITE_BIT_SOFT |
  156. AL_MAP_PERSISTENT_BIT_SOFT)};
  157. auto EnsureBuffers(ALCdevice *device, size_t needed) noexcept -> bool
  158. try {
  159. size_t count{std::accumulate(device->BufferList.cbegin(), device->BufferList.cend(), 0_uz,
  160. [](size_t cur, const BufferSubList &sublist) noexcept -> size_t
  161. { return cur + static_cast<ALuint>(al::popcount(sublist.FreeMask)); })};
  162. while(needed > count)
  163. {
  164. if(device->BufferList.size() >= 1<<25) UNLIKELY
  165. return false;
  166. BufferSubList sublist{};
  167. sublist.FreeMask = ~0_u64;
  168. sublist.Buffers = SubListAllocator{}.allocate(1);
  169. device->BufferList.emplace_back(std::move(sublist));
  170. count += std::tuple_size_v<SubListAllocator::value_type>;
  171. }
  172. return true;
  173. }
  174. catch(...) {
  175. return false;
  176. }
  177. ALbuffer *AllocBuffer(ALCdevice *device) noexcept
  178. {
  179. auto sublist = std::find_if(device->BufferList.begin(), device->BufferList.end(),
  180. [](const BufferSubList &entry) noexcept -> bool
  181. { return entry.FreeMask != 0; });
  182. auto lidx = static_cast<ALuint>(std::distance(device->BufferList.begin(), sublist));
  183. auto slidx = static_cast<ALuint>(al::countr_zero(sublist->FreeMask));
  184. ASSUME(slidx < 64);
  185. ALbuffer *buffer{al::construct_at(al::to_address(sublist->Buffers->begin() + slidx))};
  186. /* Add 1 to avoid buffer ID 0. */
  187. buffer->id = ((lidx<<6) | slidx) + 1;
  188. sublist->FreeMask &= ~(1_u64 << slidx);
  189. return buffer;
  190. }
  191. void FreeBuffer(ALCdevice *device, ALbuffer *buffer)
  192. {
  193. #ifdef ALSOFT_EAX
  194. eax_x_ram_clear(*device, *buffer);
  195. #endif // ALSOFT_EAX
  196. device->mBufferNames.erase(buffer->id);
  197. const ALuint id{buffer->id - 1};
  198. const size_t lidx{id >> 6};
  199. const ALuint slidx{id & 0x3f};
  200. std::destroy_at(buffer);
  201. device->BufferList[lidx].FreeMask |= 1_u64 << slidx;
  202. }
  203. auto LookupBuffer(ALCdevice *device, ALuint id) noexcept -> ALbuffer*
  204. {
  205. const size_t lidx{(id-1) >> 6};
  206. const ALuint slidx{(id-1) & 0x3f};
  207. if(lidx >= device->BufferList.size()) UNLIKELY
  208. return nullptr;
  209. BufferSubList &sublist = device->BufferList[lidx];
  210. if(sublist.FreeMask & (1_u64 << slidx)) UNLIKELY
  211. return nullptr;
  212. return al::to_address(sublist.Buffers->begin() + slidx);
  213. }
  214. constexpr auto SanitizeAlignment(FmtType type, ALuint align) noexcept -> ALuint
  215. {
  216. if(align == 0)
  217. {
  218. if(type == FmtIMA4)
  219. {
  220. /* Here is where things vary:
  221. * nVidia and Apple use 64+1 sample frames per block -> block_size=36 bytes per channel
  222. * Most PC sound software uses 2040+1 sample frames per block -> block_size=1024 bytes per channel
  223. */
  224. return 65;
  225. }
  226. if(type == FmtMSADPCM)
  227. return 64;
  228. return 1;
  229. }
  230. if(type == FmtIMA4)
  231. {
  232. /* IMA4 block alignment must be a multiple of 8, plus 1. */
  233. if((align&7) == 1) return static_cast<ALuint>(align);
  234. return 0;
  235. }
  236. if(type == FmtMSADPCM)
  237. {
  238. /* MSADPCM block alignment must be a multiple of 2. */
  239. if((align&1) == 0) return static_cast<ALuint>(align);
  240. return 0;
  241. }
  242. return static_cast<ALuint>(align);
  243. }
  244. /** Loads the specified data into the buffer, using the specified format. */
  245. void LoadData(ALCcontext *context [[maybe_unused]], ALbuffer *ALBuf, ALsizei freq, ALuint size,
  246. const FmtChannels DstChannels, const FmtType DstType, const std::byte *SrcData,
  247. ALbitfieldSOFT access)
  248. {
  249. if(ALBuf->ref.load(std::memory_order_relaxed) != 0 || ALBuf->MappedAccess != 0)
  250. throw al::context_error{AL_INVALID_OPERATION, "Modifying storage for in-use buffer %u",
  251. ALBuf->id};
  252. const ALuint unpackalign{ALBuf->UnpackAlign};
  253. const ALuint align{SanitizeAlignment(DstType, unpackalign)};
  254. if(align < 1)
  255. throw al::context_error{AL_INVALID_VALUE, "Invalid unpack alignment %u for %s samples",
  256. unpackalign, NameFromFormat(DstType)};
  257. const ALuint ambiorder{IsBFormat(DstChannels) ? ALBuf->UnpackAmbiOrder :
  258. (IsUHJ(DstChannels) ? 1 : 0)};
  259. if((access&AL_PRESERVE_DATA_BIT_SOFT))
  260. {
  261. /* Can only preserve data with the same format and alignment. */
  262. if(ALBuf->mChannels != DstChannels || ALBuf->mType != DstType)
  263. throw al::context_error{AL_INVALID_VALUE, "Preserving data of mismatched format"};
  264. if(ALBuf->mBlockAlign != align)
  265. throw al::context_error{AL_INVALID_VALUE, "Preserving data of mismatched alignment"};
  266. if(ALBuf->mAmbiOrder != ambiorder)
  267. throw al::context_error{AL_INVALID_VALUE, "Preserving data of mismatched order"};
  268. }
  269. /* Convert the size in bytes to blocks using the unpack block alignment. */
  270. const ALuint NumChannels{ChannelsFromFmt(DstChannels, ambiorder)};
  271. const ALuint BlockSize{NumChannels *
  272. ((DstType == FmtIMA4) ? (align-1)/2 + 4 :
  273. (DstType == FmtMSADPCM) ? (align-2)/2 + 7 :
  274. (align * BytesFromFmt(DstType)))};
  275. if((size%BlockSize) != 0)
  276. throw al::context_error{AL_INVALID_VALUE,
  277. "Data size %d is not a multiple of frame size %d (%d unpack alignment)",
  278. size, BlockSize, align};
  279. const ALuint blocks{size / BlockSize};
  280. if(blocks > std::numeric_limits<ALsizei>::max()/align)
  281. throw al::context_error{AL_OUT_OF_MEMORY,
  282. "Buffer size overflow, %d blocks x %d samples per block", blocks, align};
  283. if(blocks > std::numeric_limits<size_t>::max()/BlockSize)
  284. throw al::context_error{AL_OUT_OF_MEMORY,
  285. "Buffer size overflow, %d frames x %d bytes per frame", blocks, BlockSize};
  286. const size_t newsize{static_cast<size_t>(blocks) * BlockSize};
  287. #ifdef ALSOFT_EAX
  288. if(ALBuf->eax_x_ram_mode == EaxStorage::Hardware)
  289. {
  290. ALCdevice &device = *context->mALDevice;
  291. if(!eax_x_ram_check_availability(device, *ALBuf, size))
  292. throw al::context_error{AL_OUT_OF_MEMORY,
  293. "Out of X-RAM memory (avail: %u, needed: %u)", device.eax_x_ram_free_size, size};
  294. }
  295. #endif
  296. /* This could reallocate only when increasing the size or the new size is
  297. * less than half the current, but then the buffer's AL_SIZE would not be
  298. * very reliable for accounting buffer memory usage, and reporting the real
  299. * size could cause problems for apps that use AL_SIZE to try to get the
  300. * buffer's play length.
  301. */
  302. if(newsize != ALBuf->mDataStorage.size())
  303. {
  304. auto newdata = decltype(ALBuf->mDataStorage)(newsize, std::byte{});
  305. if((access&AL_PRESERVE_DATA_BIT_SOFT))
  306. {
  307. const size_t tocopy{std::min(newdata.size(), ALBuf->mDataStorage.size())};
  308. std::copy_n(ALBuf->mDataStorage.begin(), tocopy, newdata.begin());
  309. }
  310. newdata.swap(ALBuf->mDataStorage);
  311. }
  312. ALBuf->mData = ALBuf->mDataStorage;
  313. #ifdef ALSOFT_EAX
  314. eax_x_ram_clear(*context->mALDevice, *ALBuf);
  315. #endif
  316. if(SrcData != nullptr && !ALBuf->mData.empty())
  317. std::copy_n(SrcData, blocks*BlockSize, ALBuf->mData.begin());
  318. ALBuf->mBlockAlign = (DstType == FmtIMA4 || DstType == FmtMSADPCM) ? align : 1;
  319. ALBuf->OriginalSize = size;
  320. ALBuf->Access = access;
  321. ALBuf->mSampleRate = static_cast<ALuint>(freq);
  322. ALBuf->mChannels = DstChannels;
  323. ALBuf->mType = DstType;
  324. ALBuf->mAmbiOrder = ambiorder;
  325. ALBuf->mCallback = nullptr;
  326. ALBuf->mUserData = nullptr;
  327. ALBuf->mSampleLen = blocks * align;
  328. ALBuf->mLoopStart = 0;
  329. ALBuf->mLoopEnd = ALBuf->mSampleLen;
  330. #ifdef ALSOFT_EAX
  331. if(eax_g_is_enabled && ALBuf->eax_x_ram_mode == EaxStorage::Hardware)
  332. eax_x_ram_apply(*context->mALDevice, *ALBuf);
  333. #endif
  334. }
  335. /** Prepares the buffer to use the specified callback, using the specified format. */
  336. void PrepareCallback(ALCcontext *context [[maybe_unused]], ALbuffer *ALBuf, ALsizei freq,
  337. const FmtChannels DstChannels, const FmtType DstType, ALBUFFERCALLBACKTYPESOFT callback,
  338. void *userptr)
  339. {
  340. if(ALBuf->ref.load(std::memory_order_relaxed) != 0 || ALBuf->MappedAccess != 0)
  341. throw al::context_error{AL_INVALID_OPERATION, "Modifying callback for in-use buffer %u",
  342. ALBuf->id};
  343. const ALuint ambiorder{IsBFormat(DstChannels) ? ALBuf->UnpackAmbiOrder :
  344. (IsUHJ(DstChannels) ? 1 : 0)};
  345. const ALuint unpackalign{ALBuf->UnpackAlign};
  346. const ALuint align{SanitizeAlignment(DstType, unpackalign)};
  347. if(align < 1)
  348. throw al::context_error{AL_INVALID_VALUE, "Invalid unpack alignment %u for %s samples",
  349. unpackalign, NameFromFormat(DstType)};
  350. const ALuint BlockSize{ChannelsFromFmt(DstChannels, ambiorder) *
  351. ((DstType == FmtIMA4) ? (align-1)/2 + 4 :
  352. (DstType == FmtMSADPCM) ? (align-2)/2 + 7 :
  353. (align * BytesFromFmt(DstType)))};
  354. /* The maximum number of samples a callback buffer may need to store is a
  355. * full mixing line * max pitch * channel count, since it may need to hold
  356. * a full line's worth of sample frames before downsampling. An additional
  357. * MaxResamplerEdge is needed for "future" samples during resampling (the
  358. * voice will hold a history for the past samples).
  359. */
  360. static constexpr size_t line_size{DeviceBase::MixerLineSize*MaxPitch + MaxResamplerEdge};
  361. const size_t line_blocks{(line_size + align-1) / align};
  362. using BufferVectorType = decltype(ALBuf->mDataStorage);
  363. BufferVectorType(line_blocks*BlockSize).swap(ALBuf->mDataStorage);
  364. ALBuf->mData = ALBuf->mDataStorage;
  365. #ifdef ALSOFT_EAX
  366. eax_x_ram_clear(*context->mALDevice, *ALBuf);
  367. #endif
  368. ALBuf->mCallback = callback;
  369. ALBuf->mUserData = userptr;
  370. ALBuf->OriginalSize = 0;
  371. ALBuf->Access = 0;
  372. ALBuf->mBlockAlign = (DstType == FmtIMA4 || DstType == FmtMSADPCM) ? align : 1;
  373. ALBuf->mSampleRate = static_cast<ALuint>(freq);
  374. ALBuf->mChannels = DstChannels;
  375. ALBuf->mType = DstType;
  376. ALBuf->mAmbiOrder = ambiorder;
  377. ALBuf->mSampleLen = 0;
  378. ALBuf->mLoopStart = 0;
  379. ALBuf->mLoopEnd = ALBuf->mSampleLen;
  380. }
  381. /** Prepares the buffer to use caller-specified storage. */
  382. void PrepareUserPtr(ALCcontext *context [[maybe_unused]], ALbuffer *ALBuf, ALsizei freq,
  383. const FmtChannels DstChannels, const FmtType DstType, std::byte *sdata, const ALuint sdatalen)
  384. {
  385. if(ALBuf->ref.load(std::memory_order_relaxed) != 0 || ALBuf->MappedAccess != 0)
  386. throw al::context_error{AL_INVALID_OPERATION, "Modifying storage for in-use buffer %u",
  387. ALBuf->id};
  388. const ALuint unpackalign{ALBuf->UnpackAlign};
  389. const ALuint align{SanitizeAlignment(DstType, unpackalign)};
  390. if(align < 1)
  391. throw al::context_error{AL_INVALID_VALUE, "Invalid unpack alignment %u for %s samples",
  392. unpackalign, NameFromFormat(DstType)};
  393. auto get_type_alignment = [](const FmtType type) noexcept -> ALuint
  394. {
  395. /* NOTE: This only needs to be the required alignment for the CPU to
  396. * read/write the given sample type in the mixer.
  397. */
  398. switch(type)
  399. {
  400. case FmtUByte: return alignof(ALubyte);
  401. case FmtShort: return alignof(ALshort);
  402. case FmtInt: return alignof(ALint);
  403. case FmtFloat: return alignof(ALfloat);
  404. case FmtDouble: return alignof(ALdouble);
  405. case FmtMulaw: return alignof(ALubyte);
  406. case FmtAlaw: return alignof(ALubyte);
  407. case FmtIMA4: break;
  408. case FmtMSADPCM: break;
  409. }
  410. return 1;
  411. };
  412. const auto typealign = get_type_alignment(DstType);
  413. if((reinterpret_cast<uintptr_t>(sdata) & (typealign-1)) != 0)
  414. throw al::context_error{AL_INVALID_VALUE, "Pointer %p is misaligned for %s samples (%u)",
  415. static_cast<void*>(sdata), NameFromFormat(DstType), typealign};
  416. const ALuint ambiorder{IsBFormat(DstChannels) ? ALBuf->UnpackAmbiOrder :
  417. (IsUHJ(DstChannels) ? 1 : 0)};
  418. /* Convert the size in bytes to blocks using the unpack block alignment. */
  419. const ALuint NumChannels{ChannelsFromFmt(DstChannels, ambiorder)};
  420. const ALuint BlockSize{NumChannels *
  421. ((DstType == FmtIMA4) ? (align-1)/2 + 4 :
  422. (DstType == FmtMSADPCM) ? (align-2)/2 + 7 :
  423. (align * BytesFromFmt(DstType)))};
  424. if((sdatalen%BlockSize) != 0)
  425. throw al::context_error{AL_INVALID_VALUE,
  426. "Data size %u is not a multiple of frame size %u (%u unpack alignment)",
  427. sdatalen, BlockSize, align};
  428. const ALuint blocks{sdatalen / BlockSize};
  429. if(blocks > std::numeric_limits<ALsizei>::max()/align)
  430. throw al::context_error{AL_OUT_OF_MEMORY,
  431. "Buffer size overflow, %d blocks x %d samples per block", blocks, align};
  432. if(blocks > std::numeric_limits<size_t>::max()/BlockSize)
  433. throw al::context_error{AL_OUT_OF_MEMORY,
  434. "Buffer size overflow, %d frames x %d bytes per frame", blocks, BlockSize};
  435. #ifdef ALSOFT_EAX
  436. if(ALBuf->eax_x_ram_mode == EaxStorage::Hardware)
  437. {
  438. ALCdevice &device = *context->mALDevice;
  439. if(!eax_x_ram_check_availability(device, *ALBuf, sdatalen))
  440. throw al::context_error{AL_OUT_OF_MEMORY,
  441. "Out of X-RAM memory (avail: %u, needed: %u)", device.eax_x_ram_free_size,
  442. sdatalen};
  443. }
  444. #endif
  445. decltype(ALBuf->mDataStorage){}.swap(ALBuf->mDataStorage);
  446. ALBuf->mData = {static_cast<std::byte*>(sdata), sdatalen};
  447. #ifdef ALSOFT_EAX
  448. eax_x_ram_clear(*context->mALDevice, *ALBuf);
  449. #endif
  450. ALBuf->mCallback = nullptr;
  451. ALBuf->mUserData = nullptr;
  452. ALBuf->OriginalSize = sdatalen;
  453. ALBuf->Access = 0;
  454. ALBuf->mBlockAlign = (DstType == FmtIMA4 || DstType == FmtMSADPCM) ? align : 1;
  455. ALBuf->mSampleRate = static_cast<ALuint>(freq);
  456. ALBuf->mChannels = DstChannels;
  457. ALBuf->mType = DstType;
  458. ALBuf->mAmbiOrder = ambiorder;
  459. ALBuf->mSampleLen = blocks * align;
  460. ALBuf->mLoopStart = 0;
  461. ALBuf->mLoopEnd = ALBuf->mSampleLen;
  462. #ifdef ALSOFT_EAX
  463. if(ALBuf->eax_x_ram_mode == EaxStorage::Hardware)
  464. eax_x_ram_apply(*context->mALDevice, *ALBuf);
  465. #endif
  466. }
  467. struct DecompResult { FmtChannels channels; FmtType type; };
  468. auto DecomposeUserFormat(ALenum format) noexcept -> std::optional<DecompResult>
  469. {
  470. struct FormatMap {
  471. ALenum format;
  472. DecompResult result;
  473. };
  474. static constexpr std::array UserFmtList{
  475. FormatMap{AL_FORMAT_MONO8, {FmtMono, FmtUByte} },
  476. FormatMap{AL_FORMAT_MONO16, {FmtMono, FmtShort} },
  477. FormatMap{AL_FORMAT_MONO_I32, {FmtMono, FmtInt} },
  478. FormatMap{AL_FORMAT_MONO_FLOAT32, {FmtMono, FmtFloat} },
  479. FormatMap{AL_FORMAT_MONO_DOUBLE_EXT, {FmtMono, FmtDouble} },
  480. FormatMap{AL_FORMAT_MONO_IMA4, {FmtMono, FmtIMA4} },
  481. FormatMap{AL_FORMAT_MONO_MSADPCM_SOFT, {FmtMono, FmtMSADPCM}},
  482. FormatMap{AL_FORMAT_MONO_MULAW, {FmtMono, FmtMulaw} },
  483. FormatMap{AL_FORMAT_MONO_ALAW_EXT, {FmtMono, FmtAlaw} },
  484. FormatMap{AL_FORMAT_STEREO8, {FmtStereo, FmtUByte} },
  485. FormatMap{AL_FORMAT_STEREO16, {FmtStereo, FmtShort} },
  486. FormatMap{AL_FORMAT_STEREO_I32, {FmtStereo, FmtInt} },
  487. FormatMap{AL_FORMAT_STEREO_FLOAT32, {FmtStereo, FmtFloat} },
  488. FormatMap{AL_FORMAT_STEREO_DOUBLE_EXT, {FmtStereo, FmtDouble} },
  489. FormatMap{AL_FORMAT_STEREO_IMA4, {FmtStereo, FmtIMA4} },
  490. FormatMap{AL_FORMAT_STEREO_MSADPCM_SOFT, {FmtStereo, FmtMSADPCM}},
  491. FormatMap{AL_FORMAT_STEREO_MULAW, {FmtStereo, FmtMulaw} },
  492. FormatMap{AL_FORMAT_STEREO_ALAW_EXT, {FmtStereo, FmtAlaw} },
  493. FormatMap{AL_FORMAT_REAR8, {FmtRear, FmtUByte}},
  494. FormatMap{AL_FORMAT_REAR16, {FmtRear, FmtShort}},
  495. FormatMap{AL_FORMAT_REAR32, {FmtRear, FmtFloat}},
  496. FormatMap{AL_FORMAT_REAR_I32, {FmtRear, FmtInt} },
  497. FormatMap{AL_FORMAT_REAR_FLOAT32, {FmtRear, FmtFloat}},
  498. FormatMap{AL_FORMAT_REAR_MULAW, {FmtRear, FmtMulaw}},
  499. FormatMap{AL_FORMAT_QUAD8_LOKI, {FmtQuad, FmtUByte}},
  500. FormatMap{AL_FORMAT_QUAD16_LOKI, {FmtQuad, FmtShort}},
  501. FormatMap{AL_FORMAT_QUAD8, {FmtQuad, FmtUByte}},
  502. FormatMap{AL_FORMAT_QUAD16, {FmtQuad, FmtShort}},
  503. FormatMap{AL_FORMAT_QUAD32, {FmtQuad, FmtFloat}},
  504. FormatMap{AL_FORMAT_QUAD_I32, {FmtQuad, FmtInt} },
  505. FormatMap{AL_FORMAT_QUAD_FLOAT32, {FmtQuad, FmtFloat}},
  506. FormatMap{AL_FORMAT_QUAD_MULAW, {FmtQuad, FmtMulaw}},
  507. FormatMap{AL_FORMAT_51CHN8, {FmtX51, FmtUByte}},
  508. FormatMap{AL_FORMAT_51CHN16, {FmtX51, FmtShort}},
  509. FormatMap{AL_FORMAT_51CHN32, {FmtX51, FmtFloat}},
  510. FormatMap{AL_FORMAT_51CHN_I32, {FmtX51, FmtInt} },
  511. FormatMap{AL_FORMAT_51CHN_FLOAT32, {FmtX51, FmtFloat}},
  512. FormatMap{AL_FORMAT_51CHN_MULAW, {FmtX51, FmtMulaw}},
  513. FormatMap{AL_FORMAT_61CHN8, {FmtX61, FmtUByte}},
  514. FormatMap{AL_FORMAT_61CHN16, {FmtX61, FmtShort}},
  515. FormatMap{AL_FORMAT_61CHN32, {FmtX61, FmtFloat}},
  516. FormatMap{AL_FORMAT_61CHN_I32, {FmtX61, FmtInt} },
  517. FormatMap{AL_FORMAT_61CHN_FLOAT32, {FmtX61, FmtFloat}},
  518. FormatMap{AL_FORMAT_61CHN_MULAW, {FmtX61, FmtMulaw}},
  519. FormatMap{AL_FORMAT_71CHN8, {FmtX71, FmtUByte}},
  520. FormatMap{AL_FORMAT_71CHN16, {FmtX71, FmtShort}},
  521. FormatMap{AL_FORMAT_71CHN32, {FmtX71, FmtFloat}},
  522. FormatMap{AL_FORMAT_71CHN_I32, {FmtX71, FmtInt} },
  523. FormatMap{AL_FORMAT_71CHN_FLOAT32, {FmtX71, FmtFloat}},
  524. FormatMap{AL_FORMAT_71CHN_MULAW, {FmtX71, FmtMulaw}},
  525. FormatMap{AL_FORMAT_BFORMAT2D_8, {FmtBFormat2D, FmtUByte}},
  526. FormatMap{AL_FORMAT_BFORMAT2D_16, {FmtBFormat2D, FmtShort}},
  527. FormatMap{AL_FORMAT_BFORMAT2D_FLOAT32, {FmtBFormat2D, FmtFloat}},
  528. FormatMap{AL_FORMAT_BFORMAT2D_MULAW, {FmtBFormat2D, FmtMulaw}},
  529. FormatMap{AL_FORMAT_BFORMAT3D_8, {FmtBFormat3D, FmtUByte}},
  530. FormatMap{AL_FORMAT_BFORMAT3D_16, {FmtBFormat3D, FmtShort}},
  531. FormatMap{AL_FORMAT_BFORMAT3D_FLOAT32, {FmtBFormat3D, FmtFloat}},
  532. FormatMap{AL_FORMAT_BFORMAT3D_MULAW, {FmtBFormat3D, FmtMulaw}},
  533. FormatMap{AL_FORMAT_UHJ2CHN8_SOFT, {FmtUHJ2, FmtUByte} },
  534. FormatMap{AL_FORMAT_UHJ2CHN16_SOFT, {FmtUHJ2, FmtShort} },
  535. FormatMap{AL_FORMAT_UHJ2CHN_I32_SOFT, {FmtUHJ2, FmtInt} },
  536. FormatMap{AL_FORMAT_UHJ2CHN_FLOAT32_SOFT, {FmtUHJ2, FmtFloat} },
  537. FormatMap{AL_FORMAT_UHJ2CHN_MULAW_SOFT, {FmtUHJ2, FmtMulaw} },
  538. FormatMap{AL_FORMAT_UHJ2CHN_ALAW_SOFT, {FmtUHJ2, FmtAlaw} },
  539. FormatMap{AL_FORMAT_UHJ2CHN_IMA4_SOFT, {FmtUHJ2, FmtIMA4} },
  540. FormatMap{AL_FORMAT_UHJ2CHN_MSADPCM_SOFT, {FmtUHJ2, FmtMSADPCM}},
  541. FormatMap{AL_FORMAT_UHJ3CHN8_SOFT, {FmtUHJ3, FmtUByte}},
  542. FormatMap{AL_FORMAT_UHJ3CHN16_SOFT, {FmtUHJ3, FmtShort}},
  543. FormatMap{AL_FORMAT_UHJ3CHN_I32_SOFT, {FmtUHJ3, FmtInt} },
  544. FormatMap{AL_FORMAT_UHJ3CHN_FLOAT32_SOFT, {FmtUHJ3, FmtFloat}},
  545. FormatMap{AL_FORMAT_UHJ3CHN_MULAW_SOFT, {FmtUHJ3, FmtMulaw}},
  546. FormatMap{AL_FORMAT_UHJ3CHN_ALAW_SOFT, {FmtUHJ3, FmtAlaw} },
  547. FormatMap{AL_FORMAT_UHJ4CHN8_SOFT, {FmtUHJ4, FmtUByte}},
  548. FormatMap{AL_FORMAT_UHJ4CHN16_SOFT, {FmtUHJ4, FmtShort}},
  549. FormatMap{AL_FORMAT_UHJ4CHN_I32_SOFT, {FmtUHJ4, FmtInt} },
  550. FormatMap{AL_FORMAT_UHJ4CHN_FLOAT32_SOFT, {FmtUHJ4, FmtFloat}},
  551. FormatMap{AL_FORMAT_UHJ4CHN_MULAW_SOFT, {FmtUHJ4, FmtMulaw}},
  552. FormatMap{AL_FORMAT_UHJ4CHN_ALAW_SOFT, {FmtUHJ4, FmtAlaw} },
  553. };
  554. auto iter = std::find_if(UserFmtList.cbegin(), UserFmtList.cend(),
  555. [format](const FormatMap &fmt) noexcept { return fmt.format == format; });
  556. if(iter != UserFmtList.cend())
  557. return iter->result;
  558. return std::nullopt;
  559. }
  560. } // namespace
  561. AL_API DECL_FUNC2(void, alGenBuffers, ALsizei,n, ALuint*,buffers)
  562. FORCE_ALIGN void AL_APIENTRY alGenBuffersDirect(ALCcontext *context, ALsizei n, ALuint *buffers) noexcept
  563. try {
  564. if(n < 0)
  565. throw al::context_error{AL_INVALID_VALUE, "Generating %d buffers", n};
  566. if(n <= 0) UNLIKELY return;
  567. ALCdevice *device{context->mALDevice.get()};
  568. std::lock_guard<std::mutex> buflock{device->BufferLock};
  569. const al::span bids{buffers, static_cast<ALuint>(n)};
  570. if(!EnsureBuffers(device, bids.size()))
  571. throw al::context_error{AL_OUT_OF_MEMORY, "Failed to allocate %d buffer%s", n,
  572. (n == 1) ? "" : "s"};
  573. std::generate(bids.begin(), bids.end(), [device]{ return AllocBuffer(device)->id; });
  574. }
  575. catch(al::context_error& e) {
  576. context->setError(e.errorCode(), "%s", e.what());
  577. }
  578. AL_API DECL_FUNC2(void, alDeleteBuffers, ALsizei,n, const ALuint*,buffers)
  579. FORCE_ALIGN void AL_APIENTRY alDeleteBuffersDirect(ALCcontext *context, ALsizei n,
  580. const ALuint *buffers) noexcept
  581. try {
  582. if(n < 0)
  583. throw al::context_error{AL_INVALID_VALUE, "Deleting %d buffers", n};
  584. if(n <= 0) UNLIKELY return;
  585. ALCdevice *device{context->mALDevice.get()};
  586. std::lock_guard<std::mutex> buflock{device->BufferLock};
  587. /* First try to find any buffers that are invalid or in-use. */
  588. auto validate_buffer = [device](const ALuint bid)
  589. {
  590. if(!bid) return;
  591. ALbuffer *ALBuf{LookupBuffer(device, bid)};
  592. if(!ALBuf)
  593. throw al::context_error{AL_INVALID_NAME, "Invalid buffer ID %u", bid};
  594. if(ALBuf->ref.load(std::memory_order_relaxed) != 0)
  595. throw al::context_error{AL_INVALID_OPERATION, "Deleting in-use buffer %u", bid};
  596. };
  597. const al::span bids{buffers, static_cast<ALuint>(n)};
  598. std::for_each(bids.begin(), bids.end(), validate_buffer);
  599. /* All good. Delete non-0 buffer IDs. */
  600. auto delete_buffer = [device](const ALuint bid) -> void
  601. {
  602. if(ALbuffer *buffer{bid ? LookupBuffer(device, bid) : nullptr})
  603. FreeBuffer(device, buffer);
  604. };
  605. std::for_each(bids.begin(), bids.end(), delete_buffer);
  606. }
  607. catch(al::context_error& e) {
  608. context->setError(e.errorCode(), "%s", e.what());
  609. }
  610. AL_API DECL_FUNC1(ALboolean, alIsBuffer, ALuint,buffer)
  611. FORCE_ALIGN ALboolean AL_APIENTRY alIsBufferDirect(ALCcontext *context, ALuint buffer) noexcept
  612. {
  613. ALCdevice *device{context->mALDevice.get()};
  614. std::lock_guard<std::mutex> buflock{device->BufferLock};
  615. if(!buffer || LookupBuffer(device, buffer))
  616. return AL_TRUE;
  617. return AL_FALSE;
  618. }
  619. AL_API void AL_APIENTRY alBufferData(ALuint buffer, ALenum format, const ALvoid *data, ALsizei size, ALsizei freq) noexcept
  620. {
  621. auto context = GetContextRef();
  622. if(!context) UNLIKELY return;
  623. alBufferStorageDirectSOFT(context.get(), buffer, format, data, size, freq, 0);
  624. }
  625. FORCE_ALIGN void AL_APIENTRY alBufferDataDirect(ALCcontext *context, ALuint buffer, ALenum format, const ALvoid *data, ALsizei size, ALsizei freq) noexcept
  626. { alBufferStorageDirectSOFT(context, buffer, format, data, size, freq, 0); }
  627. AL_API DECL_FUNCEXT6(void, alBufferStorage,SOFT, ALuint,buffer, ALenum,format, const ALvoid*,data, ALsizei,size, ALsizei,freq, ALbitfieldSOFT,flags)
  628. FORCE_ALIGN void AL_APIENTRY alBufferStorageDirectSOFT(ALCcontext *context, ALuint buffer,
  629. ALenum format, const ALvoid *data, ALsizei size, ALsizei freq, ALbitfieldSOFT flags) noexcept
  630. try {
  631. ALCdevice *device{context->mALDevice.get()};
  632. std::lock_guard<std::mutex> buflock{device->BufferLock};
  633. ALbuffer *albuf{LookupBuffer(device, buffer)};
  634. if(!albuf)
  635. throw al::context_error{AL_INVALID_NAME, "Invalid buffer ID %u", buffer};
  636. if(size < 0)
  637. throw al::context_error{AL_INVALID_VALUE, "Negative storage size %d", size};
  638. if(freq < 1)
  639. throw al::context_error{AL_INVALID_VALUE, "Invalid sample rate %d", freq};
  640. if((flags&INVALID_STORAGE_MASK) != 0)
  641. throw al::context_error{AL_INVALID_VALUE, "Invalid storage flags 0x%x",
  642. flags&INVALID_STORAGE_MASK};
  643. if((flags&AL_MAP_PERSISTENT_BIT_SOFT) && !(flags&MAP_READ_WRITE_FLAGS))
  644. throw al::context_error{AL_INVALID_VALUE,
  645. "Declaring persistently mapped storage without read or write access"};
  646. auto usrfmt = DecomposeUserFormat(format);
  647. if(!usrfmt)
  648. throw al::context_error{AL_INVALID_ENUM, "Invalid format 0x%04x", format};
  649. LoadData(context, albuf, freq, static_cast<ALuint>(size), usrfmt->channels, usrfmt->type,
  650. static_cast<const std::byte*>(data), flags);
  651. }
  652. catch(al::context_error& e) {
  653. context->setError(e.errorCode(), "%s", e.what());
  654. }
  655. FORCE_ALIGN DECL_FUNC5(void, alBufferDataStatic, ALuint,buffer, ALenum,format, ALvoid*,data, ALsizei,size, ALsizei,freq)
  656. FORCE_ALIGN void AL_APIENTRY alBufferDataStaticDirect(ALCcontext *context, const ALuint buffer,
  657. ALenum format, ALvoid *data, ALsizei size, ALsizei freq) noexcept
  658. try {
  659. ALCdevice *device{context->mALDevice.get()};
  660. std::lock_guard<std::mutex> buflock{device->BufferLock};
  661. ALbuffer *albuf{LookupBuffer(device, buffer)};
  662. if(!albuf)
  663. throw al::context_error{AL_INVALID_NAME, "Invalid buffer ID %u", buffer};
  664. if(size < 0)
  665. throw al::context_error{AL_INVALID_VALUE, "Negative storage size %d", size};
  666. if(freq < 1)
  667. throw al::context_error{AL_INVALID_VALUE, "Invalid sample rate %d", freq};
  668. auto usrfmt = DecomposeUserFormat(format);
  669. if(!usrfmt)
  670. throw al::context_error{AL_INVALID_ENUM, "Invalid format 0x%04x", format};
  671. PrepareUserPtr(context, albuf, freq, usrfmt->channels, usrfmt->type,
  672. static_cast<std::byte*>(data), static_cast<ALuint>(size));
  673. }
  674. catch(al::context_error& e) {
  675. context->setError(e.errorCode(), "%s", e.what());
  676. }
  677. AL_API DECL_FUNCEXT4(void*, alMapBuffer,SOFT, ALuint,buffer, ALsizei,offset, ALsizei,length, ALbitfieldSOFT,access)
  678. FORCE_ALIGN void* AL_APIENTRY alMapBufferDirectSOFT(ALCcontext *context, ALuint buffer,
  679. ALsizei offset, ALsizei length, ALbitfieldSOFT access) noexcept
  680. try {
  681. ALCdevice *device{context->mALDevice.get()};
  682. std::lock_guard<std::mutex> buflock{device->BufferLock};
  683. ALbuffer *albuf{LookupBuffer(device, buffer)};
  684. if(!albuf)
  685. throw al::context_error{AL_INVALID_NAME, "Invalid buffer ID %u", buffer};
  686. if((access&INVALID_MAP_FLAGS) != 0)
  687. throw al::context_error{AL_INVALID_VALUE, "Invalid map flags 0x%x",
  688. access&INVALID_MAP_FLAGS};
  689. if(!(access&MAP_READ_WRITE_FLAGS))
  690. throw al::context_error{AL_INVALID_VALUE, "Mapping buffer %u without read or write access",
  691. buffer};
  692. const ALbitfieldSOFT unavailable{(albuf->Access^access) & access};
  693. if(albuf->ref.load(std::memory_order_relaxed) != 0 && !(access&AL_MAP_PERSISTENT_BIT_SOFT))
  694. throw al::context_error{AL_INVALID_OPERATION,
  695. "Mapping in-use buffer %u without persistent mapping", buffer};
  696. if(albuf->MappedAccess != 0)
  697. throw al::context_error{AL_INVALID_OPERATION, "Mapping already-mapped buffer %u", buffer};
  698. if((unavailable&AL_MAP_READ_BIT_SOFT))
  699. throw al::context_error{AL_INVALID_VALUE,
  700. "Mapping buffer %u for reading without read access", buffer};
  701. if((unavailable&AL_MAP_WRITE_BIT_SOFT))
  702. throw al::context_error{AL_INVALID_VALUE,
  703. "Mapping buffer %u for writing without write access", buffer};
  704. if((unavailable&AL_MAP_PERSISTENT_BIT_SOFT))
  705. throw al::context_error{AL_INVALID_VALUE,
  706. "Mapping buffer %u persistently without persistent access", buffer};
  707. if(offset < 0 || length <= 0 || static_cast<ALuint>(offset) >= albuf->OriginalSize
  708. || static_cast<ALuint>(length) > albuf->OriginalSize - static_cast<ALuint>(offset))
  709. throw al::context_error{AL_INVALID_VALUE, "Mapping invalid range %d+%d for buffer %u",
  710. offset, length, buffer};
  711. void *retval{albuf->mData.data() + offset};
  712. albuf->MappedAccess = access;
  713. albuf->MappedOffset = offset;
  714. albuf->MappedSize = length;
  715. return retval;
  716. }
  717. catch(al::context_error& e) {
  718. context->setError(e.errorCode(), "%s", e.what());
  719. return nullptr;
  720. }
  721. AL_API DECL_FUNCEXT1(void, alUnmapBuffer,SOFT, ALuint,buffer)
  722. FORCE_ALIGN void AL_APIENTRY alUnmapBufferDirectSOFT(ALCcontext *context, ALuint buffer) noexcept
  723. try {
  724. ALCdevice *device{context->mALDevice.get()};
  725. std::lock_guard<std::mutex> buflock{device->BufferLock};
  726. ALbuffer *albuf{LookupBuffer(device, buffer)};
  727. if(!albuf)
  728. throw al::context_error{AL_INVALID_NAME, "Invalid buffer ID %u", buffer};
  729. if(albuf->MappedAccess == 0)
  730. throw al::context_error{AL_INVALID_OPERATION, "Unmapping unmapped buffer %u", buffer};
  731. albuf->MappedAccess = 0;
  732. albuf->MappedOffset = 0;
  733. albuf->MappedSize = 0;
  734. }
  735. catch(al::context_error& e) {
  736. context->setError(e.errorCode(), "%s", e.what());
  737. }
  738. AL_API DECL_FUNCEXT3(void, alFlushMappedBuffer,SOFT, ALuint,buffer, ALsizei,offset, ALsizei,length)
  739. FORCE_ALIGN void AL_APIENTRY alFlushMappedBufferDirectSOFT(ALCcontext *context, ALuint buffer,
  740. ALsizei offset, ALsizei length) noexcept
  741. try {
  742. ALCdevice *device{context->mALDevice.get()};
  743. std::lock_guard<std::mutex> buflock{device->BufferLock};
  744. ALbuffer *albuf{LookupBuffer(device, buffer)};
  745. if(!albuf)
  746. throw al::context_error{AL_INVALID_NAME, "Invalid buffer ID %u", buffer};
  747. if(!(albuf->MappedAccess&AL_MAP_WRITE_BIT_SOFT))
  748. throw al::context_error{AL_INVALID_OPERATION,
  749. "Flushing buffer %u while not mapped for writing", buffer};
  750. if(offset < albuf->MappedOffset || length <= 0
  751. || offset >= albuf->MappedOffset+albuf->MappedSize
  752. || length > albuf->MappedOffset+albuf->MappedSize-offset)
  753. throw al::context_error{AL_INVALID_VALUE, "Flushing invalid range %d+%d on buffer %u",
  754. offset, length, buffer};
  755. /* FIXME: Need to use some method of double-buffering for the mixer and app
  756. * to hold separate memory, which can be safely transferred asynchronously.
  757. * Currently we just say the app shouldn't write where OpenAL's reading,
  758. * and hope for the best...
  759. */
  760. std::atomic_thread_fence(std::memory_order_seq_cst);
  761. }
  762. catch(al::context_error& e) {
  763. context->setError(e.errorCode(), "%s", e.what());
  764. }
  765. AL_API DECL_FUNCEXT5(void, alBufferSubData,SOFT, ALuint,buffer, ALenum,format, const ALvoid*,data, ALsizei,offset, ALsizei,length)
  766. FORCE_ALIGN void AL_APIENTRY alBufferSubDataDirectSOFT(ALCcontext *context, ALuint buffer,
  767. ALenum format, const ALvoid *data, ALsizei offset, ALsizei length) noexcept
  768. try {
  769. ALCdevice *device{context->mALDevice.get()};
  770. std::lock_guard<std::mutex> buflock{device->BufferLock};
  771. ALbuffer *albuf{LookupBuffer(device, buffer)};
  772. if(!albuf)
  773. throw al::context_error{AL_INVALID_NAME, "Invalid buffer ID %u", buffer};
  774. auto usrfmt = DecomposeUserFormat(format);
  775. if(!usrfmt)
  776. throw al::context_error{AL_INVALID_ENUM, "Invalid format 0x%04x", format};
  777. const ALuint unpack_align{albuf->UnpackAlign};
  778. const ALuint align{SanitizeAlignment(usrfmt->type, unpack_align)};
  779. if(align < 1)
  780. throw al::context_error{AL_INVALID_VALUE, "Invalid unpack alignment %u", unpack_align};
  781. if(usrfmt->channels != albuf->mChannels || usrfmt->type != albuf->mType)
  782. throw al::context_error{AL_INVALID_ENUM, "Unpacking data with mismatched format"};
  783. if(align != albuf->mBlockAlign)
  784. throw al::context_error{AL_INVALID_VALUE,
  785. "Unpacking data with alignment %u does not match original alignment %u", align,
  786. albuf->mBlockAlign};
  787. if(albuf->isBFormat() && albuf->UnpackAmbiOrder != albuf->mAmbiOrder)
  788. throw al::context_error{AL_INVALID_VALUE,
  789. "Unpacking data with mismatched ambisonic order"};
  790. if(albuf->MappedAccess != 0)
  791. throw al::context_error{AL_INVALID_OPERATION, "Unpacking data into mapped buffer %u",
  792. buffer};
  793. const ALuint num_chans{albuf->channelsFromFmt()};
  794. const ALuint byte_align{
  795. (albuf->mType == FmtIMA4) ? ((align-1)/2 + 4) * num_chans :
  796. (albuf->mType == FmtMSADPCM) ? ((align-2)/2 + 7) * num_chans :
  797. (align * albuf->bytesFromFmt() * num_chans)};
  798. if(offset < 0 || length < 0 || static_cast<ALuint>(offset) > albuf->OriginalSize
  799. || static_cast<ALuint>(length) > albuf->OriginalSize-static_cast<ALuint>(offset))
  800. throw al::context_error{AL_INVALID_VALUE, "Invalid data sub-range %d+%d on buffer %u",
  801. offset, length, buffer};
  802. if((static_cast<ALuint>(offset)%byte_align) != 0)
  803. throw al::context_error{AL_INVALID_VALUE,
  804. "Sub-range offset %d is not a multiple of frame size %d (%d unpack alignment)",
  805. offset, byte_align, align};
  806. if((static_cast<ALuint>(length)%byte_align) != 0)
  807. throw al::context_error{AL_INVALID_VALUE,
  808. "Sub-range length %d is not a multiple of frame size %d (%d unpack alignment)",
  809. length, byte_align, align};
  810. std::memcpy(albuf->mData.data()+offset, data, static_cast<ALuint>(length));
  811. }
  812. catch(al::context_error& e) {
  813. context->setError(e.errorCode(), "%s", e.what());
  814. }
  815. AL_API DECL_FUNC3(void, alBufferf, ALuint,buffer, ALenum,param, ALfloat,value)
  816. FORCE_ALIGN void AL_APIENTRY alBufferfDirect(ALCcontext *context, ALuint buffer, ALenum param,
  817. ALfloat value [[maybe_unused]]) noexcept
  818. try {
  819. ALCdevice *device{context->mALDevice.get()};
  820. std::lock_guard<std::mutex> buflock{device->BufferLock};
  821. if(LookupBuffer(device, buffer) == nullptr)
  822. throw al::context_error{AL_INVALID_NAME, "Invalid buffer ID %u", buffer};
  823. switch(param)
  824. {
  825. }
  826. throw al::context_error{AL_INVALID_ENUM, "Invalid buffer float property 0x%04x", param};
  827. }
  828. catch(al::context_error& e) {
  829. context->setError(e.errorCode(), "%s", e.what());
  830. }
  831. AL_API DECL_FUNC5(void, alBuffer3f, ALuint,buffer, ALenum,param, ALfloat,value1, ALfloat,value2, ALfloat,value3)
  832. FORCE_ALIGN void AL_APIENTRY alBuffer3fDirect(ALCcontext *context, ALuint buffer, ALenum param,
  833. ALfloat value1 [[maybe_unused]], ALfloat value2 [[maybe_unused]],
  834. ALfloat value3 [[maybe_unused]]) noexcept
  835. try {
  836. ALCdevice *device{context->mALDevice.get()};
  837. std::lock_guard<std::mutex> buflock{device->BufferLock};
  838. if(LookupBuffer(device, buffer) == nullptr)
  839. throw al::context_error{AL_INVALID_NAME, "Invalid buffer ID %u", buffer};
  840. switch(param)
  841. {
  842. }
  843. throw al::context_error{AL_INVALID_ENUM, "Invalid buffer 3-float property 0x%04x", param};
  844. }
  845. catch(al::context_error& e) {
  846. context->setError(e.errorCode(), "%s", e.what());
  847. }
  848. AL_API DECL_FUNC3(void, alBufferfv, ALuint,buffer, ALenum,param, const ALfloat*,values)
  849. FORCE_ALIGN void AL_APIENTRY alBufferfvDirect(ALCcontext *context, ALuint buffer, ALenum param,
  850. const ALfloat *values) noexcept
  851. try {
  852. ALCdevice *device{context->mALDevice.get()};
  853. std::lock_guard<std::mutex> buflock{device->BufferLock};
  854. if(LookupBuffer(device, buffer) == nullptr)
  855. throw al::context_error{AL_INVALID_NAME, "Invalid buffer ID %u", buffer};
  856. if(!values)
  857. throw al::context_error{AL_INVALID_VALUE, "NULL pointer"};
  858. switch(param)
  859. {
  860. }
  861. throw al::context_error{AL_INVALID_ENUM, "Invalid buffer float-vector property 0x%04x", param};
  862. }
  863. catch(al::context_error& e) {
  864. context->setError(e.errorCode(), "%s", e.what());
  865. }
  866. AL_API DECL_FUNC3(void, alBufferi, ALuint,buffer, ALenum,param, ALint,value)
  867. FORCE_ALIGN void AL_APIENTRY alBufferiDirect(ALCcontext *context, ALuint buffer, ALenum param,
  868. ALint value) noexcept
  869. try {
  870. ALCdevice *device{context->mALDevice.get()};
  871. std::lock_guard<std::mutex> buflock{device->BufferLock};
  872. ALbuffer *albuf{LookupBuffer(device, buffer)};
  873. if(!albuf)
  874. throw al::context_error{AL_INVALID_NAME, "Invalid buffer ID %u", buffer};
  875. switch(param)
  876. {
  877. case AL_UNPACK_BLOCK_ALIGNMENT_SOFT:
  878. if(value < 0)
  879. throw al::context_error{AL_INVALID_VALUE, "Invalid unpack block alignment %d", value};
  880. albuf->UnpackAlign = static_cast<ALuint>(value);
  881. return;
  882. case AL_PACK_BLOCK_ALIGNMENT_SOFT:
  883. if(value < 0)
  884. throw al::context_error{AL_INVALID_VALUE, "Invalid pack block alignment %d", value};
  885. albuf->PackAlign = static_cast<ALuint>(value);
  886. return;
  887. case AL_AMBISONIC_LAYOUT_SOFT:
  888. if(albuf->ref.load(std::memory_order_relaxed) != 0)
  889. throw al::context_error{AL_INVALID_OPERATION,
  890. "Modifying in-use buffer %u's ambisonic layout", buffer};
  891. if(const auto layout = AmbiLayoutFromEnum(value))
  892. {
  893. albuf->mAmbiLayout = layout.value();
  894. return;
  895. }
  896. throw al::context_error{AL_INVALID_VALUE, "Invalid unpack ambisonic layout %04x", value};
  897. case AL_AMBISONIC_SCALING_SOFT:
  898. if(albuf->ref.load(std::memory_order_relaxed) != 0)
  899. throw al::context_error{AL_INVALID_OPERATION,
  900. "Modifying in-use buffer %u's ambisonic scaling", buffer};
  901. if(const auto scaling = AmbiScalingFromEnum(value))
  902. {
  903. albuf->mAmbiScaling = scaling.value();
  904. return;
  905. }
  906. throw al::context_error{AL_INVALID_VALUE, "Invalid unpack ambisonic scaling %04x", value};
  907. case AL_UNPACK_AMBISONIC_ORDER_SOFT:
  908. if(value < 1 || value > 14)
  909. throw al::context_error{AL_INVALID_VALUE, "Invalid unpack ambisonic order %d", value};
  910. albuf->UnpackAmbiOrder = static_cast<ALuint>(value);
  911. return;
  912. }
  913. throw al::context_error{AL_INVALID_ENUM, "Invalid buffer integer property 0x%04x", param};
  914. }
  915. catch(al::context_error& e) {
  916. context->setError(e.errorCode(), "%s", e.what());
  917. }
  918. AL_API DECL_FUNC5(void, alBuffer3i, ALuint,buffer, ALenum,param, ALint,value1, ALint,value2, ALint,value3)
  919. FORCE_ALIGN void AL_APIENTRY alBuffer3iDirect(ALCcontext *context, ALuint buffer, ALenum param,
  920. ALint value1 [[maybe_unused]], ALint value2 [[maybe_unused]], ALint value3 [[maybe_unused]]) noexcept
  921. try {
  922. ALCdevice *device{context->mALDevice.get()};
  923. std::lock_guard<std::mutex> buflock{device->BufferLock};
  924. if(LookupBuffer(device, buffer) == nullptr)
  925. throw al::context_error{AL_INVALID_NAME, "Invalid buffer ID %u", buffer};
  926. switch(param)
  927. {
  928. }
  929. throw al::context_error{AL_INVALID_ENUM, "Invalid buffer 3-integer property 0x%04x", param};
  930. }
  931. catch(al::context_error& e) {
  932. context->setError(e.errorCode(), "%s", e.what());
  933. }
  934. AL_API DECL_FUNC3(void, alBufferiv, ALuint,buffer, ALenum,param, const ALint*,values)
  935. FORCE_ALIGN void AL_APIENTRY alBufferivDirect(ALCcontext *context, ALuint buffer, ALenum param,
  936. const ALint *values) noexcept
  937. try {
  938. if(!values)
  939. throw al::context_error{AL_INVALID_VALUE, "NULL pointer"};
  940. switch(param)
  941. {
  942. case AL_UNPACK_BLOCK_ALIGNMENT_SOFT:
  943. case AL_PACK_BLOCK_ALIGNMENT_SOFT:
  944. case AL_AMBISONIC_LAYOUT_SOFT:
  945. case AL_AMBISONIC_SCALING_SOFT:
  946. case AL_UNPACK_AMBISONIC_ORDER_SOFT:
  947. alBufferiDirect(context, buffer, param, *values);
  948. return;
  949. }
  950. ALCdevice *device{context->mALDevice.get()};
  951. std::lock_guard<std::mutex> buflock{device->BufferLock};
  952. ALbuffer *albuf{LookupBuffer(device, buffer)};
  953. if(!albuf)
  954. throw al::context_error{AL_INVALID_NAME, "Invalid buffer ID %u", buffer};
  955. switch(param)
  956. {
  957. case AL_LOOP_POINTS_SOFT:
  958. auto vals = al::span{values, 2_uz};
  959. if(albuf->ref.load(std::memory_order_relaxed) != 0)
  960. throw al::context_error{AL_INVALID_OPERATION,
  961. "Modifying in-use buffer %u's loop points", buffer};
  962. if(vals[0] < 0 || vals[0] >= vals[1] || static_cast<ALuint>(vals[1]) > albuf->mSampleLen)
  963. throw al::context_error{AL_INVALID_VALUE,
  964. "Invalid loop point range %d -> %d on buffer %u", vals[0], vals[1], buffer};
  965. albuf->mLoopStart = static_cast<ALuint>(vals[0]);
  966. albuf->mLoopEnd = static_cast<ALuint>(vals[1]);
  967. return;
  968. }
  969. throw al::context_error{AL_INVALID_ENUM, "Invalid buffer integer-vector property 0x%04x",
  970. param};
  971. }
  972. catch(al::context_error& e) {
  973. context->setError(e.errorCode(), "%s", e.what());
  974. }
  975. AL_API DECL_FUNC3(void, alGetBufferf, ALuint,buffer, ALenum,param, ALfloat*,value)
  976. FORCE_ALIGN void AL_APIENTRY alGetBufferfDirect(ALCcontext *context, ALuint buffer, ALenum param,
  977. ALfloat *value) noexcept
  978. try {
  979. ALCdevice *device{context->mALDevice.get()};
  980. std::lock_guard<std::mutex> buflock{device->BufferLock};
  981. ALbuffer *albuf{LookupBuffer(device, buffer)};
  982. if(!albuf)
  983. throw al::context_error{AL_INVALID_NAME, "Invalid buffer ID %u", buffer};
  984. if(!value)
  985. throw al::context_error{AL_INVALID_VALUE, "NULL pointer"};
  986. switch(param)
  987. {
  988. case AL_SEC_LENGTH_SOFT:
  989. *value = (albuf->mSampleRate < 1) ? 0.0f :
  990. (static_cast<float>(albuf->mSampleLen) / static_cast<float>(albuf->mSampleRate));
  991. return;
  992. }
  993. throw al::context_error{AL_INVALID_ENUM, "Invalid buffer float property 0x%04x", param};
  994. }
  995. catch(al::context_error& e) {
  996. context->setError(e.errorCode(), "%s", e.what());
  997. }
  998. AL_API DECL_FUNC5(void, alGetBuffer3f, ALuint,buffer, ALenum,param, ALfloat*,value1, ALfloat*,value2, ALfloat*,value3)
  999. FORCE_ALIGN void AL_APIENTRY alGetBuffer3fDirect(ALCcontext *context, ALuint buffer, ALenum param,
  1000. ALfloat *value1, ALfloat *value2, ALfloat *value3) noexcept
  1001. try {
  1002. ALCdevice *device{context->mALDevice.get()};
  1003. std::lock_guard<std::mutex> buflock{device->BufferLock};
  1004. if(LookupBuffer(device, buffer) == nullptr)
  1005. throw al::context_error{AL_INVALID_NAME, "Invalid buffer ID %u", buffer};
  1006. if(!value1 || !value2 || !value3)
  1007. throw al::context_error{AL_INVALID_VALUE, "NULL pointer"};
  1008. switch(param)
  1009. {
  1010. }
  1011. throw al::context_error{AL_INVALID_ENUM, "Invalid buffer 3-float property 0x%04x", param};
  1012. }
  1013. catch(al::context_error& e) {
  1014. context->setError(e.errorCode(), "%s", e.what());
  1015. }
  1016. AL_API DECL_FUNC3(void, alGetBufferfv, ALuint,buffer, ALenum,param, ALfloat*,values)
  1017. FORCE_ALIGN void AL_APIENTRY alGetBufferfvDirect(ALCcontext *context, ALuint buffer, ALenum param,
  1018. ALfloat *values) noexcept
  1019. try {
  1020. switch(param)
  1021. {
  1022. case AL_SEC_LENGTH_SOFT:
  1023. alGetBufferfDirect(context, buffer, param, values);
  1024. return;
  1025. }
  1026. ALCdevice *device{context->mALDevice.get()};
  1027. std::lock_guard<std::mutex> buflock{device->BufferLock};
  1028. if(LookupBuffer(device, buffer) == nullptr)
  1029. throw al::context_error{AL_INVALID_NAME, "Invalid buffer ID %u", buffer};
  1030. if(!values)
  1031. throw al::context_error{AL_INVALID_VALUE, "NULL pointer"};
  1032. switch(param)
  1033. {
  1034. }
  1035. throw al::context_error{AL_INVALID_ENUM, "Invalid buffer float-vector property 0x%04x", param};
  1036. }
  1037. catch(al::context_error& e) {
  1038. context->setError(e.errorCode(), "%s", e.what());
  1039. }
  1040. AL_API DECL_FUNC3(void, alGetBufferi, ALuint,buffer, ALenum,param, ALint*,value)
  1041. FORCE_ALIGN void AL_APIENTRY alGetBufferiDirect(ALCcontext *context, ALuint buffer, ALenum param,
  1042. ALint *value) noexcept
  1043. try {
  1044. ALCdevice *device{context->mALDevice.get()};
  1045. std::lock_guard<std::mutex> buflock{device->BufferLock};
  1046. ALbuffer *albuf{LookupBuffer(device, buffer)};
  1047. if(!albuf)
  1048. throw al::context_error{AL_INVALID_NAME, "Invalid buffer ID %u", buffer};
  1049. if(!value)
  1050. throw al::context_error{AL_INVALID_VALUE, "NULL pointer"};
  1051. switch(param)
  1052. {
  1053. case AL_FREQUENCY:
  1054. *value = static_cast<ALint>(albuf->mSampleRate);
  1055. return;
  1056. case AL_BITS:
  1057. *value = (albuf->mType == FmtIMA4 || albuf->mType == FmtMSADPCM) ? 4
  1058. : static_cast<ALint>(albuf->bytesFromFmt() * 8);
  1059. return;
  1060. case AL_CHANNELS:
  1061. *value = static_cast<ALint>(albuf->channelsFromFmt());
  1062. return;
  1063. case AL_SIZE:
  1064. *value = albuf->mCallback ? 0 : static_cast<ALint>(albuf->mData.size());
  1065. return;
  1066. case AL_BYTE_LENGTH_SOFT:
  1067. *value = static_cast<ALint>(albuf->mSampleLen / albuf->mBlockAlign
  1068. * albuf->blockSizeFromFmt());
  1069. return;
  1070. case AL_SAMPLE_LENGTH_SOFT:
  1071. *value = static_cast<ALint>(albuf->mSampleLen);
  1072. return;
  1073. case AL_UNPACK_BLOCK_ALIGNMENT_SOFT:
  1074. *value = static_cast<ALint>(albuf->UnpackAlign);
  1075. return;
  1076. case AL_PACK_BLOCK_ALIGNMENT_SOFT:
  1077. *value = static_cast<ALint>(albuf->PackAlign);
  1078. return;
  1079. case AL_AMBISONIC_LAYOUT_SOFT:
  1080. *value = EnumFromAmbiLayout(albuf->mAmbiLayout);
  1081. return;
  1082. case AL_AMBISONIC_SCALING_SOFT:
  1083. *value = EnumFromAmbiScaling(albuf->mAmbiScaling);
  1084. return;
  1085. case AL_UNPACK_AMBISONIC_ORDER_SOFT:
  1086. *value = static_cast<int>(albuf->UnpackAmbiOrder);
  1087. return;
  1088. }
  1089. throw al::context_error{AL_INVALID_ENUM, "Invalid buffer integer property 0x%04x", param};
  1090. }
  1091. catch(al::context_error& e) {
  1092. context->setError(e.errorCode(), "%s", e.what());
  1093. }
  1094. AL_API DECL_FUNC5(void, alGetBuffer3i, ALuint,buffer, ALenum,param, ALint*,value1, ALint*,value2, ALint*,value3)
  1095. FORCE_ALIGN void AL_APIENTRY alGetBuffer3iDirect(ALCcontext *context, ALuint buffer, ALenum param,
  1096. ALint *value1, ALint *value2, ALint *value3) noexcept
  1097. try {
  1098. ALCdevice *device{context->mALDevice.get()};
  1099. std::lock_guard<std::mutex> buflock{device->BufferLock};
  1100. if(LookupBuffer(device, buffer) == nullptr)
  1101. throw al::context_error{AL_INVALID_NAME, "Invalid buffer ID %u", buffer};
  1102. if(!value1 || !value2 || !value3)
  1103. throw al::context_error{AL_INVALID_VALUE, "NULL pointer"};
  1104. switch(param)
  1105. {
  1106. }
  1107. throw al::context_error{AL_INVALID_ENUM, "Invalid buffer 3-integer property 0x%04x", param};
  1108. }
  1109. catch(al::context_error& e) {
  1110. context->setError(e.errorCode(), "%s", e.what());
  1111. }
  1112. AL_API DECL_FUNC3(void, alGetBufferiv, ALuint,buffer, ALenum,param, ALint*,values)
  1113. FORCE_ALIGN void AL_APIENTRY alGetBufferivDirect(ALCcontext *context, ALuint buffer, ALenum param,
  1114. ALint *values) noexcept
  1115. try {
  1116. switch(param)
  1117. {
  1118. case AL_FREQUENCY:
  1119. case AL_BITS:
  1120. case AL_CHANNELS:
  1121. case AL_SIZE:
  1122. case AL_INTERNAL_FORMAT_SOFT:
  1123. case AL_BYTE_LENGTH_SOFT:
  1124. case AL_SAMPLE_LENGTH_SOFT:
  1125. case AL_UNPACK_BLOCK_ALIGNMENT_SOFT:
  1126. case AL_PACK_BLOCK_ALIGNMENT_SOFT:
  1127. case AL_AMBISONIC_LAYOUT_SOFT:
  1128. case AL_AMBISONIC_SCALING_SOFT:
  1129. case AL_UNPACK_AMBISONIC_ORDER_SOFT:
  1130. alGetBufferiDirect(context, buffer, param, values);
  1131. return;
  1132. }
  1133. ALCdevice *device{context->mALDevice.get()};
  1134. std::lock_guard<std::mutex> buflock{device->BufferLock};
  1135. ALbuffer *albuf{LookupBuffer(device, buffer)};
  1136. if(!albuf)
  1137. throw al::context_error{AL_INVALID_NAME, "Invalid buffer ID %u", buffer};
  1138. if(!values)
  1139. throw al::context_error{AL_INVALID_VALUE, "NULL pointer"};
  1140. switch(param)
  1141. {
  1142. case AL_LOOP_POINTS_SOFT:
  1143. auto vals = al::span{values, 2_uz};
  1144. vals[0] = static_cast<ALint>(albuf->mLoopStart);
  1145. vals[1] = static_cast<ALint>(albuf->mLoopEnd);
  1146. return;
  1147. }
  1148. throw al::context_error{AL_INVALID_ENUM, "Invalid buffer integer-vector property 0x%04x",
  1149. param};
  1150. }
  1151. catch(al::context_error& e) {
  1152. context->setError(e.errorCode(), "%s", e.what());
  1153. }
  1154. AL_API DECL_FUNCEXT5(void, alBufferCallback,SOFT, ALuint,buffer, ALenum,format, ALsizei,freq, ALBUFFERCALLBACKTYPESOFT,callback, ALvoid*,userptr)
  1155. FORCE_ALIGN void AL_APIENTRY alBufferCallbackDirectSOFT(ALCcontext *context, ALuint buffer,
  1156. ALenum format, ALsizei freq, ALBUFFERCALLBACKTYPESOFT callback, ALvoid *userptr) noexcept
  1157. try {
  1158. ALCdevice *device{context->mALDevice.get()};
  1159. std::lock_guard<std::mutex> buflock{device->BufferLock};
  1160. ALbuffer *albuf{LookupBuffer(device, buffer)};
  1161. if(!albuf)
  1162. throw al::context_error{AL_INVALID_NAME, "Invalid buffer ID %u", buffer};
  1163. if(freq < 1)
  1164. throw al::context_error{AL_INVALID_VALUE, "Invalid sample rate %d", freq};
  1165. if(callback == nullptr)
  1166. throw al::context_error{AL_INVALID_VALUE, "NULL callback"};
  1167. auto usrfmt = DecomposeUserFormat(format);
  1168. if(!usrfmt)
  1169. throw al::context_error{AL_INVALID_ENUM, "Invalid format 0x%04x", format};
  1170. PrepareCallback(context, albuf, freq, usrfmt->channels, usrfmt->type, callback, userptr);
  1171. }
  1172. catch(al::context_error& e) {
  1173. context->setError(e.errorCode(), "%s", e.what());
  1174. }
  1175. AL_API DECL_FUNCEXT3(void, alGetBufferPtr,SOFT, ALuint,buffer, ALenum,param, ALvoid**,value)
  1176. FORCE_ALIGN void AL_APIENTRY alGetBufferPtrDirectSOFT(ALCcontext *context, ALuint buffer,
  1177. ALenum param, ALvoid **value) noexcept
  1178. try {
  1179. ALCdevice *device{context->mALDevice.get()};
  1180. std::lock_guard<std::mutex> buflock{device->BufferLock};
  1181. ALbuffer *albuf{LookupBuffer(device, buffer)};
  1182. if(!albuf)
  1183. throw al::context_error{AL_INVALID_NAME, "Invalid buffer ID %u", buffer};
  1184. if(!value)
  1185. throw al::context_error{AL_INVALID_VALUE, "NULL pointer"};
  1186. switch(param)
  1187. {
  1188. case AL_BUFFER_CALLBACK_FUNCTION_SOFT:
  1189. *value = reinterpret_cast<void*>(albuf->mCallback);
  1190. return;
  1191. case AL_BUFFER_CALLBACK_USER_PARAM_SOFT:
  1192. *value = albuf->mUserData;
  1193. return;
  1194. }
  1195. throw al::context_error{AL_INVALID_ENUM, "Invalid buffer pointer property 0x%04x", param};
  1196. }
  1197. catch(al::context_error& e) {
  1198. context->setError(e.errorCode(), "%s", e.what());
  1199. }
  1200. AL_API DECL_FUNCEXT5(void, alGetBuffer3Ptr,SOFT, ALuint,buffer, ALenum,param, ALvoid**,value1, ALvoid**,value2, ALvoid**,value3)
  1201. FORCE_ALIGN void AL_APIENTRY alGetBuffer3PtrDirectSOFT(ALCcontext *context, ALuint buffer,
  1202. ALenum param, ALvoid **value1, ALvoid **value2, ALvoid **value3) noexcept
  1203. try {
  1204. ALCdevice *device{context->mALDevice.get()};
  1205. std::lock_guard<std::mutex> buflock{device->BufferLock};
  1206. if(LookupBuffer(device, buffer) == nullptr)
  1207. throw al::context_error{AL_INVALID_NAME, "Invalid buffer ID %u", buffer};
  1208. if(!value1 || !value2 || !value3)
  1209. throw al::context_error{AL_INVALID_VALUE, "NULL pointer"};
  1210. switch(param)
  1211. {
  1212. }
  1213. throw al::context_error{AL_INVALID_ENUM, "Invalid buffer 3-pointer property 0x%04x", param};
  1214. }
  1215. catch(al::context_error& e) {
  1216. context->setError(e.errorCode(), "%s", e.what());
  1217. }
  1218. AL_API DECL_FUNCEXT3(void, alGetBufferPtrv,SOFT, ALuint,buffer, ALenum,param, ALvoid**,values)
  1219. FORCE_ALIGN void AL_APIENTRY alGetBufferPtrvDirectSOFT(ALCcontext *context, ALuint buffer,
  1220. ALenum param, ALvoid **values) noexcept
  1221. try {
  1222. switch(param)
  1223. {
  1224. case AL_BUFFER_CALLBACK_FUNCTION_SOFT:
  1225. case AL_BUFFER_CALLBACK_USER_PARAM_SOFT:
  1226. alGetBufferPtrDirectSOFT(context, buffer, param, values);
  1227. return;
  1228. }
  1229. ALCdevice *device{context->mALDevice.get()};
  1230. std::lock_guard<std::mutex> buflock{device->BufferLock};
  1231. if(LookupBuffer(device, buffer) == nullptr)
  1232. throw al::context_error{AL_INVALID_NAME, "Invalid buffer ID %u", buffer};
  1233. if(!values)
  1234. throw al::context_error{AL_INVALID_VALUE, "NULL pointer"};
  1235. switch(param)
  1236. {
  1237. }
  1238. throw al::context_error{AL_INVALID_ENUM, "Invalid buffer pointer-vector property 0x%04x",
  1239. param};
  1240. }
  1241. catch(al::context_error& e) {
  1242. context->setError(e.errorCode(), "%s", e.what());
  1243. }
  1244. AL_API void AL_APIENTRY alBufferSamplesSOFT(ALuint /*buffer*/, ALuint /*samplerate*/,
  1245. ALenum /*internalformat*/, ALsizei /*samples*/, ALenum /*channels*/, ALenum /*type*/,
  1246. const ALvoid* /*data*/) noexcept
  1247. {
  1248. ContextRef context{GetContextRef()};
  1249. if(!context) UNLIKELY return;
  1250. context->setError(AL_INVALID_OPERATION, "alBufferSamplesSOFT not supported");
  1251. }
  1252. AL_API void AL_APIENTRY alBufferSubSamplesSOFT(ALuint /*buffer*/, ALsizei /*offset*/,
  1253. ALsizei /*samples*/, ALenum /*channels*/, ALenum /*type*/, const ALvoid* /*data*/) noexcept
  1254. {
  1255. ContextRef context{GetContextRef()};
  1256. if(!context) UNLIKELY return;
  1257. context->setError(AL_INVALID_OPERATION, "alBufferSubSamplesSOFT not supported");
  1258. }
  1259. AL_API void AL_APIENTRY alGetBufferSamplesSOFT(ALuint /*buffer*/, ALsizei /*offset*/,
  1260. ALsizei /*samples*/, ALenum /*channels*/, ALenum /*type*/, ALvoid* /*data*/) noexcept
  1261. {
  1262. ContextRef context{GetContextRef()};
  1263. if(!context) UNLIKELY return;
  1264. context->setError(AL_INVALID_OPERATION, "alGetBufferSamplesSOFT not supported");
  1265. }
  1266. AL_API ALboolean AL_APIENTRY alIsBufferFormatSupportedSOFT(ALenum /*format*/) noexcept
  1267. {
  1268. ContextRef context{GetContextRef()};
  1269. if(!context) UNLIKELY return AL_FALSE;
  1270. context->setError(AL_INVALID_OPERATION, "alIsBufferFormatSupportedSOFT not supported");
  1271. return AL_FALSE;
  1272. }
  1273. void ALbuffer::SetName(ALCcontext *context, ALuint id, std::string_view name)
  1274. {
  1275. ALCdevice *device{context->mALDevice.get()};
  1276. std::lock_guard<std::mutex> buflock{device->BufferLock};
  1277. auto buffer = LookupBuffer(device, id);
  1278. if(!buffer)
  1279. throw al::context_error{AL_INVALID_NAME, "Invalid buffer ID %u", id};
  1280. device->mBufferNames.insert_or_assign(id, name);
  1281. }
  1282. BufferSubList::~BufferSubList()
  1283. {
  1284. if(!Buffers)
  1285. return;
  1286. uint64_t usemask{~FreeMask};
  1287. while(usemask)
  1288. {
  1289. const int idx{al::countr_zero(usemask)};
  1290. std::destroy_at(al::to_address(Buffers->begin() + idx));
  1291. usemask &= ~(1_u64 << idx);
  1292. }
  1293. FreeMask = ~usemask;
  1294. SubListAllocator{}.deallocate(Buffers, 1);
  1295. Buffers = nullptr;
  1296. }
  1297. #ifdef ALSOFT_EAX
  1298. FORCE_ALIGN DECL_FUNC3(ALboolean, EAXSetBufferMode, ALsizei,n, const ALuint*,buffers, ALint,value)
  1299. FORCE_ALIGN ALboolean AL_APIENTRY EAXSetBufferModeDirect(ALCcontext *context, ALsizei n,
  1300. const ALuint *buffers, ALint value) noexcept
  1301. try {
  1302. if(!eax_g_is_enabled)
  1303. throw al::context_error{AL_INVALID_OPERATION, "EAX not enabled"};
  1304. const auto storage = EaxStorageFromEnum(value);
  1305. if(!storage)
  1306. throw al::context_error{AL_INVALID_ENUM, "Unsupported X-RAM mode 0x%x", value};
  1307. if(n == 0)
  1308. return AL_TRUE;
  1309. if(n < 0)
  1310. throw al::context_error{AL_INVALID_VALUE, "Buffer count %d out of range", n};
  1311. if(!buffers)
  1312. throw al::context_error{AL_INVALID_VALUE, "Null AL buffers"};
  1313. auto device = context->mALDevice.get();
  1314. std::lock_guard<std::mutex> devlock{device->BufferLock};
  1315. /* Special-case setting a single buffer, to avoid extraneous allocations. */
  1316. if(n == 1)
  1317. {
  1318. const auto bufid = *buffers;
  1319. if(bufid == AL_NONE)
  1320. return AL_TRUE;
  1321. const auto buffer = LookupBuffer(device, bufid);
  1322. if(!buffer)
  1323. throw al::context_error{AL_INVALID_NAME, "Invalid buffer ID %u", bufid};
  1324. /* TODO: Is the store location allowed to change for in-use buffers, or
  1325. * only when not set/queued on a source?
  1326. */
  1327. if(*storage == EaxStorage::Hardware)
  1328. {
  1329. if(!buffer->eax_x_ram_is_hardware
  1330. && buffer->OriginalSize > device->eax_x_ram_free_size)
  1331. throw al::context_error{AL_OUT_OF_MEMORY,
  1332. "Out of X-RAM memory (need: %u, avail: %u)", buffer->OriginalSize,
  1333. device->eax_x_ram_free_size};
  1334. eax_x_ram_apply(*device, *buffer);
  1335. }
  1336. else
  1337. eax_x_ram_clear(*device, *buffer);
  1338. buffer->eax_x_ram_mode = *storage;
  1339. return AL_TRUE;
  1340. }
  1341. /* Validate the buffers. */
  1342. std::unordered_set<ALbuffer*> buflist;
  1343. for(const ALuint bufid : al::span{buffers, static_cast<ALuint>(n)})
  1344. {
  1345. if(bufid == AL_NONE)
  1346. continue;
  1347. const auto buffer = LookupBuffer(device, bufid);
  1348. if(!buffer)
  1349. throw al::context_error{AL_INVALID_NAME, "Invalid buffer ID %u", bufid};
  1350. /* TODO: Is the store location allowed to change for in-use buffers, or
  1351. * only when not set/queued on a source?
  1352. */
  1353. buflist.emplace(buffer);
  1354. }
  1355. if(*storage == EaxStorage::Hardware)
  1356. {
  1357. size_t total_needed{0};
  1358. for(ALbuffer *buffer : buflist)
  1359. {
  1360. if(!buffer->eax_x_ram_is_hardware)
  1361. {
  1362. if(std::numeric_limits<size_t>::max() - buffer->OriginalSize < total_needed)
  1363. throw al::context_error{AL_OUT_OF_MEMORY, "Size overflow (%u + %zu)",
  1364. buffer->OriginalSize, total_needed};
  1365. total_needed += buffer->OriginalSize;
  1366. }
  1367. }
  1368. if(total_needed > device->eax_x_ram_free_size)
  1369. throw al::context_error{AL_OUT_OF_MEMORY, "Out of X-RAM memory (need: %zu, avail: %u)",
  1370. total_needed, device->eax_x_ram_free_size};
  1371. }
  1372. /* Update the mode. */
  1373. for(ALbuffer *buffer : buflist)
  1374. {
  1375. if(*storage == EaxStorage::Hardware)
  1376. eax_x_ram_apply(*device, *buffer);
  1377. else
  1378. eax_x_ram_clear(*device, *buffer);
  1379. buffer->eax_x_ram_mode = *storage;
  1380. }
  1381. return AL_TRUE;
  1382. }
  1383. catch(al::context_error& e) {
  1384. context->setError(e.errorCode(), "[EAXSetBufferMode] %s", e.what());
  1385. return AL_FALSE;
  1386. }
  1387. FORCE_ALIGN DECL_FUNC2(ALenum, EAXGetBufferMode, ALuint,buffer, ALint*,pReserved)
  1388. FORCE_ALIGN ALenum AL_APIENTRY EAXGetBufferModeDirect(ALCcontext *context, ALuint buffer,
  1389. ALint *pReserved) noexcept
  1390. try {
  1391. if(!eax_g_is_enabled)
  1392. throw al::context_error{AL_INVALID_OPERATION, "EAX not enabled."};
  1393. if(pReserved)
  1394. throw al::context_error{AL_INVALID_VALUE, "Non-null reserved parameter"};
  1395. auto device = context->mALDevice.get();
  1396. std::lock_guard<std::mutex> devlock{device->BufferLock};
  1397. const auto al_buffer = LookupBuffer(device, buffer);
  1398. if(!al_buffer)
  1399. throw al::context_error{AL_INVALID_NAME, "Invalid buffer ID %u", buffer};
  1400. return EnumFromEaxStorage(al_buffer->eax_x_ram_mode);
  1401. }
  1402. catch(al::context_error& e) {
  1403. context->setError(e.errorCode(), "[EAXGetBufferMode] %s", e.what());
  1404. return AL_NONE;
  1405. }
  1406. #endif // ALSOFT_EAX