buffer.cpp 63 KB

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