Merge pull request #483 from jhasse/silence-nodiscard
[openal-soft.git] / al / buffer.cpp
blob524fb81cecb0e515d7a567c60e2912e606bc5af7
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 <utility>
40 #include "AL/al.h"
41 #include "AL/alc.h"
42 #include "AL/alext.h"
44 #include "albyte.h"
45 #include "alcmain.h"
46 #include "alcontext.h"
47 #include "alexcpt.h"
48 #include "almalloc.h"
49 #include "alnumeric.h"
50 #include "aloptional.h"
51 #include "atomic.h"
52 #include "inprogext.h"
53 #include "opthelpers.h"
56 namespace {
58 constexpr int MaxAdpcmChannels{2};
60 /* IMA ADPCM Stepsize table */
61 constexpr int IMAStep_size[89] = {
62 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 19,
63 21, 23, 25, 28, 31, 34, 37, 41, 45, 50, 55,
64 60, 66, 73, 80, 88, 97, 107, 118, 130, 143, 157,
65 173, 190, 209, 230, 253, 279, 307, 337, 371, 408, 449,
66 494, 544, 598, 658, 724, 796, 876, 963, 1060, 1166, 1282,
67 1411, 1552, 1707, 1878, 2066, 2272, 2499, 2749, 3024, 3327, 3660,
68 4026, 4428, 4871, 5358, 5894, 6484, 7132, 7845, 8630, 9493,10442,
69 11487,12635,13899,15289,16818,18500,20350,22358,24633,27086,29794,
70 32767
73 /* IMA4 ADPCM Codeword decode table */
74 constexpr int IMA4Codeword[16] = {
75 1, 3, 5, 7, 9, 11, 13, 15,
76 -1,-3,-5,-7,-9,-11,-13,-15,
79 /* IMA4 ADPCM Step index adjust decode table */
80 constexpr int IMA4Index_adjust[16] = {
81 -1,-1,-1,-1, 2, 4, 6, 8,
82 -1,-1,-1,-1, 2, 4, 6, 8
86 /* MSADPCM Adaption table */
87 constexpr int MSADPCMAdaption[16] = {
88 230, 230, 230, 230, 307, 409, 512, 614,
89 768, 614, 512, 409, 307, 230, 230, 230
92 /* MSADPCM Adaption Coefficient tables */
93 constexpr int MSADPCMAdaptionCoeff[7][2] = {
94 { 256, 0 },
95 { 512, -256 },
96 { 0, 0 },
97 { 192, 64 },
98 { 240, 0 },
99 { 460, -208 },
100 { 392, -232 }
104 void DecodeIMA4Block(int16_t *dst, const al::byte *src, size_t numchans, size_t align)
106 int sample[MaxAdpcmChannels]{};
107 int index[MaxAdpcmChannels]{};
108 ALuint code[MaxAdpcmChannels]{};
110 for(size_t c{0};c < numchans;c++)
112 sample[c] = al::to_integer<int>(src[0]) | (al::to_integer<int>(src[1])<<8);
113 sample[c] = (sample[c]^0x8000) - 32768;
114 src += 2;
115 index[c] = al::to_integer<int>(src[0]) | (al::to_integer<int>(src[1])<<8);
116 index[c] = clampi((index[c]^0x8000) - 32768, 0, 88);
117 src += 2;
119 *(dst++) = static_cast<int16_t>(sample[c]);
122 for(size_t i{1};i < align;i++)
124 if((i&7) == 1)
126 for(size_t c{0};c < numchans;c++)
128 code[c] = al::to_integer<ALuint>(src[0]) | (al::to_integer<ALuint>(src[1])<< 8) |
129 (al::to_integer<ALuint>(src[2])<<16) | (al::to_integer<ALuint>(src[3])<<24);
130 src += 4;
134 for(size_t c{0};c < numchans;c++)
136 const ALuint nibble{code[c]&0xf};
137 code[c] >>= 4;
139 sample[c] += IMA4Codeword[nibble] * IMAStep_size[index[c]] / 8;
140 sample[c] = clampi(sample[c], -32768, 32767);
142 index[c] += IMA4Index_adjust[nibble];
143 index[c] = clampi(index[c], 0, 88);
145 *(dst++) = static_cast<int16_t>(sample[c]);
150 void DecodeMSADPCMBlock(int16_t *dst, const al::byte *src, size_t numchans, size_t align)
152 uint8_t blockpred[MaxAdpcmChannels]{};
153 int delta[MaxAdpcmChannels]{};
154 int16_t samples[MaxAdpcmChannels][2]{};
156 for(size_t c{0};c < numchans;c++)
158 blockpred[c] = std::min<ALubyte>(al::to_integer<ALubyte>(src[0]), 6);
159 ++src;
161 for(size_t c{0};c < numchans;c++)
163 delta[c] = al::to_integer<int>(src[0]) | (al::to_integer<int>(src[1])<<8);
164 delta[c] = (delta[c]^0x8000) - 32768;
165 src += 2;
167 for(size_t c{0};c < numchans;c++)
169 samples[c][0] = static_cast<ALshort>(al::to_integer<int>(src[0]) |
170 (al::to_integer<int>(src[1])<<8));
171 src += 2;
173 for(size_t c{0};c < numchans;c++)
175 samples[c][1] = static_cast<ALshort>(al::to_integer<int>(src[0]) |
176 (al::to_integer<int>(src[1])<<8));
177 src += 2;
180 /* Second sample is written first. */
181 for(size_t c{0};c < numchans;c++)
182 *(dst++) = samples[c][1];
183 for(size_t c{0};c < numchans;c++)
184 *(dst++) = samples[c][0];
186 int num{0};
187 for(size_t i{2};i < align;i++)
189 for(size_t c{0};c < numchans;c++)
191 /* Read the nibble (first is in the upper bits). */
192 al::byte nibble;
193 if(!(num++ & 1))
194 nibble = *src >> 4;
195 else
196 nibble = *(src++) & 0x0f;
198 int pred{(samples[c][0]*MSADPCMAdaptionCoeff[blockpred[c]][0] +
199 samples[c][1]*MSADPCMAdaptionCoeff[blockpred[c]][1]) / 256};
200 pred += (al::to_integer<int>(nibble^0x08) - 0x08) * delta[c];
201 pred = clampi(pred, -32768, 32767);
203 samples[c][1] = samples[c][0];
204 samples[c][0] = static_cast<int16_t>(pred);
206 delta[c] = (MSADPCMAdaption[al::to_integer<ALubyte>(nibble)] * delta[c]) / 256;
207 delta[c] = maxi(16, delta[c]);
209 *(dst++) = static_cast<int16_t>(pred);
214 void Convert_int16_ima4(int16_t *dst, const al::byte *src, size_t numchans, size_t len,
215 size_t align)
217 assert(numchans <= MaxAdpcmChannels);
218 const size_t byte_align{((align-1)/2 + 4) * numchans};
220 len /= align;
221 while(len--)
223 DecodeIMA4Block(dst, src, numchans, align);
224 src += byte_align;
225 dst += align*numchans;
229 void Convert_int16_msadpcm(int16_t *dst, const al::byte *src, size_t numchans, size_t len,
230 size_t align)
232 assert(numchans <= MaxAdpcmChannels);
233 const size_t byte_align{((align-2)/2 + 7) * numchans};
235 len /= align;
236 while(len--)
238 DecodeMSADPCMBlock(dst, src, numchans, align);
239 src += byte_align;
240 dst += align*numchans;
245 ALuint BytesFromUserFmt(UserFmtType type) noexcept
247 switch(type)
249 case UserFmtUByte: return sizeof(uint8_t);
250 case UserFmtShort: return sizeof(int16_t);
251 case UserFmtFloat: return sizeof(float);
252 case UserFmtDouble: return sizeof(double);
253 case UserFmtMulaw: return sizeof(uint8_t);
254 case UserFmtAlaw: return sizeof(uint8_t);
255 case UserFmtIMA4: break; /* not handled here */
256 case UserFmtMSADPCM: break; /* not handled here */
258 return 0;
260 ALuint ChannelsFromUserFmt(UserFmtChannels chans, ALuint ambiorder) noexcept
262 switch(chans)
264 case UserFmtMono: return 1;
265 case UserFmtStereo: return 2;
266 case UserFmtRear: return 2;
267 case UserFmtQuad: return 4;
268 case UserFmtX51: return 6;
269 case UserFmtX61: return 7;
270 case UserFmtX71: return 8;
271 case UserFmtBFormat2D: return (ambiorder*2) + 1;
272 case UserFmtBFormat3D: return (ambiorder+1) * (ambiorder+1);
274 return 0;
278 constexpr ALbitfieldSOFT INVALID_STORAGE_MASK{~unsigned(AL_MAP_READ_BIT_SOFT |
279 AL_MAP_WRITE_BIT_SOFT | AL_MAP_PERSISTENT_BIT_SOFT | AL_PRESERVE_DATA_BIT_SOFT)};
280 constexpr ALbitfieldSOFT MAP_READ_WRITE_FLAGS{AL_MAP_READ_BIT_SOFT | AL_MAP_WRITE_BIT_SOFT};
281 constexpr ALbitfieldSOFT INVALID_MAP_FLAGS{~unsigned(AL_MAP_READ_BIT_SOFT | AL_MAP_WRITE_BIT_SOFT |
282 AL_MAP_PERSISTENT_BIT_SOFT)};
285 bool EnsureBuffers(ALCdevice *device, size_t needed)
287 size_t count{std::accumulate(device->BufferList.cbegin(), device->BufferList.cend(), size_t{0},
288 [](size_t cur, const BufferSubList &sublist) noexcept -> size_t
289 { return cur + static_cast<ALuint>(PopCount(sublist.FreeMask)); })};
291 while(needed > count)
293 if UNLIKELY(device->BufferList.size() >= 1<<25)
294 return false;
296 device->BufferList.emplace_back();
297 auto sublist = device->BufferList.end() - 1;
298 sublist->FreeMask = ~0_u64;
299 sublist->Buffers = static_cast<ALbuffer*>(al_calloc(alignof(ALbuffer), sizeof(ALbuffer)*64));
300 if UNLIKELY(!sublist->Buffers)
302 device->BufferList.pop_back();
303 return false;
305 count += 64;
307 return true;
310 ALbuffer *AllocBuffer(ALCdevice *device)
312 auto sublist = std::find_if(device->BufferList.begin(), device->BufferList.end(),
313 [](const BufferSubList &entry) noexcept -> bool
314 { return entry.FreeMask != 0; }
317 auto lidx = static_cast<ALuint>(std::distance(device->BufferList.begin(), sublist));
318 auto slidx = static_cast<ALuint>(CountTrailingZeros(sublist->FreeMask));
320 ALbuffer *buffer{::new (sublist->Buffers + slidx) ALbuffer{}};
322 /* Add 1 to avoid buffer ID 0. */
323 buffer->id = ((lidx<<6) | slidx) + 1;
325 sublist->FreeMask &= ~(1_u64 << slidx);
327 return buffer;
330 void FreeBuffer(ALCdevice *device, ALbuffer *buffer)
332 const ALuint id{buffer->id - 1};
333 const size_t lidx{id >> 6};
334 const ALuint slidx{id & 0x3f};
336 al::destroy_at(buffer);
338 device->BufferList[lidx].FreeMask |= 1_u64 << slidx;
341 inline ALbuffer *LookupBuffer(ALCdevice *device, ALuint id)
343 const size_t lidx{(id-1) >> 6};
344 const ALuint slidx{(id-1) & 0x3f};
346 if UNLIKELY(lidx >= device->BufferList.size())
347 return nullptr;
348 BufferSubList &sublist = device->BufferList[lidx];
349 if UNLIKELY(sublist.FreeMask & (1_u64 << slidx))
350 return nullptr;
351 return sublist.Buffers + slidx;
355 ALuint SanitizeAlignment(UserFmtType type, ALuint align)
357 if(align == 0)
359 if(type == UserFmtIMA4)
361 /* Here is where things vary:
362 * nVidia and Apple use 64+1 sample frames per block -> block_size=36 bytes per channel
363 * Most PC sound software uses 2040+1 sample frames per block -> block_size=1024 bytes per channel
365 return 65;
367 if(type == UserFmtMSADPCM)
368 return 64;
369 return 1;
372 if(type == UserFmtIMA4)
374 /* IMA4 block alignment must be a multiple of 8, plus 1. */
375 if((align&7) == 1) return static_cast<ALuint>(align);
376 return 0;
378 if(type == UserFmtMSADPCM)
380 /* MSADPCM block alignment must be a multiple of 2. */
381 if((align&1) == 0) return static_cast<ALuint>(align);
382 return 0;
385 return static_cast<ALuint>(align);
389 const ALchar *NameFromUserFmtType(UserFmtType type)
391 switch(type)
393 case UserFmtUByte: return "UInt8";
394 case UserFmtShort: return "Int16";
395 case UserFmtFloat: return "Float32";
396 case UserFmtDouble: return "Float64";
397 case UserFmtMulaw: return "muLaw";
398 case UserFmtAlaw: return "aLaw";
399 case UserFmtIMA4: return "IMA4 ADPCM";
400 case UserFmtMSADPCM: return "MSADPCM";
402 return "<internal type error>";
405 /** Loads the specified data into the buffer, using the specified format. */
406 void LoadData(ALCcontext *context, ALbuffer *ALBuf, ALsizei freq, ALuint size,
407 UserFmtChannels SrcChannels, UserFmtType SrcType, const al::byte *SrcData,
408 ALbitfieldSOFT access)
410 if UNLIKELY(ReadRef(ALBuf->ref) != 0 || ALBuf->MappedAccess != 0)
411 SETERR_RETURN(context, AL_INVALID_OPERATION,, "Modifying storage for in-use buffer %u",
412 ALBuf->id);
414 /* Currently no channel configurations need to be converted. */
415 FmtChannels DstChannels{FmtMono};
416 switch(SrcChannels)
418 case UserFmtMono: DstChannels = FmtMono; break;
419 case UserFmtStereo: DstChannels = FmtStereo; break;
420 case UserFmtRear: DstChannels = FmtRear; break;
421 case UserFmtQuad: DstChannels = FmtQuad; break;
422 case UserFmtX51: DstChannels = FmtX51; break;
423 case UserFmtX61: DstChannels = FmtX61; break;
424 case UserFmtX71: DstChannels = FmtX71; break;
425 case UserFmtBFormat2D: DstChannels = FmtBFormat2D; break;
426 case UserFmtBFormat3D: DstChannels = FmtBFormat3D; break;
428 if UNLIKELY(static_cast<long>(SrcChannels) != static_cast<long>(DstChannels))
429 SETERR_RETURN(context, AL_INVALID_ENUM, , "Invalid format");
431 /* IMA4 and MSADPCM convert to 16-bit short. */
432 FmtType DstType{FmtUByte};
433 switch(SrcType)
435 case UserFmtUByte: DstType = FmtUByte; break;
436 case UserFmtShort: DstType = FmtShort; break;
437 case UserFmtFloat: DstType = FmtFloat; break;
438 case UserFmtDouble: DstType = FmtDouble; break;
439 case UserFmtAlaw: DstType = FmtAlaw; break;
440 case UserFmtMulaw: DstType = FmtMulaw; break;
441 case UserFmtIMA4: DstType = FmtShort; break;
442 case UserFmtMSADPCM: DstType = FmtShort; break;
445 /* TODO: Currently we can only map samples when they're not converted. To
446 * allow it would need some kind of double-buffering to hold onto a copy of
447 * the original data.
449 if((access&MAP_READ_WRITE_FLAGS))
451 if UNLIKELY(static_cast<long>(SrcType) != static_cast<long>(DstType))
452 SETERR_RETURN(context, AL_INVALID_VALUE,, "%s samples cannot be mapped",
453 NameFromUserFmtType(SrcType));
456 const ALuint unpackalign{ALBuf->UnpackAlign};
457 const ALuint align{SanitizeAlignment(SrcType, unpackalign)};
458 if UNLIKELY(align < 1)
459 SETERR_RETURN(context, AL_INVALID_VALUE,, "Invalid unpack alignment %u for %s samples",
460 unpackalign, NameFromUserFmtType(SrcType));
462 const ALuint ambiorder{(DstChannels == FmtBFormat2D || DstChannels == FmtBFormat3D) ?
463 ALBuf->UnpackAmbiOrder : 0};
465 if((access&AL_PRESERVE_DATA_BIT_SOFT))
467 /* Can only preserve data with the same format and alignment. */
468 if UNLIKELY(ALBuf->mBuffer.mChannels != DstChannels || ALBuf->OriginalType != SrcType)
469 SETERR_RETURN(context, AL_INVALID_VALUE,, "Preserving data of mismatched format");
470 if UNLIKELY(ALBuf->OriginalAlign != align)
471 SETERR_RETURN(context, AL_INVALID_VALUE,, "Preserving data of mismatched alignment");
472 if(ALBuf->mBuffer.mAmbiOrder != ambiorder)
473 SETERR_RETURN(context, AL_INVALID_VALUE,, "Preserving data of mismatched order");
476 /* Convert the input/source size in bytes to sample frames using the unpack
477 * block alignment.
479 const ALuint SrcByteAlign{ChannelsFromUserFmt(SrcChannels, ambiorder) *
480 ((SrcType == UserFmtIMA4) ? (align-1)/2 + 4 :
481 (SrcType == UserFmtMSADPCM) ? (align-2)/2 + 7 :
482 (align * BytesFromUserFmt(SrcType)))};
483 if UNLIKELY((size%SrcByteAlign) != 0)
484 SETERR_RETURN(context, AL_INVALID_VALUE,,
485 "Data size %d is not a multiple of frame size %d (%d unpack alignment)",
486 size, SrcByteAlign, align);
488 if UNLIKELY(size/SrcByteAlign > std::numeric_limits<ALsizei>::max()/align)
489 SETERR_RETURN(context, AL_OUT_OF_MEMORY,,
490 "Buffer size overflow, %d blocks x %d samples per block", size/SrcByteAlign, align);
491 const ALuint frames{size / SrcByteAlign * align};
493 /* Convert the sample frames to the number of bytes needed for internal
494 * storage.
496 ALuint NumChannels{ChannelsFromFmt(DstChannels, ambiorder)};
497 ALuint FrameSize{NumChannels * BytesFromFmt(DstType)};
498 if UNLIKELY(frames > std::numeric_limits<size_t>::max()/FrameSize)
499 SETERR_RETURN(context, AL_OUT_OF_MEMORY,,
500 "Buffer size overflow, %d frames x %d bytes per frame", frames, FrameSize);
501 size_t newsize{static_cast<size_t>(frames) * FrameSize};
503 /* Round up to the next 16-byte multiple. This could reallocate only when
504 * increasing or the new size is less than half the current, but then the
505 * buffer's AL_SIZE would not be very reliable for accounting buffer memory
506 * usage, and reporting the real size could cause problems for apps that
507 * use AL_SIZE to try to get the buffer's play length.
509 newsize = RoundUp(newsize, 16);
510 if(newsize != ALBuf->mBuffer.mData.size())
512 auto newdata = al::vector<al::byte,16>(newsize, al::byte{});
513 if((access&AL_PRESERVE_DATA_BIT_SOFT))
515 const size_t tocopy{minz(newdata.size(), ALBuf->mBuffer.mData.size())};
516 std::copy_n(ALBuf->mBuffer.mData.begin(), tocopy, newdata.begin());
518 newdata.swap(ALBuf->mBuffer.mData);
521 if(SrcType == UserFmtIMA4)
523 assert(DstType == FmtShort);
524 if(SrcData != nullptr && !ALBuf->mBuffer.mData.empty())
525 Convert_int16_ima4(reinterpret_cast<int16_t*>(ALBuf->mBuffer.mData.data()), SrcData,
526 NumChannels, frames, align);
527 ALBuf->OriginalAlign = align;
529 else if(SrcType == UserFmtMSADPCM)
531 assert(DstType == FmtShort);
532 if(SrcData != nullptr && !ALBuf->mBuffer.mData.empty())
533 Convert_int16_msadpcm(reinterpret_cast<int16_t*>(ALBuf->mBuffer.mData.data()), SrcData,
534 NumChannels, frames, align);
535 ALBuf->OriginalAlign = align;
537 else
539 assert(static_cast<long>(SrcType) == static_cast<long>(DstType));
540 if(SrcData != nullptr && !ALBuf->mBuffer.mData.empty())
541 std::copy_n(SrcData, frames*FrameSize, ALBuf->mBuffer.mData.begin());
542 ALBuf->OriginalAlign = 1;
544 ALBuf->OriginalSize = size;
545 ALBuf->OriginalType = SrcType;
547 ALBuf->mBuffer.mSampleRate = static_cast<ALuint>(freq);
548 ALBuf->mBuffer.mChannels = DstChannels;
549 ALBuf->mBuffer.mType = DstType;
550 ALBuf->Access = access;
551 ALBuf->mBuffer.mAmbiOrder = ambiorder;
553 ALBuf->mBuffer.mCallback = nullptr;
554 ALBuf->mBuffer.mUserData = nullptr;
556 ALBuf->mBuffer.mSampleLen = frames;
557 ALBuf->LoopStart = 0;
558 ALBuf->LoopEnd = ALBuf->mBuffer.mSampleLen;
561 /** Prepares the buffer to use the specified callback, using the specified format. */
562 void PrepareCallback(ALCcontext *context, ALbuffer *ALBuf, ALsizei freq,
563 UserFmtChannels SrcChannels, UserFmtType SrcType, LPALBUFFERCALLBACKTYPESOFT callback,
564 void *userptr)
566 if UNLIKELY(ReadRef(ALBuf->ref) != 0 || ALBuf->MappedAccess != 0)
567 SETERR_RETURN(context, AL_INVALID_OPERATION,, "Modifying callback for in-use buffer %u",
568 ALBuf->id);
570 /* Currently no channel configurations need to be converted. */
571 FmtChannels DstChannels{FmtMono};
572 switch(SrcChannels)
574 case UserFmtMono: DstChannels = FmtMono; break;
575 case UserFmtStereo: DstChannels = FmtStereo; break;
576 case UserFmtRear: DstChannels = FmtRear; break;
577 case UserFmtQuad: DstChannels = FmtQuad; break;
578 case UserFmtX51: DstChannels = FmtX51; break;
579 case UserFmtX61: DstChannels = FmtX61; break;
580 case UserFmtX71: DstChannels = FmtX71; break;
581 case UserFmtBFormat2D: DstChannels = FmtBFormat2D; break;
582 case UserFmtBFormat3D: DstChannels = FmtBFormat3D; break;
584 if UNLIKELY(static_cast<long>(SrcChannels) != static_cast<long>(DstChannels))
585 SETERR_RETURN(context, AL_INVALID_ENUM,, "Invalid format");
587 /* IMA4 and MSADPCM convert to 16-bit short. Not supported with callbacks. */
588 FmtType DstType{FmtUByte};
589 switch(SrcType)
591 case UserFmtUByte: DstType = FmtUByte; break;
592 case UserFmtShort: DstType = FmtShort; break;
593 case UserFmtFloat: DstType = FmtFloat; break;
594 case UserFmtDouble: DstType = FmtDouble; break;
595 case UserFmtAlaw: DstType = FmtAlaw; break;
596 case UserFmtMulaw: DstType = FmtMulaw; break;
597 case UserFmtIMA4: DstType = FmtShort; break;
598 case UserFmtMSADPCM: DstType = FmtShort; break;
600 if UNLIKELY(static_cast<long>(SrcType) != static_cast<long>(DstType))
601 SETERR_RETURN(context, AL_INVALID_ENUM,, "Unsupported callback format");
603 const ALuint ambiorder{(DstChannels == FmtBFormat2D || DstChannels == FmtBFormat3D) ?
604 ALBuf->UnpackAmbiOrder : 0};
606 al::vector<al::byte,16>(FrameSizeFromFmt(DstChannels, DstType, ambiorder) *
607 size_t{BUFFERSIZE + (MAX_RESAMPLER_PADDING>>1)}).swap(ALBuf->mBuffer.mData);
609 ALBuf->mBuffer.mCallback = callback;
610 ALBuf->mBuffer.mUserData = userptr;
612 ALBuf->OriginalType = SrcType;
613 ALBuf->OriginalSize = 0;
614 ALBuf->OriginalAlign = 1;
616 ALBuf->mBuffer.mSampleRate = static_cast<ALuint>(freq);
617 ALBuf->mBuffer.mChannels = DstChannels;
618 ALBuf->mBuffer.mType = DstType;
619 ALBuf->Access = 0;
620 ALBuf->mBuffer.mAmbiOrder = ambiorder;
622 ALBuf->mBuffer.mSampleLen = 0;
623 ALBuf->LoopStart = 0;
624 ALBuf->LoopEnd = ALBuf->mBuffer.mSampleLen;
628 struct DecompResult { UserFmtChannels channels; UserFmtType type; };
629 al::optional<DecompResult> DecomposeUserFormat(ALenum format)
631 struct FormatMap {
632 ALenum format;
633 UserFmtChannels channels;
634 UserFmtType type;
636 static const std::array<FormatMap,46> UserFmtList{{
637 { AL_FORMAT_MONO8, UserFmtMono, UserFmtUByte },
638 { AL_FORMAT_MONO16, UserFmtMono, UserFmtShort },
639 { AL_FORMAT_MONO_FLOAT32, UserFmtMono, UserFmtFloat },
640 { AL_FORMAT_MONO_DOUBLE_EXT, UserFmtMono, UserFmtDouble },
641 { AL_FORMAT_MONO_IMA4, UserFmtMono, UserFmtIMA4 },
642 { AL_FORMAT_MONO_MSADPCM_SOFT, UserFmtMono, UserFmtMSADPCM },
643 { AL_FORMAT_MONO_MULAW, UserFmtMono, UserFmtMulaw },
644 { AL_FORMAT_MONO_ALAW_EXT, UserFmtMono, UserFmtAlaw },
646 { AL_FORMAT_STEREO8, UserFmtStereo, UserFmtUByte },
647 { AL_FORMAT_STEREO16, UserFmtStereo, UserFmtShort },
648 { AL_FORMAT_STEREO_FLOAT32, UserFmtStereo, UserFmtFloat },
649 { AL_FORMAT_STEREO_DOUBLE_EXT, UserFmtStereo, UserFmtDouble },
650 { AL_FORMAT_STEREO_IMA4, UserFmtStereo, UserFmtIMA4 },
651 { AL_FORMAT_STEREO_MSADPCM_SOFT, UserFmtStereo, UserFmtMSADPCM },
652 { AL_FORMAT_STEREO_MULAW, UserFmtStereo, UserFmtMulaw },
653 { AL_FORMAT_STEREO_ALAW_EXT, UserFmtStereo, UserFmtAlaw },
655 { AL_FORMAT_REAR8, UserFmtRear, UserFmtUByte },
656 { AL_FORMAT_REAR16, UserFmtRear, UserFmtShort },
657 { AL_FORMAT_REAR32, UserFmtRear, UserFmtFloat },
658 { AL_FORMAT_REAR_MULAW, UserFmtRear, UserFmtMulaw },
660 { AL_FORMAT_QUAD8_LOKI, UserFmtQuad, UserFmtUByte },
661 { AL_FORMAT_QUAD16_LOKI, UserFmtQuad, UserFmtShort },
663 { AL_FORMAT_QUAD8, UserFmtQuad, UserFmtUByte },
664 { AL_FORMAT_QUAD16, UserFmtQuad, UserFmtShort },
665 { AL_FORMAT_QUAD32, UserFmtQuad, UserFmtFloat },
666 { AL_FORMAT_QUAD_MULAW, UserFmtQuad, UserFmtMulaw },
668 { AL_FORMAT_51CHN8, UserFmtX51, UserFmtUByte },
669 { AL_FORMAT_51CHN16, UserFmtX51, UserFmtShort },
670 { AL_FORMAT_51CHN32, UserFmtX51, UserFmtFloat },
671 { AL_FORMAT_51CHN_MULAW, UserFmtX51, UserFmtMulaw },
673 { AL_FORMAT_61CHN8, UserFmtX61, UserFmtUByte },
674 { AL_FORMAT_61CHN16, UserFmtX61, UserFmtShort },
675 { AL_FORMAT_61CHN32, UserFmtX61, UserFmtFloat },
676 { AL_FORMAT_61CHN_MULAW, UserFmtX61, UserFmtMulaw },
678 { AL_FORMAT_71CHN8, UserFmtX71, UserFmtUByte },
679 { AL_FORMAT_71CHN16, UserFmtX71, UserFmtShort },
680 { AL_FORMAT_71CHN32, UserFmtX71, UserFmtFloat },
681 { AL_FORMAT_71CHN_MULAW, UserFmtX71, UserFmtMulaw },
683 { AL_FORMAT_BFORMAT2D_8, UserFmtBFormat2D, UserFmtUByte },
684 { AL_FORMAT_BFORMAT2D_16, UserFmtBFormat2D, UserFmtShort },
685 { AL_FORMAT_BFORMAT2D_FLOAT32, UserFmtBFormat2D, UserFmtFloat },
686 { AL_FORMAT_BFORMAT2D_MULAW, UserFmtBFormat2D, UserFmtMulaw },
688 { AL_FORMAT_BFORMAT3D_8, UserFmtBFormat3D, UserFmtUByte },
689 { AL_FORMAT_BFORMAT3D_16, UserFmtBFormat3D, UserFmtShort },
690 { AL_FORMAT_BFORMAT3D_FLOAT32, UserFmtBFormat3D, UserFmtFloat },
691 { AL_FORMAT_BFORMAT3D_MULAW, UserFmtBFormat3D, UserFmtMulaw },
694 for(const auto &fmt : UserFmtList)
696 if(fmt.format == format)
697 return al::make_optional<DecompResult>({fmt.channels, fmt.type});
699 return al::nullopt;
702 } // namespace
705 AL_API void AL_APIENTRY alGenBuffers(ALsizei n, ALuint *buffers)
706 START_API_FUNC
708 ContextRef context{GetContextRef()};
709 if UNLIKELY(!context) return;
711 if UNLIKELY(n < 0)
712 context->setError(AL_INVALID_VALUE, "Generating %d buffers", n);
713 if UNLIKELY(n <= 0) return;
715 ALCdevice *device{context->mDevice.get()};
716 std::lock_guard<std::mutex> _{device->BufferLock};
717 if(!EnsureBuffers(device, static_cast<ALuint>(n)))
719 context->setError(AL_OUT_OF_MEMORY, "Failed to allocate %d buffer%s", n, (n==1)?"":"s");
720 return;
723 if LIKELY(n == 1)
725 /* Special handling for the easy and normal case. */
726 ALbuffer *buffer{AllocBuffer(device)};
727 buffers[0] = buffer->id;
729 else
731 /* Store the allocated buffer IDs in a separate local list, to avoid
732 * modifying the user storage in case of failure.
734 al::vector<ALuint> ids;
735 ids.reserve(static_cast<ALuint>(n));
736 do {
737 ALbuffer *buffer{AllocBuffer(device)};
738 ids.emplace_back(buffer->id);
739 } while(--n);
740 std::copy(ids.begin(), ids.end(), buffers);
743 END_API_FUNC
745 AL_API void AL_APIENTRY alDeleteBuffers(ALsizei n, const ALuint *buffers)
746 START_API_FUNC
748 ContextRef context{GetContextRef()};
749 if UNLIKELY(!context) return;
751 if UNLIKELY(n < 0)
752 context->setError(AL_INVALID_VALUE, "Deleting %d buffers", n);
753 if UNLIKELY(n <= 0) return;
755 ALCdevice *device{context->mDevice.get()};
756 std::lock_guard<std::mutex> _{device->BufferLock};
758 /* First try to find any buffers that are invalid or in-use. */
759 auto validate_buffer = [device, &context](const ALuint bid) -> bool
761 if(!bid) return true;
762 ALbuffer *ALBuf{LookupBuffer(device, bid)};
763 if UNLIKELY(!ALBuf)
765 context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", bid);
766 return false;
768 if UNLIKELY(ReadRef(ALBuf->ref) != 0)
770 context->setError(AL_INVALID_OPERATION, "Deleting in-use buffer %u", bid);
771 return false;
773 return true;
775 const ALuint *buffers_end = buffers + n;
776 auto invbuf = std::find_if_not(buffers, buffers_end, validate_buffer);
777 if UNLIKELY(invbuf != buffers_end) return;
779 /* All good. Delete non-0 buffer IDs. */
780 auto delete_buffer = [device](const ALuint bid) -> void
782 ALbuffer *buffer{bid ? LookupBuffer(device, bid) : nullptr};
783 if(buffer) FreeBuffer(device, buffer);
785 std::for_each(buffers, buffers_end, delete_buffer);
787 END_API_FUNC
789 AL_API ALboolean AL_APIENTRY alIsBuffer(ALuint buffer)
790 START_API_FUNC
792 ContextRef context{GetContextRef()};
793 if LIKELY(context)
795 ALCdevice *device{context->mDevice.get()};
796 std::lock_guard<std::mutex> _{device->BufferLock};
797 if(!buffer || LookupBuffer(device, buffer))
798 return AL_TRUE;
800 return AL_FALSE;
802 END_API_FUNC
805 AL_API void AL_APIENTRY alBufferData(ALuint buffer, ALenum format, const ALvoid *data, ALsizei size, ALsizei freq)
806 START_API_FUNC
807 { alBufferStorageSOFT(buffer, format, data, size, freq, 0); }
808 END_API_FUNC
810 AL_API void AL_APIENTRY alBufferStorageSOFT(ALuint buffer, ALenum format, const ALvoid *data, ALsizei size, ALsizei freq, ALbitfieldSOFT flags)
811 START_API_FUNC
813 ContextRef context{GetContextRef()};
814 if UNLIKELY(!context) return;
816 ALCdevice *device{context->mDevice.get()};
817 std::lock_guard<std::mutex> _{device->BufferLock};
819 ALbuffer *albuf = LookupBuffer(device, buffer);
820 if UNLIKELY(!albuf)
821 context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
822 else if UNLIKELY(size < 0)
823 context->setError(AL_INVALID_VALUE, "Negative storage size %d", size);
824 else if UNLIKELY(freq < 1)
825 context->setError(AL_INVALID_VALUE, "Invalid sample rate %d", freq);
826 else if UNLIKELY((flags&INVALID_STORAGE_MASK) != 0)
827 context->setError(AL_INVALID_VALUE, "Invalid storage flags 0x%x",
828 flags&INVALID_STORAGE_MASK);
829 else if UNLIKELY((flags&AL_MAP_PERSISTENT_BIT_SOFT) && !(flags&MAP_READ_WRITE_FLAGS))
830 context->setError(AL_INVALID_VALUE,
831 "Declaring persistently mapped storage without read or write access");
832 else
834 auto usrfmt = DecomposeUserFormat(format);
835 if UNLIKELY(!usrfmt)
836 context->setError(AL_INVALID_ENUM, "Invalid format 0x%04x", format);
837 else
838 LoadData(context.get(), albuf, freq, static_cast<ALuint>(size), usrfmt->channels,
839 usrfmt->type, static_cast<const al::byte*>(data), flags);
842 END_API_FUNC
844 AL_API void* AL_APIENTRY alMapBufferSOFT(ALuint buffer, ALsizei offset, ALsizei length, ALbitfieldSOFT access)
845 START_API_FUNC
847 ContextRef context{GetContextRef()};
848 if UNLIKELY(!context) return nullptr;
850 ALCdevice *device{context->mDevice.get()};
851 std::lock_guard<std::mutex> _{device->BufferLock};
853 ALbuffer *albuf = LookupBuffer(device, buffer);
854 if UNLIKELY(!albuf)
855 context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
856 else if UNLIKELY((access&INVALID_MAP_FLAGS) != 0)
857 context->setError(AL_INVALID_VALUE, "Invalid map flags 0x%x", access&INVALID_MAP_FLAGS);
858 else if UNLIKELY(!(access&MAP_READ_WRITE_FLAGS))
859 context->setError(AL_INVALID_VALUE, "Mapping buffer %u without read or write access",
860 buffer);
861 else
863 ALbitfieldSOFT unavailable = (albuf->Access^access) & access;
864 if UNLIKELY(ReadRef(albuf->ref) != 0 && !(access&AL_MAP_PERSISTENT_BIT_SOFT))
865 context->setError(AL_INVALID_OPERATION,
866 "Mapping in-use buffer %u without persistent mapping", buffer);
867 else if UNLIKELY(albuf->MappedAccess != 0)
868 context->setError(AL_INVALID_OPERATION, "Mapping already-mapped buffer %u", buffer);
869 else if UNLIKELY((unavailable&AL_MAP_READ_BIT_SOFT))
870 context->setError(AL_INVALID_VALUE,
871 "Mapping buffer %u for reading without read access", buffer);
872 else if UNLIKELY((unavailable&AL_MAP_WRITE_BIT_SOFT))
873 context->setError(AL_INVALID_VALUE,
874 "Mapping buffer %u for writing without write access", buffer);
875 else if UNLIKELY((unavailable&AL_MAP_PERSISTENT_BIT_SOFT))
876 context->setError(AL_INVALID_VALUE,
877 "Mapping buffer %u persistently without persistent access", buffer);
878 else if UNLIKELY(offset < 0 || length <= 0
879 || static_cast<ALuint>(offset) >= albuf->OriginalSize
880 || static_cast<ALuint>(length) > albuf->OriginalSize - static_cast<ALuint>(offset))
881 context->setError(AL_INVALID_VALUE, "Mapping invalid range %d+%d for buffer %u",
882 offset, length, buffer);
883 else
885 void *retval{albuf->mBuffer.mData.data() + offset};
886 albuf->MappedAccess = access;
887 albuf->MappedOffset = offset;
888 albuf->MappedSize = length;
889 return retval;
893 return nullptr;
895 END_API_FUNC
897 AL_API void AL_APIENTRY alUnmapBufferSOFT(ALuint buffer)
898 START_API_FUNC
900 ContextRef context{GetContextRef()};
901 if UNLIKELY(!context) return;
903 ALCdevice *device{context->mDevice.get()};
904 std::lock_guard<std::mutex> _{device->BufferLock};
906 ALbuffer *albuf = LookupBuffer(device, buffer);
907 if UNLIKELY(!albuf)
908 context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
909 else if UNLIKELY(albuf->MappedAccess == 0)
910 context->setError(AL_INVALID_OPERATION, "Unmapping unmapped buffer %u", buffer);
911 else
913 albuf->MappedAccess = 0;
914 albuf->MappedOffset = 0;
915 albuf->MappedSize = 0;
918 END_API_FUNC
920 AL_API void AL_APIENTRY alFlushMappedBufferSOFT(ALuint buffer, ALsizei offset, ALsizei length)
921 START_API_FUNC
923 ContextRef context{GetContextRef()};
924 if UNLIKELY(!context) return;
926 ALCdevice *device{context->mDevice.get()};
927 std::lock_guard<std::mutex> _{device->BufferLock};
929 ALbuffer *albuf = LookupBuffer(device, buffer);
930 if UNLIKELY(!albuf)
931 context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
932 else if UNLIKELY(!(albuf->MappedAccess&AL_MAP_WRITE_BIT_SOFT))
933 context->setError(AL_INVALID_OPERATION, "Flushing buffer %u while not mapped for writing",
934 buffer);
935 else if UNLIKELY(offset < albuf->MappedOffset || length <= 0
936 || offset >= albuf->MappedOffset+albuf->MappedSize
937 || length > albuf->MappedOffset+albuf->MappedSize-offset)
938 context->setError(AL_INVALID_VALUE, "Flushing invalid range %d+%d on buffer %u", offset,
939 length, buffer);
940 else
942 /* FIXME: Need to use some method of double-buffering for the mixer and
943 * app to hold separate memory, which can be safely transfered
944 * asynchronously. Currently we just say the app shouldn't write where
945 * OpenAL's reading, and hope for the best...
947 std::atomic_thread_fence(std::memory_order_seq_cst);
950 END_API_FUNC
952 AL_API void AL_APIENTRY alBufferSubDataSOFT(ALuint buffer, ALenum format, const ALvoid *data, ALsizei offset, ALsizei length)
953 START_API_FUNC
955 ContextRef context{GetContextRef()};
956 if UNLIKELY(!context) return;
958 ALCdevice *device{context->mDevice.get()};
959 std::lock_guard<std::mutex> _{device->BufferLock};
961 ALbuffer *albuf = LookupBuffer(device, buffer);
962 if UNLIKELY(!albuf)
964 context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
965 return;
968 auto usrfmt = DecomposeUserFormat(format);
969 if UNLIKELY(!usrfmt)
971 context->setError(AL_INVALID_ENUM, "Invalid format 0x%04x", format);
972 return;
975 ALuint unpack_align{albuf->UnpackAlign};
976 ALuint align{SanitizeAlignment(usrfmt->type, unpack_align)};
977 if UNLIKELY(align < 1)
978 context->setError(AL_INVALID_VALUE, "Invalid unpack alignment %u", unpack_align);
979 else if UNLIKELY(long{usrfmt->channels} != long{albuf->mBuffer.mChannels}
980 || usrfmt->type != albuf->OriginalType)
981 context->setError(AL_INVALID_ENUM, "Unpacking data with mismatched format");
982 else if UNLIKELY(align != albuf->OriginalAlign)
983 context->setError(AL_INVALID_VALUE,
984 "Unpacking data with alignment %u does not match original alignment %u", align,
985 albuf->OriginalAlign);
986 else if UNLIKELY(albuf->mBuffer.isBFormat()
987 && albuf->UnpackAmbiOrder != albuf->mBuffer.mAmbiOrder)
988 context->setError(AL_INVALID_VALUE, "Unpacking data with mismatched ambisonic order");
989 else if UNLIKELY(albuf->MappedAccess != 0)
990 context->setError(AL_INVALID_OPERATION, "Unpacking data into mapped buffer %u", buffer);
991 else
993 ALuint num_chans{albuf->channelsFromFmt()};
994 ALuint frame_size{num_chans * albuf->bytesFromFmt()};
995 ALuint byte_align{
996 (albuf->OriginalType == UserFmtIMA4) ? ((align-1)/2 + 4) * num_chans :
997 (albuf->OriginalType == UserFmtMSADPCM) ? ((align-2)/2 + 7) * num_chans :
998 (align * frame_size)
1001 if UNLIKELY(offset < 0 || length < 0 || static_cast<ALuint>(offset) > albuf->OriginalSize
1002 || static_cast<ALuint>(length) > albuf->OriginalSize-static_cast<ALuint>(offset))
1003 context->setError(AL_INVALID_VALUE, "Invalid data sub-range %d+%d on buffer %u",
1004 offset, length, buffer);
1005 else if UNLIKELY((static_cast<ALuint>(offset)%byte_align) != 0)
1006 context->setError(AL_INVALID_VALUE,
1007 "Sub-range offset %d is not a multiple of frame size %d (%d unpack alignment)",
1008 offset, byte_align, align);
1009 else if UNLIKELY((static_cast<ALuint>(length)%byte_align) != 0)
1010 context->setError(AL_INVALID_VALUE,
1011 "Sub-range length %d is not a multiple of frame size %d (%d unpack alignment)",
1012 length, byte_align, align);
1013 else
1015 /* offset -> byte offset, length -> sample count */
1016 size_t byteoff{static_cast<ALuint>(offset)/byte_align * align * frame_size};
1017 size_t samplen{static_cast<ALuint>(length)/byte_align * align};
1019 void *dst = albuf->mBuffer.mData.data() + byteoff;
1020 if(usrfmt->type == UserFmtIMA4 && albuf->mBuffer.mType == FmtShort)
1021 Convert_int16_ima4(static_cast<int16_t*>(dst), static_cast<const al::byte*>(data),
1022 num_chans, samplen, align);
1023 else if(usrfmt->type == UserFmtMSADPCM && albuf->mBuffer.mType == FmtShort)
1024 Convert_int16_msadpcm(static_cast<int16_t*>(dst),
1025 static_cast<const al::byte*>(data), num_chans, samplen, align);
1026 else
1028 assert(long{usrfmt->type} == long{albuf->mBuffer.mType});
1029 memcpy(dst, data, size_t{samplen} * frame_size);
1034 END_API_FUNC
1037 AL_API void AL_APIENTRY alBufferSamplesSOFT(ALuint /*buffer*/, ALuint /*samplerate*/,
1038 ALenum /*internalformat*/, ALsizei /*samples*/, ALenum /*channels*/, ALenum /*type*/,
1039 const ALvoid* /*data*/)
1040 START_API_FUNC
1042 ContextRef context{GetContextRef()};
1043 if UNLIKELY(!context) return;
1045 context->setError(AL_INVALID_OPERATION, "alBufferSamplesSOFT not supported");
1047 END_API_FUNC
1049 AL_API void AL_APIENTRY alBufferSubSamplesSOFT(ALuint /*buffer*/, ALsizei /*offset*/,
1050 ALsizei /*samples*/, ALenum /*channels*/, ALenum /*type*/, const ALvoid* /*data*/)
1051 START_API_FUNC
1053 ContextRef context{GetContextRef()};
1054 if UNLIKELY(!context) return;
1056 context->setError(AL_INVALID_OPERATION, "alBufferSubSamplesSOFT not supported");
1058 END_API_FUNC
1060 AL_API void AL_APIENTRY alGetBufferSamplesSOFT(ALuint /*buffer*/, ALsizei /*offset*/,
1061 ALsizei /*samples*/, ALenum /*channels*/, ALenum /*type*/, ALvoid* /*data*/)
1062 START_API_FUNC
1064 ContextRef context{GetContextRef()};
1065 if UNLIKELY(!context) return;
1067 context->setError(AL_INVALID_OPERATION, "alGetBufferSamplesSOFT not supported");
1069 END_API_FUNC
1071 AL_API ALboolean AL_APIENTRY alIsBufferFormatSupportedSOFT(ALenum /*format*/)
1072 START_API_FUNC
1074 ContextRef context{GetContextRef()};
1075 if UNLIKELY(!context) return AL_FALSE;
1077 context->setError(AL_INVALID_OPERATION, "alIsBufferFormatSupportedSOFT not supported");
1078 return AL_FALSE;
1080 END_API_FUNC
1083 AL_API void AL_APIENTRY alBufferf(ALuint buffer, ALenum param, ALfloat /*value*/)
1084 START_API_FUNC
1086 ContextRef context{GetContextRef()};
1087 if UNLIKELY(!context) return;
1089 ALCdevice *device{context->mDevice.get()};
1090 std::lock_guard<std::mutex> _{device->BufferLock};
1092 if UNLIKELY(LookupBuffer(device, buffer) == nullptr)
1093 context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
1094 else switch(param)
1096 default:
1097 context->setError(AL_INVALID_ENUM, "Invalid buffer float property 0x%04x", param);
1100 END_API_FUNC
1102 AL_API void AL_APIENTRY alBuffer3f(ALuint buffer, ALenum param,
1103 ALfloat /*value1*/, ALfloat /*value2*/, ALfloat /*value3*/)
1104 START_API_FUNC
1106 ContextRef context{GetContextRef()};
1107 if UNLIKELY(!context) return;
1109 ALCdevice *device{context->mDevice.get()};
1110 std::lock_guard<std::mutex> _{device->BufferLock};
1112 if UNLIKELY(LookupBuffer(device, buffer) == nullptr)
1113 context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
1114 else switch(param)
1116 default:
1117 context->setError(AL_INVALID_ENUM, "Invalid buffer 3-float property 0x%04x", param);
1120 END_API_FUNC
1122 AL_API void AL_APIENTRY alBufferfv(ALuint buffer, ALenum param, const ALfloat *values)
1123 START_API_FUNC
1125 ContextRef context{GetContextRef()};
1126 if UNLIKELY(!context) return;
1128 ALCdevice *device{context->mDevice.get()};
1129 std::lock_guard<std::mutex> _{device->BufferLock};
1131 if UNLIKELY(LookupBuffer(device, buffer) == nullptr)
1132 context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
1133 else if UNLIKELY(!values)
1134 context->setError(AL_INVALID_VALUE, "NULL pointer");
1135 else switch(param)
1137 default:
1138 context->setError(AL_INVALID_ENUM, "Invalid buffer float-vector property 0x%04x", param);
1141 END_API_FUNC
1144 AL_API void AL_APIENTRY alBufferi(ALuint buffer, ALenum param, ALint value)
1145 START_API_FUNC
1147 ContextRef context{GetContextRef()};
1148 if UNLIKELY(!context) return;
1150 ALCdevice *device{context->mDevice.get()};
1151 std::lock_guard<std::mutex> _{device->BufferLock};
1153 ALbuffer *albuf = LookupBuffer(device, buffer);
1154 if UNLIKELY(!albuf)
1155 context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
1156 else switch(param)
1158 case AL_UNPACK_BLOCK_ALIGNMENT_SOFT:
1159 if UNLIKELY(value < 0)
1160 context->setError(AL_INVALID_VALUE, "Invalid unpack block alignment %d", value);
1161 else
1162 albuf->UnpackAlign = static_cast<ALuint>(value);
1163 break;
1165 case AL_PACK_BLOCK_ALIGNMENT_SOFT:
1166 if UNLIKELY(value < 0)
1167 context->setError(AL_INVALID_VALUE, "Invalid pack block alignment %d", value);
1168 else
1169 albuf->PackAlign = static_cast<ALuint>(value);
1170 break;
1172 case AL_AMBISONIC_LAYOUT_SOFT:
1173 if UNLIKELY(ReadRef(albuf->ref) != 0)
1174 context->setError(AL_INVALID_OPERATION, "Modifying in-use buffer %u's ambisonic layout",
1175 buffer);
1176 else if UNLIKELY(value != AL_FUMA_SOFT && value != AL_ACN_SOFT)
1177 context->setError(AL_INVALID_VALUE, "Invalid unpack ambisonic layout %04x", value);
1178 else
1179 albuf->mBuffer.mAmbiLayout = static_cast<AmbiLayout>(value);
1180 break;
1182 case AL_AMBISONIC_SCALING_SOFT:
1183 if UNLIKELY(ReadRef(albuf->ref) != 0)
1184 context->setError(AL_INVALID_OPERATION, "Modifying in-use buffer %u's ambisonic scaling",
1185 buffer);
1186 else if UNLIKELY(value != AL_FUMA_SOFT && value != AL_SN3D_SOFT && value != AL_N3D_SOFT)
1187 context->setError(AL_INVALID_VALUE, "Invalid unpack ambisonic scaling %04x", value);
1188 else
1189 albuf->mBuffer.mAmbiScaling = static_cast<AmbiScaling>(value);
1190 break;
1192 case AL_UNPACK_AMBISONIC_ORDER_SOFT:
1193 if UNLIKELY(value < 1 || value > 14)
1194 context->setError(AL_INVALID_VALUE, "Invalid unpack ambisonic order %d", value);
1195 else
1196 albuf->UnpackAmbiOrder = static_cast<ALuint>(value);
1197 break;
1199 default:
1200 context->setError(AL_INVALID_ENUM, "Invalid buffer integer property 0x%04x", param);
1203 END_API_FUNC
1205 AL_API void AL_APIENTRY alBuffer3i(ALuint buffer, ALenum param,
1206 ALint /*value1*/, ALint /*value2*/, ALint /*value3*/)
1207 START_API_FUNC
1209 ContextRef context{GetContextRef()};
1210 if UNLIKELY(!context) return;
1212 ALCdevice *device{context->mDevice.get()};
1213 std::lock_guard<std::mutex> _{device->BufferLock};
1215 if UNLIKELY(LookupBuffer(device, buffer) == nullptr)
1216 context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
1217 else switch(param)
1219 default:
1220 context->setError(AL_INVALID_ENUM, "Invalid buffer 3-integer property 0x%04x", param);
1223 END_API_FUNC
1225 AL_API void AL_APIENTRY alBufferiv(ALuint buffer, ALenum param, const ALint *values)
1226 START_API_FUNC
1228 if(values)
1230 switch(param)
1232 case AL_UNPACK_BLOCK_ALIGNMENT_SOFT:
1233 case AL_PACK_BLOCK_ALIGNMENT_SOFT:
1234 case AL_AMBISONIC_LAYOUT_SOFT:
1235 case AL_AMBISONIC_SCALING_SOFT:
1236 case AL_UNPACK_AMBISONIC_ORDER_SOFT:
1237 alBufferi(buffer, param, values[0]);
1238 return;
1242 ContextRef context{GetContextRef()};
1243 if UNLIKELY(!context) return;
1245 ALCdevice *device{context->mDevice.get()};
1246 std::lock_guard<std::mutex> _{device->BufferLock};
1248 ALbuffer *albuf = LookupBuffer(device, buffer);
1249 if UNLIKELY(!albuf)
1250 context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
1251 else if UNLIKELY(!values)
1252 context->setError(AL_INVALID_VALUE, "NULL pointer");
1253 else switch(param)
1255 case AL_LOOP_POINTS_SOFT:
1256 if UNLIKELY(ReadRef(albuf->ref) != 0)
1257 context->setError(AL_INVALID_OPERATION, "Modifying in-use buffer %u's loop points",
1258 buffer);
1259 else if UNLIKELY(values[0] < 0 || values[0] >= values[1]
1260 || static_cast<ALuint>(values[1]) > albuf->mBuffer.mSampleLen)
1261 context->setError(AL_INVALID_VALUE, "Invalid loop point range %d -> %d on buffer %u",
1262 values[0], values[1], buffer);
1263 else
1265 albuf->LoopStart = static_cast<ALuint>(values[0]);
1266 albuf->LoopEnd = static_cast<ALuint>(values[1]);
1268 break;
1270 default:
1271 context->setError(AL_INVALID_ENUM, "Invalid buffer integer-vector property 0x%04x", param);
1274 END_API_FUNC
1277 AL_API void AL_APIENTRY alGetBufferf(ALuint buffer, ALenum param, ALfloat *value)
1278 START_API_FUNC
1280 ContextRef context{GetContextRef()};
1281 if UNLIKELY(!context) return;
1283 ALCdevice *device{context->mDevice.get()};
1284 std::lock_guard<std::mutex> _{device->BufferLock};
1286 ALbuffer *albuf = LookupBuffer(device, buffer);
1287 if UNLIKELY(!albuf)
1288 context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
1289 else if UNLIKELY(!value)
1290 context->setError(AL_INVALID_VALUE, "NULL pointer");
1291 else switch(param)
1293 default:
1294 context->setError(AL_INVALID_ENUM, "Invalid buffer float property 0x%04x", param);
1297 END_API_FUNC
1299 AL_API void AL_APIENTRY alGetBuffer3f(ALuint buffer, ALenum param, ALfloat *value1, ALfloat *value2, ALfloat *value3)
1300 START_API_FUNC
1302 ContextRef context{GetContextRef()};
1303 if UNLIKELY(!context) return;
1305 ALCdevice *device{context->mDevice.get()};
1306 std::lock_guard<std::mutex> _{device->BufferLock};
1308 if UNLIKELY(LookupBuffer(device, buffer) == nullptr)
1309 context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
1310 else if UNLIKELY(!value1 || !value2 || !value3)
1311 context->setError(AL_INVALID_VALUE, "NULL pointer");
1312 else switch(param)
1314 default:
1315 context->setError(AL_INVALID_ENUM, "Invalid buffer 3-float property 0x%04x", param);
1318 END_API_FUNC
1320 AL_API void AL_APIENTRY alGetBufferfv(ALuint buffer, ALenum param, ALfloat *values)
1321 START_API_FUNC
1323 switch(param)
1325 case AL_SEC_LENGTH_SOFT:
1326 alGetBufferf(buffer, param, values);
1327 return;
1330 ContextRef context{GetContextRef()};
1331 if UNLIKELY(!context) return;
1333 ALCdevice *device{context->mDevice.get()};
1334 std::lock_guard<std::mutex> _{device->BufferLock};
1336 if UNLIKELY(LookupBuffer(device, buffer) == nullptr)
1337 context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
1338 else if UNLIKELY(!values)
1339 context->setError(AL_INVALID_VALUE, "NULL pointer");
1340 else switch(param)
1342 default:
1343 context->setError(AL_INVALID_ENUM, "Invalid buffer float-vector property 0x%04x", param);
1346 END_API_FUNC
1349 AL_API void AL_APIENTRY alGetBufferi(ALuint buffer, ALenum param, ALint *value)
1350 START_API_FUNC
1352 ContextRef context{GetContextRef()};
1353 if UNLIKELY(!context) return;
1355 ALCdevice *device{context->mDevice.get()};
1356 std::lock_guard<std::mutex> _{device->BufferLock};
1357 ALbuffer *albuf = LookupBuffer(device, buffer);
1358 if UNLIKELY(!albuf)
1359 context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
1360 else if UNLIKELY(!value)
1361 context->setError(AL_INVALID_VALUE, "NULL pointer");
1362 else switch(param)
1364 case AL_FREQUENCY:
1365 *value = static_cast<ALint>(albuf->mBuffer.mSampleRate);
1366 break;
1368 case AL_BITS:
1369 *value = static_cast<ALint>(albuf->bytesFromFmt() * 8);
1370 break;
1372 case AL_CHANNELS:
1373 *value = static_cast<ALint>(albuf->channelsFromFmt());
1374 break;
1376 case AL_SIZE:
1377 *value = static_cast<ALint>(albuf->mBuffer.mSampleLen * albuf->frameSizeFromFmt());
1378 break;
1380 case AL_UNPACK_BLOCK_ALIGNMENT_SOFT:
1381 *value = static_cast<ALint>(albuf->UnpackAlign);
1382 break;
1384 case AL_PACK_BLOCK_ALIGNMENT_SOFT:
1385 *value = static_cast<ALint>(albuf->PackAlign);
1386 break;
1388 case AL_AMBISONIC_LAYOUT_SOFT:
1389 *value = static_cast<int>(albuf->mBuffer.mAmbiLayout);
1390 break;
1392 case AL_AMBISONIC_SCALING_SOFT:
1393 *value = static_cast<int>(albuf->mBuffer.mAmbiScaling);
1394 break;
1396 case AL_UNPACK_AMBISONIC_ORDER_SOFT:
1397 *value = static_cast<int>(albuf->UnpackAmbiOrder);
1398 break;
1400 default:
1401 context->setError(AL_INVALID_ENUM, "Invalid buffer integer property 0x%04x", param);
1404 END_API_FUNC
1406 AL_API void AL_APIENTRY alGetBuffer3i(ALuint buffer, ALenum param, ALint *value1, ALint *value2, ALint *value3)
1407 START_API_FUNC
1409 ContextRef context{GetContextRef()};
1410 if UNLIKELY(!context) return;
1412 ALCdevice *device{context->mDevice.get()};
1413 std::lock_guard<std::mutex> _{device->BufferLock};
1414 if UNLIKELY(LookupBuffer(device, buffer) == nullptr)
1415 context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
1416 else if UNLIKELY(!value1 || !value2 || !value3)
1417 context->setError(AL_INVALID_VALUE, "NULL pointer");
1418 else switch(param)
1420 default:
1421 context->setError(AL_INVALID_ENUM, "Invalid buffer 3-integer property 0x%04x", param);
1424 END_API_FUNC
1426 AL_API void AL_APIENTRY alGetBufferiv(ALuint buffer, ALenum param, ALint *values)
1427 START_API_FUNC
1429 switch(param)
1431 case AL_FREQUENCY:
1432 case AL_BITS:
1433 case AL_CHANNELS:
1434 case AL_SIZE:
1435 case AL_INTERNAL_FORMAT_SOFT:
1436 case AL_BYTE_LENGTH_SOFT:
1437 case AL_SAMPLE_LENGTH_SOFT:
1438 case AL_UNPACK_BLOCK_ALIGNMENT_SOFT:
1439 case AL_PACK_BLOCK_ALIGNMENT_SOFT:
1440 case AL_AMBISONIC_LAYOUT_SOFT:
1441 case AL_AMBISONIC_SCALING_SOFT:
1442 case AL_UNPACK_AMBISONIC_ORDER_SOFT:
1443 alGetBufferi(buffer, param, values);
1444 return;
1447 ContextRef context{GetContextRef()};
1448 if UNLIKELY(!context) return;
1450 ALCdevice *device{context->mDevice.get()};
1451 std::lock_guard<std::mutex> _{device->BufferLock};
1452 ALbuffer *albuf = LookupBuffer(device, buffer);
1453 if UNLIKELY(!albuf)
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 case AL_LOOP_POINTS_SOFT:
1460 values[0] = static_cast<ALint>(albuf->LoopStart);
1461 values[1] = static_cast<ALint>(albuf->LoopEnd);
1462 break;
1464 default:
1465 context->setError(AL_INVALID_ENUM, "Invalid buffer integer-vector property 0x%04x", param);
1468 END_API_FUNC
1471 AL_API void AL_APIENTRY alBufferCallbackSOFT(ALuint buffer, ALenum format, ALsizei freq,
1472 LPALBUFFERCALLBACKTYPESOFT callback, ALvoid *userptr, ALbitfieldSOFT flags)
1473 START_API_FUNC
1475 ContextRef context{GetContextRef()};
1476 if UNLIKELY(!context) return;
1478 ALCdevice *device{context->mDevice.get()};
1479 std::lock_guard<std::mutex> _{device->BufferLock};
1481 ALbuffer *albuf = LookupBuffer(device, buffer);
1482 if UNLIKELY(!albuf)
1483 context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
1484 else if UNLIKELY(freq < 1)
1485 context->setError(AL_INVALID_VALUE, "Invalid sample rate %d", freq);
1486 else if UNLIKELY(callback == nullptr)
1487 context->setError(AL_INVALID_VALUE, "NULL callback");
1488 else if UNLIKELY(flags != 0)
1489 context->setError(AL_INVALID_VALUE, "Invalid callback flags 0x%x", flags);
1490 else
1492 auto usrfmt = DecomposeUserFormat(format);
1493 if UNLIKELY(!usrfmt)
1494 context->setError(AL_INVALID_ENUM, "Invalid format 0x%04x", format);
1495 else
1496 PrepareCallback(context.get(), albuf, freq, usrfmt->channels, usrfmt->type, callback,
1497 userptr);
1500 END_API_FUNC
1502 AL_API void AL_APIENTRY alGetBufferPtrSOFT(ALuint buffer, ALenum param, ALvoid **value)
1503 START_API_FUNC
1505 ContextRef context{GetContextRef()};
1506 if UNLIKELY(!context) return;
1508 ALCdevice *device{context->mDevice.get()};
1509 std::lock_guard<std::mutex> _{device->BufferLock};
1510 ALbuffer *albuf = LookupBuffer(device, buffer);
1511 if UNLIKELY(!albuf)
1512 context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
1513 else if UNLIKELY(!value)
1514 context->setError(AL_INVALID_VALUE, "NULL pointer");
1515 else switch(param)
1517 case AL_BUFFER_CALLBACK_FUNCTION_SOFT:
1518 *value = reinterpret_cast<void*>(albuf->mBuffer.mCallback);
1519 break;
1520 case AL_BUFFER_CALLBACK_USER_PARAM_SOFT:
1521 *value = albuf->mBuffer.mUserData;
1522 break;
1524 default:
1525 context->setError(AL_INVALID_ENUM, "Invalid buffer pointer property 0x%04x", param);
1528 END_API_FUNC
1530 AL_API void AL_APIENTRY alGetBuffer3PtrSOFT(ALuint buffer, ALenum param, ALvoid **value1, ALvoid **value2, ALvoid **value3)
1531 START_API_FUNC
1533 ContextRef context{GetContextRef()};
1534 if UNLIKELY(!context) return;
1536 ALCdevice *device{context->mDevice.get()};
1537 std::lock_guard<std::mutex> _{device->BufferLock};
1538 if UNLIKELY(LookupBuffer(device, buffer) == nullptr)
1539 context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
1540 else if UNLIKELY(!value1 || !value2 || !value3)
1541 context->setError(AL_INVALID_VALUE, "NULL pointer");
1542 else switch(param)
1544 default:
1545 context->setError(AL_INVALID_ENUM, "Invalid buffer 3-pointer property 0x%04x", param);
1548 END_API_FUNC
1550 AL_API void AL_APIENTRY alGetBufferPtrvSOFT(ALuint buffer, ALenum param, ALvoid **values)
1551 START_API_FUNC
1553 switch(param)
1555 case AL_BUFFER_CALLBACK_FUNCTION_SOFT:
1556 case AL_BUFFER_CALLBACK_USER_PARAM_SOFT:
1557 alGetBufferPtrSOFT(buffer, param, values);
1558 return;
1561 ContextRef context{GetContextRef()};
1562 if UNLIKELY(!context) return;
1564 ALCdevice *device{context->mDevice.get()};
1565 std::lock_guard<std::mutex> _{device->BufferLock};
1566 if UNLIKELY(LookupBuffer(device, buffer) == nullptr)
1567 context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
1568 else if UNLIKELY(!values)
1569 context->setError(AL_INVALID_VALUE, "NULL pointer");
1570 else switch(param)
1572 default:
1573 context->setError(AL_INVALID_ENUM, "Invalid buffer pointer-vector property 0x%04x", param);
1576 END_API_FUNC
1579 BufferSubList::~BufferSubList()
1581 uint64_t usemask{~FreeMask};
1582 while(usemask)
1584 const ALsizei idx{CountTrailingZeros(usemask)};
1585 al::destroy_at(Buffers+idx);
1586 usemask &= ~(1_u64 << idx);
1588 FreeMask = ~usemask;
1589 al_free(Buffers);
1590 Buffers = nullptr;