Ensure the EAX functions are suitably aligned on 32-bit
[openal-soft.git] / al / buffer.cpp
blob6436ea3c68ac544f0c0ccf3d4ed4b7832f8e6247
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.
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.
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
21 #include "config.h"
23 #include "buffer.h"
25 #include <algorithm>
26 #include <array>
27 #include <atomic>
28 #include <cassert>
29 #include <cstdint>
30 #include <cstdlib>
31 #include <cstring>
32 #include <iterator>
33 #include <limits>
34 #include <memory>
35 #include <mutex>
36 #include <new>
37 #include <numeric>
38 #include <stdexcept>
39 #include <utility>
41 #include "AL/al.h"
42 #include "AL/alc.h"
43 #include "AL/alext.h"
45 #include "albit.h"
46 #include "albyte.h"
47 #include "alc/context.h"
48 #include "alc/device.h"
49 #include "alc/inprogext.h"
50 #include "almalloc.h"
51 #include "alnumeric.h"
52 #include "aloptional.h"
53 #include "atomic.h"
54 #include "core/except.h"
55 #include "core/logging.h"
56 #include "core/voice.h"
57 #include "opthelpers.h"
59 #ifdef ALSOFT_EAX
60 #include "eax_globals.h"
61 #include "eax_x_ram.h"
62 #endif // ALSOFT_EAX
65 namespace {
67 constexpr int MaxAdpcmChannels{2};
69 /* IMA ADPCM Stepsize table */
70 constexpr int IMAStep_size[89] = {
71 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 19,
72 21, 23, 25, 28, 31, 34, 37, 41, 45, 50, 55,
73 60, 66, 73, 80, 88, 97, 107, 118, 130, 143, 157,
74 173, 190, 209, 230, 253, 279, 307, 337, 371, 408, 449,
75 494, 544, 598, 658, 724, 796, 876, 963, 1060, 1166, 1282,
76 1411, 1552, 1707, 1878, 2066, 2272, 2499, 2749, 3024, 3327, 3660,
77 4026, 4428, 4871, 5358, 5894, 6484, 7132, 7845, 8630, 9493,10442,
78 11487,12635,13899,15289,16818,18500,20350,22358,24633,27086,29794,
79 32767
82 /* IMA4 ADPCM Codeword decode table */
83 constexpr int IMA4Codeword[16] = {
84 1, 3, 5, 7, 9, 11, 13, 15,
85 -1,-3,-5,-7,-9,-11,-13,-15,
88 /* IMA4 ADPCM Step index adjust decode table */
89 constexpr int IMA4Index_adjust[16] = {
90 -1,-1,-1,-1, 2, 4, 6, 8,
91 -1,-1,-1,-1, 2, 4, 6, 8
95 /* MSADPCM Adaption table */
96 constexpr int MSADPCMAdaption[16] = {
97 230, 230, 230, 230, 307, 409, 512, 614,
98 768, 614, 512, 409, 307, 230, 230, 230
101 /* MSADPCM Adaption Coefficient tables */
102 constexpr int MSADPCMAdaptionCoeff[7][2] = {
103 { 256, 0 },
104 { 512, -256 },
105 { 0, 0 },
106 { 192, 64 },
107 { 240, 0 },
108 { 460, -208 },
109 { 392, -232 }
113 void DecodeIMA4Block(int16_t *dst, const al::byte *src, size_t numchans, size_t align)
115 int sample[MaxAdpcmChannels]{};
116 int index[MaxAdpcmChannels]{};
117 ALuint code[MaxAdpcmChannels]{};
119 for(size_t c{0};c < numchans;c++)
121 sample[c] = al::to_integer<int>(src[0]) | (al::to_integer<int>(src[1])<<8);
122 sample[c] = (sample[c]^0x8000) - 32768;
123 src += 2;
124 index[c] = al::to_integer<int>(src[0]) | (al::to_integer<int>(src[1])<<8);
125 index[c] = clampi((index[c]^0x8000) - 32768, 0, 88);
126 src += 2;
128 *(dst++) = static_cast<int16_t>(sample[c]);
131 for(size_t i{1};i < align;i++)
133 if((i&7) == 1)
135 for(size_t c{0};c < numchans;c++)
137 code[c] = al::to_integer<ALuint>(src[0]) | (al::to_integer<ALuint>(src[1])<< 8) |
138 (al::to_integer<ALuint>(src[2])<<16) | (al::to_integer<ALuint>(src[3])<<24);
139 src += 4;
143 for(size_t c{0};c < numchans;c++)
145 const ALuint nibble{code[c]&0xf};
146 code[c] >>= 4;
148 sample[c] += IMA4Codeword[nibble] * IMAStep_size[index[c]] / 8;
149 sample[c] = clampi(sample[c], -32768, 32767);
151 index[c] += IMA4Index_adjust[nibble];
152 index[c] = clampi(index[c], 0, 88);
154 *(dst++) = static_cast<int16_t>(sample[c]);
159 void DecodeMSADPCMBlock(int16_t *dst, const al::byte *src, size_t numchans, size_t align)
161 uint8_t blockpred[MaxAdpcmChannels]{};
162 int delta[MaxAdpcmChannels]{};
163 int16_t samples[MaxAdpcmChannels][2]{};
165 for(size_t c{0};c < numchans;c++)
167 blockpred[c] = std::min<ALubyte>(al::to_integer<ALubyte>(src[0]), 6);
168 ++src;
170 for(size_t c{0};c < numchans;c++)
172 delta[c] = al::to_integer<int>(src[0]) | (al::to_integer<int>(src[1])<<8);
173 delta[c] = (delta[c]^0x8000) - 32768;
174 src += 2;
176 for(size_t c{0};c < numchans;c++)
178 samples[c][0] = static_cast<ALshort>(al::to_integer<int>(src[0]) |
179 (al::to_integer<int>(src[1])<<8));
180 src += 2;
182 for(size_t c{0};c < numchans;c++)
184 samples[c][1] = static_cast<ALshort>(al::to_integer<int>(src[0]) |
185 (al::to_integer<int>(src[1])<<8));
186 src += 2;
189 /* Second sample is written first. */
190 for(size_t c{0};c < numchans;c++)
191 *(dst++) = samples[c][1];
192 for(size_t c{0};c < numchans;c++)
193 *(dst++) = samples[c][0];
195 int num{0};
196 for(size_t i{2};i < align;i++)
198 for(size_t c{0};c < numchans;c++)
200 /* Read the nibble (first is in the upper bits). */
201 al::byte nibble;
202 if(!(num++ & 1))
203 nibble = *src >> 4;
204 else
205 nibble = *(src++) & 0x0f;
207 int pred{(samples[c][0]*MSADPCMAdaptionCoeff[blockpred[c]][0] +
208 samples[c][1]*MSADPCMAdaptionCoeff[blockpred[c]][1]) / 256};
209 pred += (al::to_integer<int>(nibble^0x08) - 0x08) * delta[c];
210 pred = clampi(pred, -32768, 32767);
212 samples[c][1] = samples[c][0];
213 samples[c][0] = static_cast<int16_t>(pred);
215 delta[c] = (MSADPCMAdaption[al::to_integer<ALubyte>(nibble)] * delta[c]) / 256;
216 delta[c] = maxi(16, delta[c]);
218 *(dst++) = static_cast<int16_t>(pred);
223 void Convert_int16_ima4(int16_t *dst, const al::byte *src, size_t numchans, size_t len,
224 size_t align)
226 assert(numchans <= MaxAdpcmChannels);
227 const size_t byte_align{((align-1)/2 + 4) * numchans};
229 len /= align;
230 while(len--)
232 DecodeIMA4Block(dst, src, numchans, align);
233 src += byte_align;
234 dst += align*numchans;
238 void Convert_int16_msadpcm(int16_t *dst, const al::byte *src, size_t numchans, size_t len,
239 size_t align)
241 assert(numchans <= MaxAdpcmChannels);
242 const size_t byte_align{((align-2)/2 + 7) * numchans};
244 len /= align;
245 while(len--)
247 DecodeMSADPCMBlock(dst, src, numchans, align);
248 src += byte_align;
249 dst += align*numchans;
254 ALuint BytesFromUserFmt(UserFmtType type) noexcept
256 switch(type)
258 case UserFmtUByte: return sizeof(uint8_t);
259 case UserFmtShort: return sizeof(int16_t);
260 case UserFmtFloat: return sizeof(float);
261 case UserFmtDouble: return sizeof(double);
262 case UserFmtMulaw: return sizeof(uint8_t);
263 case UserFmtAlaw: return sizeof(uint8_t);
264 case UserFmtIMA4: break; /* not handled here */
265 case UserFmtMSADPCM: break; /* not handled here */
267 return 0;
269 ALuint ChannelsFromUserFmt(UserFmtChannels chans, ALuint ambiorder) noexcept
271 switch(chans)
273 case UserFmtMono: return 1;
274 case UserFmtStereo: return 2;
275 case UserFmtRear: return 2;
276 case UserFmtQuad: return 4;
277 case UserFmtX51: return 6;
278 case UserFmtX61: return 7;
279 case UserFmtX71: return 8;
280 case UserFmtBFormat2D: return (ambiorder*2) + 1;
281 case UserFmtBFormat3D: return (ambiorder+1) * (ambiorder+1);
282 case UserFmtUHJ2: return 2;
283 case UserFmtUHJ3: return 3;
284 case UserFmtUHJ4: return 4;
286 return 0;
289 al::optional<AmbiLayout> AmbiLayoutFromEnum(ALenum layout)
291 switch(layout)
293 case AL_FUMA_SOFT: return al::make_optional(AmbiLayout::FuMa);
294 case AL_ACN_SOFT: return al::make_optional(AmbiLayout::ACN);
296 return al::nullopt;
298 ALenum EnumFromAmbiLayout(AmbiLayout layout)
300 switch(layout)
302 case AmbiLayout::FuMa: return AL_FUMA_SOFT;
303 case AmbiLayout::ACN: return AL_ACN_SOFT;
305 throw std::runtime_error{"Invalid AmbiLayout: "+std::to_string(int(layout))};
308 al::optional<AmbiScaling> AmbiScalingFromEnum(ALenum scale)
310 switch(scale)
312 case AL_FUMA_SOFT: return al::make_optional(AmbiScaling::FuMa);
313 case AL_SN3D_SOFT: return al::make_optional(AmbiScaling::SN3D);
314 case AL_N3D_SOFT: return al::make_optional(AmbiScaling::N3D);
316 return al::nullopt;
318 ALenum EnumFromAmbiScaling(AmbiScaling scale)
320 switch(scale)
322 case AmbiScaling::FuMa: return AL_FUMA_SOFT;
323 case AmbiScaling::SN3D: return AL_SN3D_SOFT;
324 case AmbiScaling::N3D: return AL_N3D_SOFT;
325 case AmbiScaling::UHJ: break;
327 throw std::runtime_error{"Invalid AmbiScaling: "+std::to_string(int(scale))};
330 al::optional<FmtChannels> FmtFromUserFmt(UserFmtChannels chans)
332 switch(chans)
334 case UserFmtMono: return al::make_optional(FmtMono);
335 case UserFmtStereo: return al::make_optional(FmtStereo);
336 case UserFmtRear: return al::make_optional(FmtRear);
337 case UserFmtQuad: return al::make_optional(FmtQuad);
338 case UserFmtX51: return al::make_optional(FmtX51);
339 case UserFmtX61: return al::make_optional(FmtX61);
340 case UserFmtX71: return al::make_optional(FmtX71);
341 case UserFmtBFormat2D: return al::make_optional(FmtBFormat2D);
342 case UserFmtBFormat3D: return al::make_optional(FmtBFormat3D);
343 case UserFmtUHJ2: return al::make_optional(FmtUHJ2);
344 case UserFmtUHJ3: return al::make_optional(FmtUHJ3);
345 case UserFmtUHJ4: return al::make_optional(FmtUHJ4);
347 return al::nullopt;
349 al::optional<FmtType> FmtFromUserFmt(UserFmtType type)
351 switch(type)
353 case UserFmtUByte: return al::make_optional(FmtUByte);
354 case UserFmtShort: return al::make_optional(FmtShort);
355 case UserFmtFloat: return al::make_optional(FmtFloat);
356 case UserFmtDouble: return al::make_optional(FmtDouble);
357 case UserFmtMulaw: return al::make_optional(FmtMulaw);
358 case UserFmtAlaw: return al::make_optional(FmtAlaw);
359 /* ADPCM not handled here. */
360 case UserFmtIMA4: break;
361 case UserFmtMSADPCM: break;
363 return al::nullopt;
367 #ifdef ALSOFT_EAX
368 bool eax_x_ram_check_availability(const ALCdevice &device, const ALbuffer &buffer,
369 const ALuint newsize) noexcept
371 ALuint freemem{device.eax_x_ram_free_size};
372 /* If the buffer is currently in "hardware", add its memory to the free
373 * pool since it'll be "replaced".
375 if(buffer.eax_x_ram_is_hardware)
376 freemem += buffer.OriginalSize;
377 return freemem >= newsize;
380 void eax_x_ram_apply(ALCdevice &device, ALbuffer &buffer) noexcept
382 if(buffer.eax_x_ram_is_hardware)
383 return;
385 if(device.eax_x_ram_free_size >= buffer.OriginalSize)
387 device.eax_x_ram_free_size -= buffer.OriginalSize;
388 buffer.eax_x_ram_is_hardware = true;
392 void eax_x_ram_clear(ALCdevice& al_device, ALbuffer& al_buffer)
394 if(al_buffer.eax_x_ram_is_hardware)
395 al_device.eax_x_ram_free_size += al_buffer.OriginalSize;
396 al_buffer.eax_x_ram_is_hardware = false;
398 #endif // ALSOFT_EAX
401 constexpr ALbitfieldSOFT INVALID_STORAGE_MASK{~unsigned(AL_MAP_READ_BIT_SOFT |
402 AL_MAP_WRITE_BIT_SOFT | AL_MAP_PERSISTENT_BIT_SOFT | AL_PRESERVE_DATA_BIT_SOFT)};
403 constexpr ALbitfieldSOFT MAP_READ_WRITE_FLAGS{AL_MAP_READ_BIT_SOFT | AL_MAP_WRITE_BIT_SOFT};
404 constexpr ALbitfieldSOFT INVALID_MAP_FLAGS{~unsigned(AL_MAP_READ_BIT_SOFT | AL_MAP_WRITE_BIT_SOFT |
405 AL_MAP_PERSISTENT_BIT_SOFT)};
408 bool EnsureBuffers(ALCdevice *device, size_t needed)
410 size_t count{std::accumulate(device->BufferList.cbegin(), device->BufferList.cend(), size_t{0},
411 [](size_t cur, const BufferSubList &sublist) noexcept -> size_t
412 { return cur + static_cast<ALuint>(al::popcount(sublist.FreeMask)); })};
414 while(needed > count)
416 if UNLIKELY(device->BufferList.size() >= 1<<25)
417 return false;
419 device->BufferList.emplace_back();
420 auto sublist = device->BufferList.end() - 1;
421 sublist->FreeMask = ~0_u64;
422 sublist->Buffers = static_cast<ALbuffer*>(al_calloc(alignof(ALbuffer), sizeof(ALbuffer)*64));
423 if UNLIKELY(!sublist->Buffers)
425 device->BufferList.pop_back();
426 return false;
428 count += 64;
430 return true;
433 ALbuffer *AllocBuffer(ALCdevice *device)
435 auto sublist = std::find_if(device->BufferList.begin(), device->BufferList.end(),
436 [](const BufferSubList &entry) noexcept -> bool
437 { return entry.FreeMask != 0; });
438 auto lidx = static_cast<ALuint>(std::distance(device->BufferList.begin(), sublist));
439 auto slidx = static_cast<ALuint>(al::countr_zero(sublist->FreeMask));
440 ASSUME(slidx < 64);
442 ALbuffer *buffer{al::construct_at(sublist->Buffers + slidx)};
444 /* Add 1 to avoid buffer ID 0. */
445 buffer->id = ((lidx<<6) | slidx) + 1;
447 sublist->FreeMask &= ~(1_u64 << slidx);
449 return buffer;
452 void FreeBuffer(ALCdevice *device, ALbuffer *buffer)
454 #ifdef ALSOFT_EAX
455 eax_x_ram_clear(*device, *buffer);
456 #endif // ALSOFT_EAX
458 const ALuint id{buffer->id - 1};
459 const size_t lidx{id >> 6};
460 const ALuint slidx{id & 0x3f};
462 al::destroy_at(buffer);
464 device->BufferList[lidx].FreeMask |= 1_u64 << slidx;
467 inline ALbuffer *LookupBuffer(ALCdevice *device, ALuint id)
469 const size_t lidx{(id-1) >> 6};
470 const ALuint slidx{(id-1) & 0x3f};
472 if UNLIKELY(lidx >= device->BufferList.size())
473 return nullptr;
474 BufferSubList &sublist = device->BufferList[lidx];
475 if UNLIKELY(sublist.FreeMask & (1_u64 << slidx))
476 return nullptr;
477 return sublist.Buffers + slidx;
481 ALuint SanitizeAlignment(UserFmtType type, ALuint align)
483 if(align == 0)
485 if(type == UserFmtIMA4)
487 /* Here is where things vary:
488 * nVidia and Apple use 64+1 sample frames per block -> block_size=36 bytes per channel
489 * Most PC sound software uses 2040+1 sample frames per block -> block_size=1024 bytes per channel
491 return 65;
493 if(type == UserFmtMSADPCM)
494 return 64;
495 return 1;
498 if(type == UserFmtIMA4)
500 /* IMA4 block alignment must be a multiple of 8, plus 1. */
501 if((align&7) == 1) return static_cast<ALuint>(align);
502 return 0;
504 if(type == UserFmtMSADPCM)
506 /* MSADPCM block alignment must be a multiple of 2. */
507 if((align&1) == 0) return static_cast<ALuint>(align);
508 return 0;
511 return static_cast<ALuint>(align);
515 const ALchar *NameFromUserFmtType(UserFmtType type)
517 switch(type)
519 case UserFmtUByte: return "UInt8";
520 case UserFmtShort: return "Int16";
521 case UserFmtFloat: return "Float32";
522 case UserFmtDouble: return "Float64";
523 case UserFmtMulaw: return "muLaw";
524 case UserFmtAlaw: return "aLaw";
525 case UserFmtIMA4: return "IMA4 ADPCM";
526 case UserFmtMSADPCM: return "MSADPCM";
528 return "<internal type error>";
531 /** Loads the specified data into the buffer, using the specified format. */
532 void LoadData(ALCcontext *context, ALbuffer *ALBuf, ALsizei freq, ALuint size,
533 UserFmtChannels SrcChannels, UserFmtType SrcType, const al::byte *SrcData,
534 ALbitfieldSOFT access)
536 if UNLIKELY(ReadRef(ALBuf->ref) != 0 || ALBuf->MappedAccess != 0)
537 SETERR_RETURN(context, AL_INVALID_OPERATION,, "Modifying storage for in-use buffer %u",
538 ALBuf->id);
540 /* Currently no channel configurations need to be converted. */
541 auto DstChannels = FmtFromUserFmt(SrcChannels);
542 if UNLIKELY(!DstChannels)
543 SETERR_RETURN(context, AL_INVALID_ENUM, , "Invalid format");
545 /* IMA4 and MSADPCM convert to 16-bit short.
547 * TODO: Currently we can only map samples when they're not converted. To
548 * allow it would need some kind of double-buffering to hold onto a copy of
549 * the original data.
551 if((access&MAP_READ_WRITE_FLAGS))
553 if UNLIKELY(SrcType == UserFmtIMA4 || SrcType == UserFmtMSADPCM)
554 SETERR_RETURN(context, AL_INVALID_VALUE,, "%s samples cannot be mapped",
555 NameFromUserFmtType(SrcType));
557 auto DstType = (SrcType == UserFmtIMA4 || SrcType == UserFmtMSADPCM)
558 ? al::make_optional(FmtShort) : FmtFromUserFmt(SrcType);
559 if UNLIKELY(!DstType)
560 SETERR_RETURN(context, AL_INVALID_ENUM, , "Invalid format");
562 const ALuint unpackalign{ALBuf->UnpackAlign};
563 const ALuint align{SanitizeAlignment(SrcType, unpackalign)};
564 if UNLIKELY(align < 1)
565 SETERR_RETURN(context, AL_INVALID_VALUE,, "Invalid unpack alignment %u for %s samples",
566 unpackalign, NameFromUserFmtType(SrcType));
568 const ALuint ambiorder{IsBFormat(*DstChannels) ? ALBuf->UnpackAmbiOrder :
569 (IsUHJ(*DstChannels) ? 1 : 0)};
571 if((access&AL_PRESERVE_DATA_BIT_SOFT))
573 /* Can only preserve data with the same format and alignment. */
574 if UNLIKELY(ALBuf->mChannels != *DstChannels || ALBuf->OriginalType != SrcType)
575 SETERR_RETURN(context, AL_INVALID_VALUE,, "Preserving data of mismatched format");
576 if UNLIKELY(ALBuf->OriginalAlign != align)
577 SETERR_RETURN(context, AL_INVALID_VALUE,, "Preserving data of mismatched alignment");
578 if(ALBuf->mAmbiOrder != ambiorder)
579 SETERR_RETURN(context, AL_INVALID_VALUE,, "Preserving data of mismatched order");
582 /* Convert the input/source size in bytes to sample frames using the unpack
583 * block alignment.
585 const ALuint SrcByteAlign{ChannelsFromUserFmt(SrcChannels, ambiorder) *
586 ((SrcType == UserFmtIMA4) ? (align-1)/2 + 4 :
587 (SrcType == UserFmtMSADPCM) ? (align-2)/2 + 7 :
588 (align * BytesFromUserFmt(SrcType)))};
589 if UNLIKELY((size%SrcByteAlign) != 0)
590 SETERR_RETURN(context, AL_INVALID_VALUE,,
591 "Data size %d is not a multiple of frame size %d (%d unpack alignment)",
592 size, SrcByteAlign, align);
594 if UNLIKELY(size/SrcByteAlign > std::numeric_limits<ALsizei>::max()/align)
595 SETERR_RETURN(context, AL_OUT_OF_MEMORY,,
596 "Buffer size overflow, %d blocks x %d samples per block", size/SrcByteAlign, align);
597 const ALuint frames{size / SrcByteAlign * align};
599 /* Convert the sample frames to the number of bytes needed for internal
600 * storage.
602 ALuint NumChannels{ChannelsFromFmt(*DstChannels, ambiorder)};
603 ALuint FrameSize{NumChannels * BytesFromFmt(*DstType)};
604 if UNLIKELY(frames > std::numeric_limits<size_t>::max()/FrameSize)
605 SETERR_RETURN(context, AL_OUT_OF_MEMORY,,
606 "Buffer size overflow, %d frames x %d bytes per frame", frames, FrameSize);
607 size_t newsize{static_cast<size_t>(frames) * FrameSize};
609 #ifdef ALSOFT_EAX
610 if(ALBuf->eax_x_ram_mode == AL_STORAGE_HARDWARE)
612 ALCdevice &device = *context->mALDevice;
613 if(!eax_x_ram_check_availability(device, *ALBuf, size))
614 SETERR_RETURN(context, AL_OUT_OF_MEMORY,,
615 "Out of X-RAM memory (avail: %u, needed: %u)", device.eax_x_ram_free_size, size);
617 #endif
619 /* Round up to the next 16-byte multiple. This could reallocate only when
620 * increasing or the new size is less than half the current, but then the
621 * buffer's AL_SIZE would not be very reliable for accounting buffer memory
622 * usage, and reporting the real size could cause problems for apps that
623 * use AL_SIZE to try to get the buffer's play length.
625 newsize = RoundUp(newsize, 16);
626 if(newsize != ALBuf->mData.size())
628 auto newdata = al::vector<al::byte,16>(newsize, al::byte{});
629 if((access&AL_PRESERVE_DATA_BIT_SOFT))
631 const size_t tocopy{minz(newdata.size(), ALBuf->mData.size())};
632 std::copy_n(ALBuf->mData.begin(), tocopy, newdata.begin());
634 newdata.swap(ALBuf->mData);
637 if(SrcType == UserFmtIMA4)
639 assert(*DstType == FmtShort);
640 if(SrcData != nullptr && !ALBuf->mData.empty())
641 Convert_int16_ima4(reinterpret_cast<int16_t*>(ALBuf->mData.data()), SrcData,
642 NumChannels, frames, align);
643 ALBuf->OriginalAlign = align;
645 else if(SrcType == UserFmtMSADPCM)
647 assert(*DstType == FmtShort);
648 if(SrcData != nullptr && !ALBuf->mData.empty())
649 Convert_int16_msadpcm(reinterpret_cast<int16_t*>(ALBuf->mData.data()), SrcData,
650 NumChannels, frames, align);
651 ALBuf->OriginalAlign = align;
653 else
655 assert(DstType.has_value());
656 if(SrcData != nullptr && !ALBuf->mData.empty())
657 std::copy_n(SrcData, frames*FrameSize, ALBuf->mData.begin());
658 ALBuf->OriginalAlign = 1;
660 ALBuf->OriginalSize = size;
661 ALBuf->OriginalType = SrcType;
663 ALBuf->Access = access;
665 ALBuf->mSampleRate = static_cast<ALuint>(freq);
666 ALBuf->mChannels = *DstChannels;
667 ALBuf->mType = *DstType;
668 ALBuf->mAmbiOrder = ambiorder;
670 ALBuf->mCallback = nullptr;
671 ALBuf->mUserData = nullptr;
673 ALBuf->mSampleLen = frames;
674 ALBuf->mLoopStart = 0;
675 ALBuf->mLoopEnd = ALBuf->mSampleLen;
677 #ifdef ALSOFT_EAX
678 if(eax_g_is_enabled && ALBuf->eax_x_ram_mode != AL_STORAGE_ACCESSIBLE)
679 eax_x_ram_apply(*context->mALDevice, *ALBuf);
680 #endif
683 /** Prepares the buffer to use the specified callback, using the specified format. */
684 void PrepareCallback(ALCcontext *context, ALbuffer *ALBuf, ALsizei freq,
685 UserFmtChannels SrcChannels, UserFmtType SrcType, ALBUFFERCALLBACKTYPESOFT callback,
686 void *userptr)
688 if UNLIKELY(ReadRef(ALBuf->ref) != 0 || ALBuf->MappedAccess != 0)
689 SETERR_RETURN(context, AL_INVALID_OPERATION,, "Modifying callback for in-use buffer %u",
690 ALBuf->id);
692 /* Currently no channel configurations need to be converted. */
693 auto DstChannels = FmtFromUserFmt(SrcChannels);
694 if UNLIKELY(!DstChannels)
695 SETERR_RETURN(context, AL_INVALID_ENUM,, "Invalid format");
697 /* IMA4 and MSADPCM convert to 16-bit short. Not supported with callbacks. */
698 auto DstType = FmtFromUserFmt(SrcType);
699 if UNLIKELY(!DstType)
700 SETERR_RETURN(context, AL_INVALID_ENUM,, "Unsupported callback format");
702 const ALuint ambiorder{IsBFormat(*DstChannels) ? ALBuf->UnpackAmbiOrder :
703 (IsUHJ(*DstChannels) ? 1 : 0)};
705 static constexpr uint line_size{BufferLineSize + MaxPostVoiceLoad};
706 al::vector<al::byte,16>(FrameSizeFromFmt(*DstChannels, *DstType, ambiorder) *
707 size_t{line_size}).swap(ALBuf->mData);
709 #ifdef ALSOFT_EAX
710 eax_x_ram_clear(*context->mALDevice, *ALBuf);
711 #endif
713 ALBuf->mCallback = callback;
714 ALBuf->mUserData = userptr;
716 ALBuf->OriginalType = SrcType;
717 ALBuf->OriginalSize = 0;
718 ALBuf->OriginalAlign = 1;
719 ALBuf->Access = 0;
721 ALBuf->mSampleRate = static_cast<ALuint>(freq);
722 ALBuf->mChannels = *DstChannels;
723 ALBuf->mType = *DstType;
724 ALBuf->mAmbiOrder = ambiorder;
726 ALBuf->mSampleLen = 0;
727 ALBuf->mLoopStart = 0;
728 ALBuf->mLoopEnd = ALBuf->mSampleLen;
732 struct DecompResult { UserFmtChannels channels; UserFmtType type; };
733 al::optional<DecompResult> DecomposeUserFormat(ALenum format)
735 struct FormatMap {
736 ALenum format;
737 UserFmtChannels channels;
738 UserFmtType type;
740 static const std::array<FormatMap,55> UserFmtList{{
741 { AL_FORMAT_MONO8, UserFmtMono, UserFmtUByte },
742 { AL_FORMAT_MONO16, UserFmtMono, UserFmtShort },
743 { AL_FORMAT_MONO_FLOAT32, UserFmtMono, UserFmtFloat },
744 { AL_FORMAT_MONO_DOUBLE_EXT, UserFmtMono, UserFmtDouble },
745 { AL_FORMAT_MONO_IMA4, UserFmtMono, UserFmtIMA4 },
746 { AL_FORMAT_MONO_MSADPCM_SOFT, UserFmtMono, UserFmtMSADPCM },
747 { AL_FORMAT_MONO_MULAW, UserFmtMono, UserFmtMulaw },
748 { AL_FORMAT_MONO_ALAW_EXT, UserFmtMono, UserFmtAlaw },
750 { AL_FORMAT_STEREO8, UserFmtStereo, UserFmtUByte },
751 { AL_FORMAT_STEREO16, UserFmtStereo, UserFmtShort },
752 { AL_FORMAT_STEREO_FLOAT32, UserFmtStereo, UserFmtFloat },
753 { AL_FORMAT_STEREO_DOUBLE_EXT, UserFmtStereo, UserFmtDouble },
754 { AL_FORMAT_STEREO_IMA4, UserFmtStereo, UserFmtIMA4 },
755 { AL_FORMAT_STEREO_MSADPCM_SOFT, UserFmtStereo, UserFmtMSADPCM },
756 { AL_FORMAT_STEREO_MULAW, UserFmtStereo, UserFmtMulaw },
757 { AL_FORMAT_STEREO_ALAW_EXT, UserFmtStereo, UserFmtAlaw },
759 { AL_FORMAT_REAR8, UserFmtRear, UserFmtUByte },
760 { AL_FORMAT_REAR16, UserFmtRear, UserFmtShort },
761 { AL_FORMAT_REAR32, UserFmtRear, UserFmtFloat },
762 { AL_FORMAT_REAR_MULAW, UserFmtRear, UserFmtMulaw },
764 { AL_FORMAT_QUAD8_LOKI, UserFmtQuad, UserFmtUByte },
765 { AL_FORMAT_QUAD16_LOKI, UserFmtQuad, UserFmtShort },
767 { AL_FORMAT_QUAD8, UserFmtQuad, UserFmtUByte },
768 { AL_FORMAT_QUAD16, UserFmtQuad, UserFmtShort },
769 { AL_FORMAT_QUAD32, UserFmtQuad, UserFmtFloat },
770 { AL_FORMAT_QUAD_MULAW, UserFmtQuad, UserFmtMulaw },
772 { AL_FORMAT_51CHN8, UserFmtX51, UserFmtUByte },
773 { AL_FORMAT_51CHN16, UserFmtX51, UserFmtShort },
774 { AL_FORMAT_51CHN32, UserFmtX51, UserFmtFloat },
775 { AL_FORMAT_51CHN_MULAW, UserFmtX51, UserFmtMulaw },
777 { AL_FORMAT_61CHN8, UserFmtX61, UserFmtUByte },
778 { AL_FORMAT_61CHN16, UserFmtX61, UserFmtShort },
779 { AL_FORMAT_61CHN32, UserFmtX61, UserFmtFloat },
780 { AL_FORMAT_61CHN_MULAW, UserFmtX61, UserFmtMulaw },
782 { AL_FORMAT_71CHN8, UserFmtX71, UserFmtUByte },
783 { AL_FORMAT_71CHN16, UserFmtX71, UserFmtShort },
784 { AL_FORMAT_71CHN32, UserFmtX71, UserFmtFloat },
785 { AL_FORMAT_71CHN_MULAW, UserFmtX71, UserFmtMulaw },
787 { AL_FORMAT_BFORMAT2D_8, UserFmtBFormat2D, UserFmtUByte },
788 { AL_FORMAT_BFORMAT2D_16, UserFmtBFormat2D, UserFmtShort },
789 { AL_FORMAT_BFORMAT2D_FLOAT32, UserFmtBFormat2D, UserFmtFloat },
790 { AL_FORMAT_BFORMAT2D_MULAW, UserFmtBFormat2D, UserFmtMulaw },
792 { AL_FORMAT_BFORMAT3D_8, UserFmtBFormat3D, UserFmtUByte },
793 { AL_FORMAT_BFORMAT3D_16, UserFmtBFormat3D, UserFmtShort },
794 { AL_FORMAT_BFORMAT3D_FLOAT32, UserFmtBFormat3D, UserFmtFloat },
795 { AL_FORMAT_BFORMAT3D_MULAW, UserFmtBFormat3D, UserFmtMulaw },
797 { AL_FORMAT_UHJ2CHN8_SOFT, UserFmtUHJ2, UserFmtUByte },
798 { AL_FORMAT_UHJ2CHN16_SOFT, UserFmtUHJ2, UserFmtShort },
799 { AL_FORMAT_UHJ2CHN_FLOAT32_SOFT, UserFmtUHJ2, UserFmtFloat },
801 { AL_FORMAT_UHJ3CHN8_SOFT, UserFmtUHJ3, UserFmtUByte },
802 { AL_FORMAT_UHJ3CHN16_SOFT, UserFmtUHJ3, UserFmtShort },
803 { AL_FORMAT_UHJ3CHN_FLOAT32_SOFT, UserFmtUHJ3, UserFmtFloat },
805 { AL_FORMAT_UHJ4CHN8_SOFT, UserFmtUHJ4, UserFmtUByte },
806 { AL_FORMAT_UHJ4CHN16_SOFT, UserFmtUHJ4, UserFmtShort },
807 { AL_FORMAT_UHJ4CHN_FLOAT32_SOFT, UserFmtUHJ4, UserFmtFloat },
810 for(const auto &fmt : UserFmtList)
812 if(fmt.format == format)
813 return al::make_optional<DecompResult>({fmt.channels, fmt.type});
815 return al::nullopt;
818 } // namespace
821 AL_API void AL_APIENTRY alGenBuffers(ALsizei n, ALuint *buffers)
822 START_API_FUNC
824 ContextRef context{GetContextRef()};
825 if UNLIKELY(!context) return;
827 if UNLIKELY(n < 0)
828 context->setError(AL_INVALID_VALUE, "Generating %d buffers", n);
829 if UNLIKELY(n <= 0) return;
831 ALCdevice *device{context->mALDevice.get()};
832 std::lock_guard<std::mutex> _{device->BufferLock};
833 if(!EnsureBuffers(device, static_cast<ALuint>(n)))
835 context->setError(AL_OUT_OF_MEMORY, "Failed to allocate %d buffer%s", n, (n==1)?"":"s");
836 return;
839 if LIKELY(n == 1)
841 /* Special handling for the easy and normal case. */
842 ALbuffer *buffer{AllocBuffer(device)};
843 buffers[0] = buffer->id;
845 else
847 /* Store the allocated buffer IDs in a separate local list, to avoid
848 * modifying the user storage in case of failure.
850 al::vector<ALuint> ids;
851 ids.reserve(static_cast<ALuint>(n));
852 do {
853 ALbuffer *buffer{AllocBuffer(device)};
854 ids.emplace_back(buffer->id);
855 } while(--n);
856 std::copy(ids.begin(), ids.end(), buffers);
859 END_API_FUNC
861 AL_API void AL_APIENTRY alDeleteBuffers(ALsizei n, const ALuint *buffers)
862 START_API_FUNC
864 ContextRef context{GetContextRef()};
865 if UNLIKELY(!context) return;
867 if UNLIKELY(n < 0)
868 context->setError(AL_INVALID_VALUE, "Deleting %d buffers", n);
869 if UNLIKELY(n <= 0) return;
871 ALCdevice *device{context->mALDevice.get()};
872 std::lock_guard<std::mutex> _{device->BufferLock};
874 /* First try to find any buffers that are invalid or in-use. */
875 auto validate_buffer = [device, &context](const ALuint bid) -> bool
877 if(!bid) return true;
878 ALbuffer *ALBuf{LookupBuffer(device, bid)};
879 if UNLIKELY(!ALBuf)
881 context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", bid);
882 return false;
884 if UNLIKELY(ReadRef(ALBuf->ref) != 0)
886 context->setError(AL_INVALID_OPERATION, "Deleting in-use buffer %u", bid);
887 return false;
889 return true;
891 const ALuint *buffers_end = buffers + n;
892 auto invbuf = std::find_if_not(buffers, buffers_end, validate_buffer);
893 if UNLIKELY(invbuf != buffers_end) return;
895 /* All good. Delete non-0 buffer IDs. */
896 auto delete_buffer = [device](const ALuint bid) -> void
898 ALbuffer *buffer{bid ? LookupBuffer(device, bid) : nullptr};
899 if(buffer) FreeBuffer(device, buffer);
901 std::for_each(buffers, buffers_end, delete_buffer);
903 END_API_FUNC
905 AL_API ALboolean AL_APIENTRY alIsBuffer(ALuint buffer)
906 START_API_FUNC
908 ContextRef context{GetContextRef()};
909 if LIKELY(context)
911 ALCdevice *device{context->mALDevice.get()};
912 std::lock_guard<std::mutex> _{device->BufferLock};
913 if(!buffer || LookupBuffer(device, buffer))
914 return AL_TRUE;
916 return AL_FALSE;
918 END_API_FUNC
921 AL_API void AL_APIENTRY alBufferData(ALuint buffer, ALenum format, const ALvoid *data, ALsizei size, ALsizei freq)
922 START_API_FUNC
923 { alBufferStorageSOFT(buffer, format, data, size, freq, 0); }
924 END_API_FUNC
926 AL_API void AL_APIENTRY alBufferStorageSOFT(ALuint buffer, ALenum format, const ALvoid *data, ALsizei size, ALsizei freq, ALbitfieldSOFT flags)
927 START_API_FUNC
929 ContextRef context{GetContextRef()};
930 if UNLIKELY(!context) return;
932 ALCdevice *device{context->mALDevice.get()};
933 std::lock_guard<std::mutex> _{device->BufferLock};
935 ALbuffer *albuf = LookupBuffer(device, buffer);
936 if UNLIKELY(!albuf)
937 context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
938 else if UNLIKELY(size < 0)
939 context->setError(AL_INVALID_VALUE, "Negative storage size %d", size);
940 else if UNLIKELY(freq < 1)
941 context->setError(AL_INVALID_VALUE, "Invalid sample rate %d", freq);
942 else if UNLIKELY((flags&INVALID_STORAGE_MASK) != 0)
943 context->setError(AL_INVALID_VALUE, "Invalid storage flags 0x%x",
944 flags&INVALID_STORAGE_MASK);
945 else if UNLIKELY((flags&AL_MAP_PERSISTENT_BIT_SOFT) && !(flags&MAP_READ_WRITE_FLAGS))
946 context->setError(AL_INVALID_VALUE,
947 "Declaring persistently mapped storage without read or write access");
948 else
950 auto usrfmt = DecomposeUserFormat(format);
951 if UNLIKELY(!usrfmt)
952 context->setError(AL_INVALID_ENUM, "Invalid format 0x%04x", format);
953 else
955 LoadData(context.get(), albuf, freq, static_cast<ALuint>(size), usrfmt->channels,
956 usrfmt->type, static_cast<const al::byte*>(data), flags);
960 END_API_FUNC
962 AL_API void* AL_APIENTRY alMapBufferSOFT(ALuint buffer, ALsizei offset, ALsizei length, ALbitfieldSOFT access)
963 START_API_FUNC
965 ContextRef context{GetContextRef()};
966 if UNLIKELY(!context) return nullptr;
968 ALCdevice *device{context->mALDevice.get()};
969 std::lock_guard<std::mutex> _{device->BufferLock};
971 ALbuffer *albuf = LookupBuffer(device, buffer);
972 if UNLIKELY(!albuf)
973 context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
974 else if UNLIKELY((access&INVALID_MAP_FLAGS) != 0)
975 context->setError(AL_INVALID_VALUE, "Invalid map flags 0x%x", access&INVALID_MAP_FLAGS);
976 else if UNLIKELY(!(access&MAP_READ_WRITE_FLAGS))
977 context->setError(AL_INVALID_VALUE, "Mapping buffer %u without read or write access",
978 buffer);
979 else
981 ALbitfieldSOFT unavailable = (albuf->Access^access) & access;
982 if UNLIKELY(ReadRef(albuf->ref) != 0 && !(access&AL_MAP_PERSISTENT_BIT_SOFT))
983 context->setError(AL_INVALID_OPERATION,
984 "Mapping in-use buffer %u without persistent mapping", buffer);
985 else if UNLIKELY(albuf->MappedAccess != 0)
986 context->setError(AL_INVALID_OPERATION, "Mapping already-mapped buffer %u", buffer);
987 else if UNLIKELY((unavailable&AL_MAP_READ_BIT_SOFT))
988 context->setError(AL_INVALID_VALUE,
989 "Mapping buffer %u for reading without read access", buffer);
990 else if UNLIKELY((unavailable&AL_MAP_WRITE_BIT_SOFT))
991 context->setError(AL_INVALID_VALUE,
992 "Mapping buffer %u for writing without write access", buffer);
993 else if UNLIKELY((unavailable&AL_MAP_PERSISTENT_BIT_SOFT))
994 context->setError(AL_INVALID_VALUE,
995 "Mapping buffer %u persistently without persistent access", buffer);
996 else if UNLIKELY(offset < 0 || length <= 0
997 || static_cast<ALuint>(offset) >= albuf->OriginalSize
998 || static_cast<ALuint>(length) > albuf->OriginalSize - static_cast<ALuint>(offset))
999 context->setError(AL_INVALID_VALUE, "Mapping invalid range %d+%d for buffer %u",
1000 offset, length, buffer);
1001 else
1003 void *retval{albuf->mData.data() + offset};
1004 albuf->MappedAccess = access;
1005 albuf->MappedOffset = offset;
1006 albuf->MappedSize = length;
1007 return retval;
1011 return nullptr;
1013 END_API_FUNC
1015 AL_API void AL_APIENTRY alUnmapBufferSOFT(ALuint buffer)
1016 START_API_FUNC
1018 ContextRef context{GetContextRef()};
1019 if UNLIKELY(!context) return;
1021 ALCdevice *device{context->mALDevice.get()};
1022 std::lock_guard<std::mutex> _{device->BufferLock};
1024 ALbuffer *albuf = LookupBuffer(device, buffer);
1025 if UNLIKELY(!albuf)
1026 context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
1027 else if UNLIKELY(albuf->MappedAccess == 0)
1028 context->setError(AL_INVALID_OPERATION, "Unmapping unmapped buffer %u", buffer);
1029 else
1031 albuf->MappedAccess = 0;
1032 albuf->MappedOffset = 0;
1033 albuf->MappedSize = 0;
1036 END_API_FUNC
1038 AL_API void AL_APIENTRY alFlushMappedBufferSOFT(ALuint buffer, ALsizei offset, ALsizei length)
1039 START_API_FUNC
1041 ContextRef context{GetContextRef()};
1042 if UNLIKELY(!context) return;
1044 ALCdevice *device{context->mALDevice.get()};
1045 std::lock_guard<std::mutex> _{device->BufferLock};
1047 ALbuffer *albuf = LookupBuffer(device, buffer);
1048 if UNLIKELY(!albuf)
1049 context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
1050 else if UNLIKELY(!(albuf->MappedAccess&AL_MAP_WRITE_BIT_SOFT))
1051 context->setError(AL_INVALID_OPERATION, "Flushing buffer %u while not mapped for writing",
1052 buffer);
1053 else if UNLIKELY(offset < albuf->MappedOffset || length <= 0
1054 || offset >= albuf->MappedOffset+albuf->MappedSize
1055 || length > albuf->MappedOffset+albuf->MappedSize-offset)
1056 context->setError(AL_INVALID_VALUE, "Flushing invalid range %d+%d on buffer %u", offset,
1057 length, buffer);
1058 else
1060 /* FIXME: Need to use some method of double-buffering for the mixer and
1061 * app to hold separate memory, which can be safely transfered
1062 * asynchronously. Currently we just say the app shouldn't write where
1063 * OpenAL's reading, and hope for the best...
1065 std::atomic_thread_fence(std::memory_order_seq_cst);
1068 END_API_FUNC
1070 AL_API void AL_APIENTRY alBufferSubDataSOFT(ALuint buffer, ALenum format, const ALvoid *data, ALsizei offset, ALsizei length)
1071 START_API_FUNC
1073 ContextRef context{GetContextRef()};
1074 if UNLIKELY(!context) return;
1076 ALCdevice *device{context->mALDevice.get()};
1077 std::lock_guard<std::mutex> _{device->BufferLock};
1079 ALbuffer *albuf = LookupBuffer(device, buffer);
1080 if UNLIKELY(!albuf)
1082 context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
1083 return;
1086 auto usrfmt = DecomposeUserFormat(format);
1087 if UNLIKELY(!usrfmt)
1089 context->setError(AL_INVALID_ENUM, "Invalid format 0x%04x", format);
1090 return;
1093 ALuint unpack_align{albuf->UnpackAlign};
1094 ALuint align{SanitizeAlignment(usrfmt->type, unpack_align)};
1095 if UNLIKELY(align < 1)
1096 context->setError(AL_INVALID_VALUE, "Invalid unpack alignment %u", unpack_align);
1097 else if UNLIKELY(long{usrfmt->channels} != long{albuf->mChannels}
1098 || usrfmt->type != albuf->OriginalType)
1099 context->setError(AL_INVALID_ENUM, "Unpacking data with mismatched format");
1100 else if UNLIKELY(align != albuf->OriginalAlign)
1101 context->setError(AL_INVALID_VALUE,
1102 "Unpacking data with alignment %u does not match original alignment %u", align,
1103 albuf->OriginalAlign);
1104 else if UNLIKELY(albuf->isBFormat() && albuf->UnpackAmbiOrder != albuf->mAmbiOrder)
1105 context->setError(AL_INVALID_VALUE, "Unpacking data with mismatched ambisonic order");
1106 else if UNLIKELY(albuf->MappedAccess != 0)
1107 context->setError(AL_INVALID_OPERATION, "Unpacking data into mapped buffer %u", buffer);
1108 else
1110 ALuint num_chans{albuf->channelsFromFmt()};
1111 ALuint frame_size{num_chans * albuf->bytesFromFmt()};
1112 ALuint byte_align{
1113 (albuf->OriginalType == UserFmtIMA4) ? ((align-1)/2 + 4) * num_chans :
1114 (albuf->OriginalType == UserFmtMSADPCM) ? ((align-2)/2 + 7) * num_chans :
1115 (align * frame_size)
1118 if UNLIKELY(offset < 0 || length < 0 || static_cast<ALuint>(offset) > albuf->OriginalSize
1119 || static_cast<ALuint>(length) > albuf->OriginalSize-static_cast<ALuint>(offset))
1120 context->setError(AL_INVALID_VALUE, "Invalid data sub-range %d+%d on buffer %u",
1121 offset, length, buffer);
1122 else if UNLIKELY((static_cast<ALuint>(offset)%byte_align) != 0)
1123 context->setError(AL_INVALID_VALUE,
1124 "Sub-range offset %d is not a multiple of frame size %d (%d unpack alignment)",
1125 offset, byte_align, align);
1126 else if UNLIKELY((static_cast<ALuint>(length)%byte_align) != 0)
1127 context->setError(AL_INVALID_VALUE,
1128 "Sub-range length %d is not a multiple of frame size %d (%d unpack alignment)",
1129 length, byte_align, align);
1130 else
1132 /* offset -> byte offset, length -> sample count */
1133 size_t byteoff{static_cast<ALuint>(offset)/byte_align * align * frame_size};
1134 size_t samplen{static_cast<ALuint>(length)/byte_align * align};
1136 void *dst = albuf->mData.data() + byteoff;
1137 if(usrfmt->type == UserFmtIMA4 && albuf->mType == FmtShort)
1138 Convert_int16_ima4(static_cast<int16_t*>(dst), static_cast<const al::byte*>(data),
1139 num_chans, samplen, align);
1140 else if(usrfmt->type == UserFmtMSADPCM && albuf->mType == FmtShort)
1141 Convert_int16_msadpcm(static_cast<int16_t*>(dst),
1142 static_cast<const al::byte*>(data), num_chans, samplen, align);
1143 else
1145 assert(long{usrfmt->type} == long{albuf->mType});
1146 memcpy(dst, data, size_t{samplen} * frame_size);
1151 END_API_FUNC
1154 AL_API void AL_APIENTRY alBufferSamplesSOFT(ALuint /*buffer*/, ALuint /*samplerate*/,
1155 ALenum /*internalformat*/, ALsizei /*samples*/, ALenum /*channels*/, ALenum /*type*/,
1156 const ALvoid* /*data*/)
1157 START_API_FUNC
1159 ContextRef context{GetContextRef()};
1160 if UNLIKELY(!context) return;
1162 context->setError(AL_INVALID_OPERATION, "alBufferSamplesSOFT not supported");
1164 END_API_FUNC
1166 AL_API void AL_APIENTRY alBufferSubSamplesSOFT(ALuint /*buffer*/, ALsizei /*offset*/,
1167 ALsizei /*samples*/, ALenum /*channels*/, ALenum /*type*/, const ALvoid* /*data*/)
1168 START_API_FUNC
1170 ContextRef context{GetContextRef()};
1171 if UNLIKELY(!context) return;
1173 context->setError(AL_INVALID_OPERATION, "alBufferSubSamplesSOFT not supported");
1175 END_API_FUNC
1177 AL_API void AL_APIENTRY alGetBufferSamplesSOFT(ALuint /*buffer*/, ALsizei /*offset*/,
1178 ALsizei /*samples*/, ALenum /*channels*/, ALenum /*type*/, ALvoid* /*data*/)
1179 START_API_FUNC
1181 ContextRef context{GetContextRef()};
1182 if UNLIKELY(!context) return;
1184 context->setError(AL_INVALID_OPERATION, "alGetBufferSamplesSOFT not supported");
1186 END_API_FUNC
1188 AL_API ALboolean AL_APIENTRY alIsBufferFormatSupportedSOFT(ALenum /*format*/)
1189 START_API_FUNC
1191 ContextRef context{GetContextRef()};
1192 if UNLIKELY(!context) return AL_FALSE;
1194 context->setError(AL_INVALID_OPERATION, "alIsBufferFormatSupportedSOFT not supported");
1195 return AL_FALSE;
1197 END_API_FUNC
1200 AL_API void AL_APIENTRY alBufferf(ALuint buffer, ALenum param, ALfloat /*value*/)
1201 START_API_FUNC
1203 ContextRef context{GetContextRef()};
1204 if UNLIKELY(!context) return;
1206 ALCdevice *device{context->mALDevice.get()};
1207 std::lock_guard<std::mutex> _{device->BufferLock};
1209 if UNLIKELY(LookupBuffer(device, buffer) == nullptr)
1210 context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
1211 else switch(param)
1213 default:
1214 context->setError(AL_INVALID_ENUM, "Invalid buffer float property 0x%04x", param);
1217 END_API_FUNC
1219 AL_API void AL_APIENTRY alBuffer3f(ALuint buffer, ALenum param,
1220 ALfloat /*value1*/, ALfloat /*value2*/, ALfloat /*value3*/)
1221 START_API_FUNC
1223 ContextRef context{GetContextRef()};
1224 if UNLIKELY(!context) return;
1226 ALCdevice *device{context->mALDevice.get()};
1227 std::lock_guard<std::mutex> _{device->BufferLock};
1229 if UNLIKELY(LookupBuffer(device, buffer) == nullptr)
1230 context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
1231 else switch(param)
1233 default:
1234 context->setError(AL_INVALID_ENUM, "Invalid buffer 3-float property 0x%04x", param);
1237 END_API_FUNC
1239 AL_API void AL_APIENTRY alBufferfv(ALuint buffer, ALenum param, const ALfloat *values)
1240 START_API_FUNC
1242 ContextRef context{GetContextRef()};
1243 if UNLIKELY(!context) return;
1245 ALCdevice *device{context->mALDevice.get()};
1246 std::lock_guard<std::mutex> _{device->BufferLock};
1248 if UNLIKELY(LookupBuffer(device, buffer) == nullptr)
1249 context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
1250 else if UNLIKELY(!values)
1251 context->setError(AL_INVALID_VALUE, "NULL pointer");
1252 else switch(param)
1254 default:
1255 context->setError(AL_INVALID_ENUM, "Invalid buffer float-vector property 0x%04x", param);
1258 END_API_FUNC
1261 AL_API void AL_APIENTRY alBufferi(ALuint buffer, ALenum param, ALint value)
1262 START_API_FUNC
1264 ContextRef context{GetContextRef()};
1265 if UNLIKELY(!context) return;
1267 ALCdevice *device{context->mALDevice.get()};
1268 std::lock_guard<std::mutex> _{device->BufferLock};
1270 ALbuffer *albuf = LookupBuffer(device, buffer);
1271 if UNLIKELY(!albuf)
1272 context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
1273 else switch(param)
1275 case AL_UNPACK_BLOCK_ALIGNMENT_SOFT:
1276 if UNLIKELY(value < 0)
1277 context->setError(AL_INVALID_VALUE, "Invalid unpack block alignment %d", value);
1278 else
1279 albuf->UnpackAlign = static_cast<ALuint>(value);
1280 break;
1282 case AL_PACK_BLOCK_ALIGNMENT_SOFT:
1283 if UNLIKELY(value < 0)
1284 context->setError(AL_INVALID_VALUE, "Invalid pack block alignment %d", value);
1285 else
1286 albuf->PackAlign = static_cast<ALuint>(value);
1287 break;
1289 case AL_AMBISONIC_LAYOUT_SOFT:
1290 if UNLIKELY(ReadRef(albuf->ref) != 0)
1291 context->setError(AL_INVALID_OPERATION, "Modifying in-use buffer %u's ambisonic layout",
1292 buffer);
1293 else if UNLIKELY(value != AL_FUMA_SOFT && value != AL_ACN_SOFT)
1294 context->setError(AL_INVALID_VALUE, "Invalid unpack ambisonic layout %04x", value);
1295 else
1296 albuf->mAmbiLayout = AmbiLayoutFromEnum(value).value();
1297 break;
1299 case AL_AMBISONIC_SCALING_SOFT:
1300 if UNLIKELY(ReadRef(albuf->ref) != 0)
1301 context->setError(AL_INVALID_OPERATION, "Modifying in-use buffer %u's ambisonic scaling",
1302 buffer);
1303 else if UNLIKELY(value != AL_FUMA_SOFT && value != AL_SN3D_SOFT && value != AL_N3D_SOFT)
1304 context->setError(AL_INVALID_VALUE, "Invalid unpack ambisonic scaling %04x", value);
1305 else
1306 albuf->mAmbiScaling = AmbiScalingFromEnum(value).value();
1307 break;
1309 case AL_UNPACK_AMBISONIC_ORDER_SOFT:
1310 if UNLIKELY(value < 1 || value > 14)
1311 context->setError(AL_INVALID_VALUE, "Invalid unpack ambisonic order %d", value);
1312 else
1313 albuf->UnpackAmbiOrder = static_cast<ALuint>(value);
1314 break;
1316 default:
1317 context->setError(AL_INVALID_ENUM, "Invalid buffer integer property 0x%04x", param);
1320 END_API_FUNC
1322 AL_API void AL_APIENTRY alBuffer3i(ALuint buffer, ALenum param,
1323 ALint /*value1*/, ALint /*value2*/, ALint /*value3*/)
1324 START_API_FUNC
1326 ContextRef context{GetContextRef()};
1327 if UNLIKELY(!context) return;
1329 ALCdevice *device{context->mALDevice.get()};
1330 std::lock_guard<std::mutex> _{device->BufferLock};
1332 if UNLIKELY(LookupBuffer(device, buffer) == nullptr)
1333 context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
1334 else switch(param)
1336 default:
1337 context->setError(AL_INVALID_ENUM, "Invalid buffer 3-integer property 0x%04x", param);
1340 END_API_FUNC
1342 AL_API void AL_APIENTRY alBufferiv(ALuint buffer, ALenum param, const ALint *values)
1343 START_API_FUNC
1345 if(values)
1347 switch(param)
1349 case AL_UNPACK_BLOCK_ALIGNMENT_SOFT:
1350 case AL_PACK_BLOCK_ALIGNMENT_SOFT:
1351 case AL_AMBISONIC_LAYOUT_SOFT:
1352 case AL_AMBISONIC_SCALING_SOFT:
1353 case AL_UNPACK_AMBISONIC_ORDER_SOFT:
1354 alBufferi(buffer, param, values[0]);
1355 return;
1359 ContextRef context{GetContextRef()};
1360 if UNLIKELY(!context) return;
1362 ALCdevice *device{context->mALDevice.get()};
1363 std::lock_guard<std::mutex> _{device->BufferLock};
1365 ALbuffer *albuf = LookupBuffer(device, buffer);
1366 if UNLIKELY(!albuf)
1367 context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
1368 else if UNLIKELY(!values)
1369 context->setError(AL_INVALID_VALUE, "NULL pointer");
1370 else switch(param)
1372 case AL_LOOP_POINTS_SOFT:
1373 if UNLIKELY(ReadRef(albuf->ref) != 0)
1374 context->setError(AL_INVALID_OPERATION, "Modifying in-use buffer %u's loop points",
1375 buffer);
1376 else if UNLIKELY(values[0] < 0 || values[0] >= values[1]
1377 || static_cast<ALuint>(values[1]) > albuf->mSampleLen)
1378 context->setError(AL_INVALID_VALUE, "Invalid loop point range %d -> %d on buffer %u",
1379 values[0], values[1], buffer);
1380 else
1382 albuf->mLoopStart = static_cast<ALuint>(values[0]);
1383 albuf->mLoopEnd = static_cast<ALuint>(values[1]);
1385 break;
1387 default:
1388 context->setError(AL_INVALID_ENUM, "Invalid buffer integer-vector property 0x%04x", param);
1391 END_API_FUNC
1394 AL_API void AL_APIENTRY alGetBufferf(ALuint buffer, ALenum param, ALfloat *value)
1395 START_API_FUNC
1397 ContextRef context{GetContextRef()};
1398 if UNLIKELY(!context) return;
1400 ALCdevice *device{context->mALDevice.get()};
1401 std::lock_guard<std::mutex> _{device->BufferLock};
1403 ALbuffer *albuf = LookupBuffer(device, buffer);
1404 if UNLIKELY(!albuf)
1405 context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
1406 else if UNLIKELY(!value)
1407 context->setError(AL_INVALID_VALUE, "NULL pointer");
1408 else switch(param)
1410 default:
1411 context->setError(AL_INVALID_ENUM, "Invalid buffer float property 0x%04x", param);
1414 END_API_FUNC
1416 AL_API void AL_APIENTRY alGetBuffer3f(ALuint buffer, ALenum param, ALfloat *value1, ALfloat *value2, ALfloat *value3)
1417 START_API_FUNC
1419 ContextRef context{GetContextRef()};
1420 if UNLIKELY(!context) return;
1422 ALCdevice *device{context->mALDevice.get()};
1423 std::lock_guard<std::mutex> _{device->BufferLock};
1425 if UNLIKELY(LookupBuffer(device, buffer) == nullptr)
1426 context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
1427 else if UNLIKELY(!value1 || !value2 || !value3)
1428 context->setError(AL_INVALID_VALUE, "NULL pointer");
1429 else switch(param)
1431 default:
1432 context->setError(AL_INVALID_ENUM, "Invalid buffer 3-float property 0x%04x", param);
1435 END_API_FUNC
1437 AL_API void AL_APIENTRY alGetBufferfv(ALuint buffer, ALenum param, ALfloat *values)
1438 START_API_FUNC
1440 switch(param)
1442 case AL_SEC_LENGTH_SOFT:
1443 alGetBufferf(buffer, param, values);
1444 return;
1447 ContextRef context{GetContextRef()};
1448 if UNLIKELY(!context) return;
1450 ALCdevice *device{context->mALDevice.get()};
1451 std::lock_guard<std::mutex> _{device->BufferLock};
1453 if UNLIKELY(LookupBuffer(device, buffer) == nullptr)
1454 context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
1455 else if UNLIKELY(!values)
1456 context->setError(AL_INVALID_VALUE, "NULL pointer");
1457 else switch(param)
1459 default:
1460 context->setError(AL_INVALID_ENUM, "Invalid buffer float-vector property 0x%04x", param);
1463 END_API_FUNC
1466 AL_API void AL_APIENTRY alGetBufferi(ALuint buffer, ALenum param, ALint *value)
1467 START_API_FUNC
1469 ContextRef context{GetContextRef()};
1470 if UNLIKELY(!context) return;
1472 ALCdevice *device{context->mALDevice.get()};
1473 std::lock_guard<std::mutex> _{device->BufferLock};
1474 ALbuffer *albuf = LookupBuffer(device, buffer);
1475 if UNLIKELY(!albuf)
1476 context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
1477 else if UNLIKELY(!value)
1478 context->setError(AL_INVALID_VALUE, "NULL pointer");
1479 else switch(param)
1481 case AL_FREQUENCY:
1482 *value = static_cast<ALint>(albuf->mSampleRate);
1483 break;
1485 case AL_BITS:
1486 *value = static_cast<ALint>(albuf->bytesFromFmt() * 8);
1487 break;
1489 case AL_CHANNELS:
1490 *value = static_cast<ALint>(albuf->channelsFromFmt());
1491 break;
1493 case AL_SIZE:
1494 *value = static_cast<ALint>(albuf->mSampleLen * albuf->frameSizeFromFmt());
1495 break;
1497 case AL_UNPACK_BLOCK_ALIGNMENT_SOFT:
1498 *value = static_cast<ALint>(albuf->UnpackAlign);
1499 break;
1501 case AL_PACK_BLOCK_ALIGNMENT_SOFT:
1502 *value = static_cast<ALint>(albuf->PackAlign);
1503 break;
1505 case AL_AMBISONIC_LAYOUT_SOFT:
1506 *value = EnumFromAmbiLayout(albuf->mAmbiLayout);
1507 break;
1509 case AL_AMBISONIC_SCALING_SOFT:
1510 *value = EnumFromAmbiScaling(albuf->mAmbiScaling);
1511 break;
1513 case AL_UNPACK_AMBISONIC_ORDER_SOFT:
1514 *value = static_cast<int>(albuf->UnpackAmbiOrder);
1515 break;
1517 default:
1518 context->setError(AL_INVALID_ENUM, "Invalid buffer integer property 0x%04x", param);
1521 END_API_FUNC
1523 AL_API void AL_APIENTRY alGetBuffer3i(ALuint buffer, ALenum param, ALint *value1, ALint *value2, ALint *value3)
1524 START_API_FUNC
1526 ContextRef context{GetContextRef()};
1527 if UNLIKELY(!context) return;
1529 ALCdevice *device{context->mALDevice.get()};
1530 std::lock_guard<std::mutex> _{device->BufferLock};
1531 if UNLIKELY(LookupBuffer(device, buffer) == nullptr)
1532 context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
1533 else if UNLIKELY(!value1 || !value2 || !value3)
1534 context->setError(AL_INVALID_VALUE, "NULL pointer");
1535 else switch(param)
1537 default:
1538 context->setError(AL_INVALID_ENUM, "Invalid buffer 3-integer property 0x%04x", param);
1541 END_API_FUNC
1543 AL_API void AL_APIENTRY alGetBufferiv(ALuint buffer, ALenum param, ALint *values)
1544 START_API_FUNC
1546 switch(param)
1548 case AL_FREQUENCY:
1549 case AL_BITS:
1550 case AL_CHANNELS:
1551 case AL_SIZE:
1552 case AL_INTERNAL_FORMAT_SOFT:
1553 case AL_BYTE_LENGTH_SOFT:
1554 case AL_SAMPLE_LENGTH_SOFT:
1555 case AL_UNPACK_BLOCK_ALIGNMENT_SOFT:
1556 case AL_PACK_BLOCK_ALIGNMENT_SOFT:
1557 case AL_AMBISONIC_LAYOUT_SOFT:
1558 case AL_AMBISONIC_SCALING_SOFT:
1559 case AL_UNPACK_AMBISONIC_ORDER_SOFT:
1560 alGetBufferi(buffer, param, values);
1561 return;
1564 ContextRef context{GetContextRef()};
1565 if UNLIKELY(!context) return;
1567 ALCdevice *device{context->mALDevice.get()};
1568 std::lock_guard<std::mutex> _{device->BufferLock};
1569 ALbuffer *albuf = LookupBuffer(device, buffer);
1570 if UNLIKELY(!albuf)
1571 context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
1572 else if UNLIKELY(!values)
1573 context->setError(AL_INVALID_VALUE, "NULL pointer");
1574 else switch(param)
1576 case AL_LOOP_POINTS_SOFT:
1577 values[0] = static_cast<ALint>(albuf->mLoopStart);
1578 values[1] = static_cast<ALint>(albuf->mLoopEnd);
1579 break;
1581 default:
1582 context->setError(AL_INVALID_ENUM, "Invalid buffer integer-vector property 0x%04x", param);
1585 END_API_FUNC
1588 AL_API void AL_APIENTRY alBufferCallbackSOFT(ALuint buffer, ALenum format, ALsizei freq,
1589 ALBUFFERCALLBACKTYPESOFT callback, ALvoid *userptr, ALbitfieldSOFT flags)
1590 START_API_FUNC
1592 ContextRef context{GetContextRef()};
1593 if UNLIKELY(!context) return;
1595 ALCdevice *device{context->mALDevice.get()};
1596 std::lock_guard<std::mutex> _{device->BufferLock};
1598 ALbuffer *albuf = LookupBuffer(device, buffer);
1599 if UNLIKELY(!albuf)
1600 context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
1601 else if UNLIKELY(freq < 1)
1602 context->setError(AL_INVALID_VALUE, "Invalid sample rate %d", freq);
1603 else if UNLIKELY(callback == nullptr)
1604 context->setError(AL_INVALID_VALUE, "NULL callback");
1605 else if UNLIKELY(flags != 0)
1606 context->setError(AL_INVALID_VALUE, "Invalid callback flags 0x%x", flags);
1607 else
1609 auto usrfmt = DecomposeUserFormat(format);
1610 if UNLIKELY(!usrfmt)
1611 context->setError(AL_INVALID_ENUM, "Invalid format 0x%04x", format);
1612 else
1613 PrepareCallback(context.get(), albuf, freq, usrfmt->channels, usrfmt->type, callback,
1614 userptr);
1617 END_API_FUNC
1619 AL_API void AL_APIENTRY alGetBufferPtrSOFT(ALuint buffer, ALenum param, ALvoid **value)
1620 START_API_FUNC
1622 ContextRef context{GetContextRef()};
1623 if UNLIKELY(!context) return;
1625 ALCdevice *device{context->mALDevice.get()};
1626 std::lock_guard<std::mutex> _{device->BufferLock};
1627 ALbuffer *albuf = LookupBuffer(device, buffer);
1628 if UNLIKELY(!albuf)
1629 context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
1630 else if UNLIKELY(!value)
1631 context->setError(AL_INVALID_VALUE, "NULL pointer");
1632 else switch(param)
1634 case AL_BUFFER_CALLBACK_FUNCTION_SOFT:
1635 *value = reinterpret_cast<void*>(albuf->mCallback);
1636 break;
1637 case AL_BUFFER_CALLBACK_USER_PARAM_SOFT:
1638 *value = albuf->mUserData;
1639 break;
1641 default:
1642 context->setError(AL_INVALID_ENUM, "Invalid buffer pointer property 0x%04x", param);
1645 END_API_FUNC
1647 AL_API void AL_APIENTRY alGetBuffer3PtrSOFT(ALuint buffer, ALenum param, ALvoid **value1, ALvoid **value2, ALvoid **value3)
1648 START_API_FUNC
1650 ContextRef context{GetContextRef()};
1651 if UNLIKELY(!context) return;
1653 ALCdevice *device{context->mALDevice.get()};
1654 std::lock_guard<std::mutex> _{device->BufferLock};
1655 if UNLIKELY(LookupBuffer(device, buffer) == nullptr)
1656 context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
1657 else if UNLIKELY(!value1 || !value2 || !value3)
1658 context->setError(AL_INVALID_VALUE, "NULL pointer");
1659 else switch(param)
1661 default:
1662 context->setError(AL_INVALID_ENUM, "Invalid buffer 3-pointer property 0x%04x", param);
1665 END_API_FUNC
1667 AL_API void AL_APIENTRY alGetBufferPtrvSOFT(ALuint buffer, ALenum param, ALvoid **values)
1668 START_API_FUNC
1670 switch(param)
1672 case AL_BUFFER_CALLBACK_FUNCTION_SOFT:
1673 case AL_BUFFER_CALLBACK_USER_PARAM_SOFT:
1674 alGetBufferPtrSOFT(buffer, param, values);
1675 return;
1678 ContextRef context{GetContextRef()};
1679 if UNLIKELY(!context) return;
1681 ALCdevice *device{context->mALDevice.get()};
1682 std::lock_guard<std::mutex> _{device->BufferLock};
1683 if UNLIKELY(LookupBuffer(device, buffer) == nullptr)
1684 context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
1685 else if UNLIKELY(!values)
1686 context->setError(AL_INVALID_VALUE, "NULL pointer");
1687 else switch(param)
1689 default:
1690 context->setError(AL_INVALID_ENUM, "Invalid buffer pointer-vector property 0x%04x", param);
1693 END_API_FUNC
1696 BufferSubList::~BufferSubList()
1698 uint64_t usemask{~FreeMask};
1699 while(usemask)
1701 const int idx{al::countr_zero(usemask)};
1702 al::destroy_at(Buffers+idx);
1703 usemask &= ~(1_u64 << idx);
1705 FreeMask = ~usemask;
1706 al_free(Buffers);
1707 Buffers = nullptr;
1711 #ifdef ALSOFT_EAX
1712 FORCE_ALIGN ALboolean AL_APIENTRY EAXSetBufferMode(ALsizei n, const ALuint* buffers, ALint value)
1713 START_API_FUNC
1715 #define EAX_PREFIX "[EAXSetBufferMode] "
1717 const auto context = ContextRef{GetContextRef()};
1718 if(!context)
1720 ERR(EAX_PREFIX "%s\n", "No current context.");
1721 return ALC_FALSE;
1724 if(!eax_g_is_enabled)
1726 context->setError(AL_INVALID_OPERATION, EAX_PREFIX "%s", "EAX not enabled.");
1727 return ALC_FALSE;
1730 switch(value)
1732 case AL_STORAGE_AUTOMATIC:
1733 case AL_STORAGE_HARDWARE:
1734 case AL_STORAGE_ACCESSIBLE:
1735 break;
1737 default:
1738 context->setError(AL_INVALID_ENUM, EAX_PREFIX "Unsupported X-RAM mode 0x%x", value);
1739 return ALC_FALSE;
1742 if(n == 0)
1743 return ALC_TRUE;
1745 if(n < 0)
1747 context->setError(AL_INVALID_VALUE, EAX_PREFIX "Buffer count %d out of range", n);
1748 return ALC_FALSE;
1751 if(!buffers)
1753 context->setError(AL_INVALID_VALUE, EAX_PREFIX "%s", "Null AL buffers");
1754 return ALC_FALSE;
1757 auto device = context->mALDevice.get();
1758 std::lock_guard<std::mutex> device_lock{device->BufferLock};
1759 size_t total_needed{0};
1761 // Validate the buffers.
1763 for(auto i = 0;i < n;++i)
1765 const auto buffer = buffers[i];
1766 if(buffer == AL_NONE)
1767 continue;
1769 const auto al_buffer = LookupBuffer(device, buffer);
1770 if (!al_buffer)
1772 ERR(EAX_PREFIX "Invalid buffer ID %u.\n", buffer);
1773 return ALC_FALSE;
1776 /* TODO: Is the store location allowed to change for in-use buffers, or
1777 * only when not set/queued on a source?
1780 if(value == AL_STORAGE_HARDWARE && !al_buffer->eax_x_ram_is_hardware)
1782 /* FIXME: This doesn't account for duplicate buffers. When the same
1783 * buffer ID is specified multiple times in the provided list, it
1784 * counts each instance as more memory that needs to fit in X-RAM.
1786 if(unlikely(std::numeric_limits<size_t>::max()-al_buffer->OriginalSize < total_needed))
1788 context->setError(AL_OUT_OF_MEMORY, EAX_PREFIX "Buffer size overflow (%u + %zu)\n",
1789 al_buffer->OriginalSize, total_needed);
1790 return ALC_FALSE;
1792 total_needed += al_buffer->OriginalSize;
1795 if(total_needed > device->eax_x_ram_free_size)
1797 context->setError(AL_INVALID_ENUM, EAX_PREFIX "Out of X-RAM memory (need: %zu, avail: %u)",
1798 total_needed, device->eax_x_ram_free_size);
1799 return ALC_FALSE;
1802 // Update the mode.
1804 for(auto i = 0;i < n;++i)
1806 const auto buffer = buffers[i];
1807 if(buffer == AL_NONE)
1808 continue;
1810 const auto al_buffer = LookupBuffer(device, buffer);
1811 assert(al_buffer);
1813 if(value != AL_STORAGE_ACCESSIBLE)
1814 eax_x_ram_apply(*device, *al_buffer);
1815 else
1816 eax_x_ram_clear(*device, *al_buffer);
1817 al_buffer->eax_x_ram_mode = value;
1820 return AL_TRUE;
1822 #undef EAX_PREFIX
1824 END_API_FUNC
1826 FORCE_ALIGN ALenum AL_APIENTRY EAXGetBufferMode(ALuint buffer, ALint* pReserved)
1827 START_API_FUNC
1829 #define EAX_PREFIX "[EAXGetBufferMode] "
1831 const auto context = ContextRef{GetContextRef()};
1832 if(!context)
1834 ERR(EAX_PREFIX "%s\n", "No current context.");
1835 return AL_NONE;
1838 if(!eax_g_is_enabled)
1840 context->setError(AL_INVALID_OPERATION, EAX_PREFIX "%s", "EAX not enabled.");
1841 return AL_NONE;
1844 if(pReserved)
1846 context->setError(AL_INVALID_VALUE, EAX_PREFIX "%s", "Non-null reserved parameter");
1847 return AL_NONE;
1850 auto device = context->mALDevice.get();
1851 std::lock_guard<std::mutex> device_lock{device->BufferLock};
1853 const auto al_buffer = LookupBuffer(device, buffer);
1854 if(!al_buffer)
1856 context->setError(AL_INVALID_NAME, EAX_PREFIX "Invalid buffer ID %u", buffer);
1857 return AL_NONE;
1860 return al_buffer->eax_x_ram_mode;
1862 #undef EAX_PREFIX
1864 END_API_FUNC
1866 #endif // ALSOFT_EAX