Accumulate delays as samples before calculating nanoseconds
[openal-soft.git] / al / buffer.cpp
blobf43c756fa7767bf1246be8be17613a764a6ac12b
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>(POPCNT64(sublist.FreeMask)); }
292 while(needed > count)
294 if UNLIKELY(device->BufferList.size() >= 1<<25)
295 return false;
297 device->BufferList.emplace_back();
298 auto sublist = device->BufferList.end() - 1;
299 sublist->FreeMask = ~0_u64;
300 sublist->Buffers = static_cast<ALbuffer*>(al_calloc(alignof(ALbuffer), sizeof(ALbuffer)*64));
301 if UNLIKELY(!sublist->Buffers)
303 device->BufferList.pop_back();
304 return false;
306 count += 64;
308 return true;
311 ALbuffer *AllocBuffer(ALCdevice *device)
313 auto sublist = std::find_if(device->BufferList.begin(), device->BufferList.end(),
314 [](const BufferSubList &entry) noexcept -> bool
315 { return entry.FreeMask != 0; }
318 auto lidx = static_cast<ALuint>(std::distance(device->BufferList.begin(), sublist));
319 auto slidx = static_cast<ALuint>(CTZ64(sublist->FreeMask));
321 ALbuffer *buffer{::new (sublist->Buffers + slidx) ALbuffer{}};
323 /* Add 1 to avoid buffer ID 0. */
324 buffer->id = ((lidx<<6) | slidx) + 1;
326 sublist->FreeMask &= ~(1_u64 << slidx);
328 return buffer;
331 void FreeBuffer(ALCdevice *device, ALbuffer *buffer)
333 const ALuint id{buffer->id - 1};
334 const size_t lidx{id >> 6};
335 const ALuint slidx{id & 0x3f};
337 al::destroy_at(buffer);
339 device->BufferList[lidx].FreeMask |= 1_u64 << slidx;
342 inline ALbuffer *LookupBuffer(ALCdevice *device, ALuint id)
344 const size_t lidx{(id-1) >> 6};
345 const ALuint slidx{(id-1) & 0x3f};
347 if UNLIKELY(lidx >= device->BufferList.size())
348 return nullptr;
349 BufferSubList &sublist = device->BufferList[lidx];
350 if UNLIKELY(sublist.FreeMask & (1_u64 << slidx))
351 return nullptr;
352 return sublist.Buffers + slidx;
356 ALuint SanitizeAlignment(UserFmtType type, ALuint align)
358 if(align == 0)
360 if(type == UserFmtIMA4)
362 /* Here is where things vary:
363 * nVidia and Apple use 64+1 sample frames per block -> block_size=36 bytes per channel
364 * Most PC sound software uses 2040+1 sample frames per block -> block_size=1024 bytes per channel
366 return 65;
368 if(type == UserFmtMSADPCM)
369 return 64;
370 return 1;
373 if(type == UserFmtIMA4)
375 /* IMA4 block alignment must be a multiple of 8, plus 1. */
376 if((align&7) == 1) return static_cast<ALuint>(align);
377 return 0;
379 if(type == UserFmtMSADPCM)
381 /* MSADPCM block alignment must be a multiple of 2. */
382 if((align&1) == 0) return static_cast<ALuint>(align);
383 return 0;
386 return static_cast<ALuint>(align);
390 const ALchar *NameFromUserFmtType(UserFmtType type)
392 switch(type)
394 case UserFmtUByte: return "UInt8";
395 case UserFmtShort: return "Int16";
396 case UserFmtFloat: return "Float32";
397 case UserFmtDouble: return "Float64";
398 case UserFmtMulaw: return "muLaw";
399 case UserFmtAlaw: return "aLaw";
400 case UserFmtIMA4: return "IMA4 ADPCM";
401 case UserFmtMSADPCM: return "MSADPCM";
403 return "<internal type error>";
406 /** Loads the specified data into the buffer, using the specified format. */
407 void LoadData(ALCcontext *context, ALbuffer *ALBuf, ALsizei freq, ALuint size,
408 UserFmtChannels SrcChannels, UserFmtType SrcType, const al::byte *SrcData,
409 ALbitfieldSOFT access)
411 if UNLIKELY(ReadRef(ALBuf->ref) != 0 || ALBuf->MappedAccess != 0)
412 SETERR_RETURN(context, AL_INVALID_OPERATION,, "Modifying storage for in-use buffer %u",
413 ALBuf->id);
415 /* Currently no channel configurations need to be converted. */
416 FmtChannels DstChannels{FmtMono};
417 switch(SrcChannels)
419 case UserFmtMono: DstChannels = FmtMono; break;
420 case UserFmtStereo: DstChannels = FmtStereo; break;
421 case UserFmtRear: DstChannels = FmtRear; break;
422 case UserFmtQuad: DstChannels = FmtQuad; break;
423 case UserFmtX51: DstChannels = FmtX51; break;
424 case UserFmtX61: DstChannels = FmtX61; break;
425 case UserFmtX71: DstChannels = FmtX71; break;
426 case UserFmtBFormat2D: DstChannels = FmtBFormat2D; break;
427 case UserFmtBFormat3D: DstChannels = FmtBFormat3D; break;
429 if UNLIKELY(static_cast<long>(SrcChannels) != static_cast<long>(DstChannels))
430 SETERR_RETURN(context, AL_INVALID_ENUM, , "Invalid format");
432 /* IMA4 and MSADPCM convert to 16-bit short. */
433 FmtType DstType{FmtUByte};
434 switch(SrcType)
436 case UserFmtUByte: DstType = FmtUByte; break;
437 case UserFmtShort: DstType = FmtShort; break;
438 case UserFmtFloat: DstType = FmtFloat; break;
439 case UserFmtDouble: DstType = FmtDouble; break;
440 case UserFmtAlaw: DstType = FmtAlaw; break;
441 case UserFmtMulaw: DstType = FmtMulaw; break;
442 case UserFmtIMA4: DstType = FmtShort; break;
443 case UserFmtMSADPCM: DstType = FmtShort; break;
446 /* TODO: Currently we can only map samples when they're not converted. To
447 * allow it would need some kind of double-buffering to hold onto a copy of
448 * the original data.
450 if((access&MAP_READ_WRITE_FLAGS))
452 if UNLIKELY(static_cast<long>(SrcType) != static_cast<long>(DstType))
453 SETERR_RETURN(context, AL_INVALID_VALUE,, "%s samples cannot be mapped",
454 NameFromUserFmtType(SrcType));
457 const ALuint unpackalign{ALBuf->UnpackAlign};
458 const ALuint align{SanitizeAlignment(SrcType, unpackalign)};
459 if UNLIKELY(align < 1)
460 SETERR_RETURN(context, AL_INVALID_VALUE,, "Invalid unpack alignment %u for %s samples",
461 unpackalign, NameFromUserFmtType(SrcType));
463 const ALuint ambiorder{(DstChannels == FmtBFormat2D || DstChannels == FmtBFormat3D) ?
464 ALBuf->UnpackAmbiOrder : 0};
466 if((access&AL_PRESERVE_DATA_BIT_SOFT))
468 /* Can only preserve data with the same format and alignment. */
469 if UNLIKELY(ALBuf->mBuffer.mChannels != DstChannels || ALBuf->OriginalType != SrcType)
470 SETERR_RETURN(context, AL_INVALID_VALUE,, "Preserving data of mismatched format");
471 if UNLIKELY(ALBuf->OriginalAlign != align)
472 SETERR_RETURN(context, AL_INVALID_VALUE,, "Preserving data of mismatched alignment");
473 if(ALBuf->mBuffer.mAmbiOrder != ambiorder)
474 SETERR_RETURN(context, AL_INVALID_VALUE,, "Preserving data of mismatched order");
477 /* Convert the input/source size in bytes to sample frames using the unpack
478 * block alignment.
480 const ALuint SrcByteAlign{ChannelsFromUserFmt(SrcChannels, ambiorder) *
481 ((SrcType == UserFmtIMA4) ? (align-1)/2 + 4 :
482 (SrcType == UserFmtMSADPCM) ? (align-2)/2 + 7 :
483 (align * BytesFromUserFmt(SrcType)))};
484 if UNLIKELY((size%SrcByteAlign) != 0)
485 SETERR_RETURN(context, AL_INVALID_VALUE,,
486 "Data size %d is not a multiple of frame size %d (%d unpack alignment)",
487 size, SrcByteAlign, align);
489 if UNLIKELY(size/SrcByteAlign > std::numeric_limits<ALsizei>::max()/align)
490 SETERR_RETURN(context, AL_OUT_OF_MEMORY,,
491 "Buffer size overflow, %d blocks x %d samples per block", size/SrcByteAlign, align);
492 const ALuint frames{size / SrcByteAlign * align};
494 /* Convert the sample frames to the number of bytes needed for internal
495 * storage.
497 ALuint NumChannels{ChannelsFromFmt(DstChannels, ambiorder)};
498 ALuint FrameSize{NumChannels * BytesFromFmt(DstType)};
499 if UNLIKELY(frames > std::numeric_limits<size_t>::max()/FrameSize)
500 SETERR_RETURN(context, AL_OUT_OF_MEMORY,,
501 "Buffer size overflow, %d frames x %d bytes per frame", frames, FrameSize);
502 size_t newsize{static_cast<size_t>(frames) * FrameSize};
504 /* Round up to the next 16-byte multiple. This could reallocate only when
505 * increasing or the new size is less than half the current, but then the
506 * buffer's AL_SIZE would not be very reliable for accounting buffer memory
507 * usage, and reporting the real size could cause problems for apps that
508 * use AL_SIZE to try to get the buffer's play length.
510 newsize = RoundUp(newsize, 16);
511 if(newsize != ALBuf->mBuffer.mData.size())
513 auto newdata = al::vector<al::byte,16>(newsize, al::byte{});
514 if((access&AL_PRESERVE_DATA_BIT_SOFT))
516 const size_t tocopy{minz(newdata.size(), ALBuf->mBuffer.mData.size())};
517 std::copy_n(ALBuf->mBuffer.mData.begin(), tocopy, newdata.begin());
519 newdata.swap(ALBuf->mBuffer.mData);
522 if(SrcType == UserFmtIMA4)
524 assert(DstType == FmtShort);
525 if(SrcData != nullptr && !ALBuf->mBuffer.mData.empty())
526 Convert_int16_ima4(reinterpret_cast<int16_t*>(ALBuf->mBuffer.mData.data()), SrcData,
527 NumChannels, frames, align);
528 ALBuf->OriginalAlign = align;
530 else if(SrcType == UserFmtMSADPCM)
532 assert(DstType == FmtShort);
533 if(SrcData != nullptr && !ALBuf->mBuffer.mData.empty())
534 Convert_int16_msadpcm(reinterpret_cast<int16_t*>(ALBuf->mBuffer.mData.data()), SrcData,
535 NumChannels, frames, align);
536 ALBuf->OriginalAlign = align;
538 else
540 assert(static_cast<long>(SrcType) == static_cast<long>(DstType));
541 if(SrcData != nullptr && !ALBuf->mBuffer.mData.empty())
542 std::copy_n(SrcData, frames*FrameSize, ALBuf->mBuffer.mData.begin());
543 ALBuf->OriginalAlign = 1;
545 ALBuf->OriginalSize = size;
546 ALBuf->OriginalType = SrcType;
548 ALBuf->mBuffer.mSampleRate = static_cast<ALuint>(freq);
549 ALBuf->mBuffer.mChannels = DstChannels;
550 ALBuf->mBuffer.mType = DstType;
551 ALBuf->Access = access;
552 ALBuf->mBuffer.mAmbiOrder = ambiorder;
554 ALBuf->mBuffer.mCallback = nullptr;
555 ALBuf->mBuffer.mUserData = nullptr;
557 ALBuf->mBuffer.mSampleLen = frames;
558 ALBuf->LoopStart = 0;
559 ALBuf->LoopEnd = ALBuf->mBuffer.mSampleLen;
562 /** Prepares the buffer to use the specified callback, using the specified format. */
563 void PrepareCallback(ALCcontext *context, ALbuffer *ALBuf, ALsizei freq,
564 UserFmtChannels SrcChannels, UserFmtType SrcType, LPALBUFFERCALLBACKTYPESOFT callback,
565 void *userptr)
567 if UNLIKELY(ReadRef(ALBuf->ref) != 0 || ALBuf->MappedAccess != 0)
568 SETERR_RETURN(context, AL_INVALID_OPERATION,, "Modifying callback for in-use buffer %u",
569 ALBuf->id);
571 /* Currently no channel configurations need to be converted. */
572 FmtChannels DstChannels{FmtMono};
573 switch(SrcChannels)
575 case UserFmtMono: DstChannels = FmtMono; break;
576 case UserFmtStereo: DstChannels = FmtStereo; break;
577 case UserFmtRear: DstChannels = FmtRear; break;
578 case UserFmtQuad: DstChannels = FmtQuad; break;
579 case UserFmtX51: DstChannels = FmtX51; break;
580 case UserFmtX61: DstChannels = FmtX61; break;
581 case UserFmtX71: DstChannels = FmtX71; break;
582 case UserFmtBFormat2D: DstChannels = FmtBFormat2D; break;
583 case UserFmtBFormat3D: DstChannels = FmtBFormat3D; break;
585 if UNLIKELY(static_cast<long>(SrcChannels) != static_cast<long>(DstChannels))
586 SETERR_RETURN(context, AL_INVALID_ENUM,, "Invalid format");
588 /* IMA4 and MSADPCM convert to 16-bit short. Not supported with callbacks. */
589 FmtType DstType{FmtUByte};
590 switch(SrcType)
592 case UserFmtUByte: DstType = FmtUByte; break;
593 case UserFmtShort: DstType = FmtShort; break;
594 case UserFmtFloat: DstType = FmtFloat; break;
595 case UserFmtDouble: DstType = FmtDouble; break;
596 case UserFmtAlaw: DstType = FmtAlaw; break;
597 case UserFmtMulaw: DstType = FmtMulaw; break;
598 case UserFmtIMA4: DstType = FmtShort; break;
599 case UserFmtMSADPCM: DstType = FmtShort; break;
601 if UNLIKELY(static_cast<long>(SrcType) != static_cast<long>(DstType))
602 SETERR_RETURN(context, AL_INVALID_ENUM,, "Unsupported callback format");
604 const ALuint ambiorder{(DstChannels == FmtBFormat2D || DstChannels == FmtBFormat3D) ?
605 ALBuf->UnpackAmbiOrder : 0};
607 al::vector<al::byte,16>(FrameSizeFromFmt(DstChannels, DstType, ambiorder) *
608 size_t{BUFFERSIZE + (MAX_RESAMPLER_PADDING>>1)}).swap(ALBuf->mBuffer.mData);
610 ALBuf->mBuffer.mCallback = callback;
611 ALBuf->mBuffer.mUserData = userptr;
613 ALBuf->OriginalType = SrcType;
614 ALBuf->OriginalSize = 0;
615 ALBuf->OriginalAlign = 1;
617 ALBuf->mBuffer.mSampleRate = static_cast<ALuint>(freq);
618 ALBuf->mBuffer.mChannels = DstChannels;
619 ALBuf->mBuffer.mType = DstType;
620 ALBuf->Access = 0;
621 ALBuf->mBuffer.mAmbiOrder = ambiorder;
623 ALBuf->mBuffer.mSampleLen = 0;
624 ALBuf->LoopStart = 0;
625 ALBuf->LoopEnd = ALBuf->mBuffer.mSampleLen;
629 struct DecompResult { UserFmtChannels channels; UserFmtType type; };
630 al::optional<DecompResult> DecomposeUserFormat(ALenum format)
632 struct FormatMap {
633 ALenum format;
634 UserFmtChannels channels;
635 UserFmtType type;
637 static const std::array<FormatMap,46> UserFmtList{{
638 { AL_FORMAT_MONO8, UserFmtMono, UserFmtUByte },
639 { AL_FORMAT_MONO16, UserFmtMono, UserFmtShort },
640 { AL_FORMAT_MONO_FLOAT32, UserFmtMono, UserFmtFloat },
641 { AL_FORMAT_MONO_DOUBLE_EXT, UserFmtMono, UserFmtDouble },
642 { AL_FORMAT_MONO_IMA4, UserFmtMono, UserFmtIMA4 },
643 { AL_FORMAT_MONO_MSADPCM_SOFT, UserFmtMono, UserFmtMSADPCM },
644 { AL_FORMAT_MONO_MULAW, UserFmtMono, UserFmtMulaw },
645 { AL_FORMAT_MONO_ALAW_EXT, UserFmtMono, UserFmtAlaw },
647 { AL_FORMAT_STEREO8, UserFmtStereo, UserFmtUByte },
648 { AL_FORMAT_STEREO16, UserFmtStereo, UserFmtShort },
649 { AL_FORMAT_STEREO_FLOAT32, UserFmtStereo, UserFmtFloat },
650 { AL_FORMAT_STEREO_DOUBLE_EXT, UserFmtStereo, UserFmtDouble },
651 { AL_FORMAT_STEREO_IMA4, UserFmtStereo, UserFmtIMA4 },
652 { AL_FORMAT_STEREO_MSADPCM_SOFT, UserFmtStereo, UserFmtMSADPCM },
653 { AL_FORMAT_STEREO_MULAW, UserFmtStereo, UserFmtMulaw },
654 { AL_FORMAT_STEREO_ALAW_EXT, UserFmtStereo, UserFmtAlaw },
656 { AL_FORMAT_REAR8, UserFmtRear, UserFmtUByte },
657 { AL_FORMAT_REAR16, UserFmtRear, UserFmtShort },
658 { AL_FORMAT_REAR32, UserFmtRear, UserFmtFloat },
659 { AL_FORMAT_REAR_MULAW, UserFmtRear, UserFmtMulaw },
661 { AL_FORMAT_QUAD8_LOKI, UserFmtQuad, UserFmtUByte },
662 { AL_FORMAT_QUAD16_LOKI, UserFmtQuad, UserFmtShort },
664 { AL_FORMAT_QUAD8, UserFmtQuad, UserFmtUByte },
665 { AL_FORMAT_QUAD16, UserFmtQuad, UserFmtShort },
666 { AL_FORMAT_QUAD32, UserFmtQuad, UserFmtFloat },
667 { AL_FORMAT_QUAD_MULAW, UserFmtQuad, UserFmtMulaw },
669 { AL_FORMAT_51CHN8, UserFmtX51, UserFmtUByte },
670 { AL_FORMAT_51CHN16, UserFmtX51, UserFmtShort },
671 { AL_FORMAT_51CHN32, UserFmtX51, UserFmtFloat },
672 { AL_FORMAT_51CHN_MULAW, UserFmtX51, UserFmtMulaw },
674 { AL_FORMAT_61CHN8, UserFmtX61, UserFmtUByte },
675 { AL_FORMAT_61CHN16, UserFmtX61, UserFmtShort },
676 { AL_FORMAT_61CHN32, UserFmtX61, UserFmtFloat },
677 { AL_FORMAT_61CHN_MULAW, UserFmtX61, UserFmtMulaw },
679 { AL_FORMAT_71CHN8, UserFmtX71, UserFmtUByte },
680 { AL_FORMAT_71CHN16, UserFmtX71, UserFmtShort },
681 { AL_FORMAT_71CHN32, UserFmtX71, UserFmtFloat },
682 { AL_FORMAT_71CHN_MULAW, UserFmtX71, UserFmtMulaw },
684 { AL_FORMAT_BFORMAT2D_8, UserFmtBFormat2D, UserFmtUByte },
685 { AL_FORMAT_BFORMAT2D_16, UserFmtBFormat2D, UserFmtShort },
686 { AL_FORMAT_BFORMAT2D_FLOAT32, UserFmtBFormat2D, UserFmtFloat },
687 { AL_FORMAT_BFORMAT2D_MULAW, UserFmtBFormat2D, UserFmtMulaw },
689 { AL_FORMAT_BFORMAT3D_8, UserFmtBFormat3D, UserFmtUByte },
690 { AL_FORMAT_BFORMAT3D_16, UserFmtBFormat3D, UserFmtShort },
691 { AL_FORMAT_BFORMAT3D_FLOAT32, UserFmtBFormat3D, UserFmtFloat },
692 { AL_FORMAT_BFORMAT3D_MULAW, UserFmtBFormat3D, UserFmtMulaw },
695 for(const auto &fmt : UserFmtList)
697 if(fmt.format == format)
698 return al::make_optional<DecompResult>({fmt.channels, fmt.type});
700 return al::nullopt;
703 } // namespace
706 AL_API void AL_APIENTRY alGenBuffers(ALsizei n, ALuint *buffers)
707 START_API_FUNC
709 ContextRef context{GetContextRef()};
710 if UNLIKELY(!context) return;
712 if UNLIKELY(n < 0)
713 context->setError(AL_INVALID_VALUE, "Generating %d buffers", n);
714 if UNLIKELY(n <= 0) return;
716 ALCdevice *device{context->mDevice.get()};
717 std::lock_guard<std::mutex> _{device->BufferLock};
718 if(!EnsureBuffers(device, static_cast<ALuint>(n)))
720 context->setError(AL_OUT_OF_MEMORY, "Failed to allocate %d buffer%s", n, (n==1)?"":"s");
721 return;
724 if LIKELY(n == 1)
726 /* Special handling for the easy and normal case. */
727 ALbuffer *buffer{AllocBuffer(device)};
728 buffers[0] = buffer->id;
730 else
732 /* Store the allocated buffer IDs in a separate local list, to avoid
733 * modifying the user storage in case of failure.
735 al::vector<ALuint> ids;
736 ids.reserve(static_cast<ALuint>(n));
737 do {
738 ALbuffer *buffer{AllocBuffer(device)};
739 ids.emplace_back(buffer->id);
740 } while(--n);
741 std::copy(ids.begin(), ids.end(), buffers);
744 END_API_FUNC
746 AL_API void AL_APIENTRY alDeleteBuffers(ALsizei n, const ALuint *buffers)
747 START_API_FUNC
749 ContextRef context{GetContextRef()};
750 if UNLIKELY(!context) return;
752 if UNLIKELY(n < 0)
753 context->setError(AL_INVALID_VALUE, "Deleting %d buffers", n);
754 if UNLIKELY(n <= 0) return;
756 ALCdevice *device{context->mDevice.get()};
757 std::lock_guard<std::mutex> _{device->BufferLock};
759 /* First try to find any buffers that are invalid or in-use. */
760 auto validate_buffer = [device, &context](const ALuint bid) -> bool
762 if(!bid) return true;
763 ALbuffer *ALBuf{LookupBuffer(device, bid)};
764 if UNLIKELY(!ALBuf)
766 context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", bid);
767 return false;
769 if UNLIKELY(ReadRef(ALBuf->ref) != 0)
771 context->setError(AL_INVALID_OPERATION, "Deleting in-use buffer %u", bid);
772 return false;
774 return true;
776 const ALuint *buffers_end = buffers + n;
777 auto invbuf = std::find_if_not(buffers, buffers_end, validate_buffer);
778 if UNLIKELY(invbuf != buffers_end) return;
780 /* All good. Delete non-0 buffer IDs. */
781 auto delete_buffer = [device](const ALuint bid) -> void
783 ALbuffer *buffer{bid ? LookupBuffer(device, bid) : nullptr};
784 if(buffer) FreeBuffer(device, buffer);
786 std::for_each(buffers, buffers_end, delete_buffer);
788 END_API_FUNC
790 AL_API ALboolean AL_APIENTRY alIsBuffer(ALuint buffer)
791 START_API_FUNC
793 ContextRef context{GetContextRef()};
794 if LIKELY(context)
796 ALCdevice *device{context->mDevice.get()};
797 std::lock_guard<std::mutex> _{device->BufferLock};
798 if(!buffer || LookupBuffer(device, buffer))
799 return AL_TRUE;
801 return AL_FALSE;
803 END_API_FUNC
806 AL_API void AL_APIENTRY alBufferData(ALuint buffer, ALenum format, const ALvoid *data, ALsizei size, ALsizei freq)
807 START_API_FUNC
808 { alBufferStorageSOFT(buffer, format, data, size, freq, 0); }
809 END_API_FUNC
811 AL_API void AL_APIENTRY alBufferStorageSOFT(ALuint buffer, ALenum format, const ALvoid *data, ALsizei size, ALsizei freq, ALbitfieldSOFT flags)
812 START_API_FUNC
814 ContextRef context{GetContextRef()};
815 if UNLIKELY(!context) return;
817 ALCdevice *device{context->mDevice.get()};
818 std::lock_guard<std::mutex> _{device->BufferLock};
820 ALbuffer *albuf = LookupBuffer(device, buffer);
821 if UNLIKELY(!albuf)
822 context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
823 else if UNLIKELY(size < 0)
824 context->setError(AL_INVALID_VALUE, "Negative storage size %d", size);
825 else if UNLIKELY(freq < 1)
826 context->setError(AL_INVALID_VALUE, "Invalid sample rate %d", freq);
827 else if UNLIKELY((flags&INVALID_STORAGE_MASK) != 0)
828 context->setError(AL_INVALID_VALUE, "Invalid storage flags 0x%x",
829 flags&INVALID_STORAGE_MASK);
830 else if UNLIKELY((flags&AL_MAP_PERSISTENT_BIT_SOFT) && !(flags&MAP_READ_WRITE_FLAGS))
831 context->setError(AL_INVALID_VALUE,
832 "Declaring persistently mapped storage without read or write access");
833 else
835 auto usrfmt = DecomposeUserFormat(format);
836 if UNLIKELY(!usrfmt)
837 context->setError(AL_INVALID_ENUM, "Invalid format 0x%04x", format);
838 else
839 LoadData(context.get(), albuf, freq, static_cast<ALuint>(size), usrfmt->channels,
840 usrfmt->type, static_cast<const al::byte*>(data), flags);
843 END_API_FUNC
845 AL_API void* AL_APIENTRY alMapBufferSOFT(ALuint buffer, ALsizei offset, ALsizei length, ALbitfieldSOFT access)
846 START_API_FUNC
848 ContextRef context{GetContextRef()};
849 if UNLIKELY(!context) return nullptr;
851 ALCdevice *device{context->mDevice.get()};
852 std::lock_guard<std::mutex> _{device->BufferLock};
854 ALbuffer *albuf = LookupBuffer(device, buffer);
855 if UNLIKELY(!albuf)
856 context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
857 else if UNLIKELY((access&INVALID_MAP_FLAGS) != 0)
858 context->setError(AL_INVALID_VALUE, "Invalid map flags 0x%x", access&INVALID_MAP_FLAGS);
859 else if UNLIKELY(!(access&MAP_READ_WRITE_FLAGS))
860 context->setError(AL_INVALID_VALUE, "Mapping buffer %u without read or write access",
861 buffer);
862 else
864 ALbitfieldSOFT unavailable = (albuf->Access^access) & access;
865 if UNLIKELY(ReadRef(albuf->ref) != 0 && !(access&AL_MAP_PERSISTENT_BIT_SOFT))
866 context->setError(AL_INVALID_OPERATION,
867 "Mapping in-use buffer %u without persistent mapping", buffer);
868 else if UNLIKELY(albuf->MappedAccess != 0)
869 context->setError(AL_INVALID_OPERATION, "Mapping already-mapped buffer %u", buffer);
870 else if UNLIKELY((unavailable&AL_MAP_READ_BIT_SOFT))
871 context->setError(AL_INVALID_VALUE,
872 "Mapping buffer %u for reading without read access", buffer);
873 else if UNLIKELY((unavailable&AL_MAP_WRITE_BIT_SOFT))
874 context->setError(AL_INVALID_VALUE,
875 "Mapping buffer %u for writing without write access", buffer);
876 else if UNLIKELY((unavailable&AL_MAP_PERSISTENT_BIT_SOFT))
877 context->setError(AL_INVALID_VALUE,
878 "Mapping buffer %u persistently without persistent access", buffer);
879 else if UNLIKELY(offset < 0 || length <= 0
880 || static_cast<ALuint>(offset) >= albuf->OriginalSize
881 || static_cast<ALuint>(length) > albuf->OriginalSize - static_cast<ALuint>(offset))
882 context->setError(AL_INVALID_VALUE, "Mapping invalid range %d+%d for buffer %u",
883 offset, length, buffer);
884 else
886 void *retval{albuf->mBuffer.mData.data() + offset};
887 albuf->MappedAccess = access;
888 albuf->MappedOffset = offset;
889 albuf->MappedSize = length;
890 return retval;
894 return nullptr;
896 END_API_FUNC
898 AL_API void AL_APIENTRY alUnmapBufferSOFT(ALuint buffer)
899 START_API_FUNC
901 ContextRef context{GetContextRef()};
902 if UNLIKELY(!context) return;
904 ALCdevice *device{context->mDevice.get()};
905 std::lock_guard<std::mutex> _{device->BufferLock};
907 ALbuffer *albuf = LookupBuffer(device, buffer);
908 if UNLIKELY(!albuf)
909 context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
910 else if UNLIKELY(albuf->MappedAccess == 0)
911 context->setError(AL_INVALID_OPERATION, "Unmapping unmapped buffer %u", buffer);
912 else
914 albuf->MappedAccess = 0;
915 albuf->MappedOffset = 0;
916 albuf->MappedSize = 0;
919 END_API_FUNC
921 AL_API void AL_APIENTRY alFlushMappedBufferSOFT(ALuint buffer, ALsizei offset, ALsizei length)
922 START_API_FUNC
924 ContextRef context{GetContextRef()};
925 if UNLIKELY(!context) return;
927 ALCdevice *device{context->mDevice.get()};
928 std::lock_guard<std::mutex> _{device->BufferLock};
930 ALbuffer *albuf = LookupBuffer(device, buffer);
931 if UNLIKELY(!albuf)
932 context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
933 else if UNLIKELY(!(albuf->MappedAccess&AL_MAP_WRITE_BIT_SOFT))
934 context->setError(AL_INVALID_OPERATION, "Flushing buffer %u while not mapped for writing",
935 buffer);
936 else if UNLIKELY(offset < albuf->MappedOffset || length <= 0
937 || offset >= albuf->MappedOffset+albuf->MappedSize
938 || length > albuf->MappedOffset+albuf->MappedSize-offset)
939 context->setError(AL_INVALID_VALUE, "Flushing invalid range %d+%d on buffer %u", offset,
940 length, buffer);
941 else
943 /* FIXME: Need to use some method of double-buffering for the mixer and
944 * app to hold separate memory, which can be safely transfered
945 * asynchronously. Currently we just say the app shouldn't write where
946 * OpenAL's reading, and hope for the best...
948 std::atomic_thread_fence(std::memory_order_seq_cst);
951 END_API_FUNC
953 AL_API void AL_APIENTRY alBufferSubDataSOFT(ALuint buffer, ALenum format, const ALvoid *data, ALsizei offset, ALsizei length)
954 START_API_FUNC
956 ContextRef context{GetContextRef()};
957 if UNLIKELY(!context) return;
959 ALCdevice *device{context->mDevice.get()};
960 std::lock_guard<std::mutex> _{device->BufferLock};
962 ALbuffer *albuf = LookupBuffer(device, buffer);
963 if UNLIKELY(!albuf)
965 context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
966 return;
969 auto usrfmt = DecomposeUserFormat(format);
970 if UNLIKELY(!usrfmt)
972 context->setError(AL_INVALID_ENUM, "Invalid format 0x%04x", format);
973 return;
976 ALuint unpack_align{albuf->UnpackAlign};
977 ALuint align{SanitizeAlignment(usrfmt->type, unpack_align)};
978 if UNLIKELY(align < 1)
979 context->setError(AL_INVALID_VALUE, "Invalid unpack alignment %u", unpack_align);
980 else if UNLIKELY(long{usrfmt->channels} != long{albuf->mBuffer.mChannels}
981 || usrfmt->type != albuf->OriginalType)
982 context->setError(AL_INVALID_ENUM, "Unpacking data with mismatched format");
983 else if UNLIKELY(align != albuf->OriginalAlign)
984 context->setError(AL_INVALID_VALUE,
985 "Unpacking data with alignment %u does not match original alignment %u", align,
986 albuf->OriginalAlign);
987 else if UNLIKELY(albuf->mBuffer.isBFormat()
988 && albuf->UnpackAmbiOrder != albuf->mBuffer.mAmbiOrder)
989 context->setError(AL_INVALID_VALUE, "Unpacking data with mismatched ambisonic order");
990 else if UNLIKELY(albuf->MappedAccess != 0)
991 context->setError(AL_INVALID_OPERATION, "Unpacking data into mapped buffer %u", buffer);
992 else
994 ALuint num_chans{albuf->channelsFromFmt()};
995 ALuint frame_size{num_chans * albuf->bytesFromFmt()};
996 ALuint byte_align{
997 (albuf->OriginalType == UserFmtIMA4) ? ((align-1)/2 + 4) * num_chans :
998 (albuf->OriginalType == UserFmtMSADPCM) ? ((align-2)/2 + 7) * num_chans :
999 (align * frame_size)
1002 if UNLIKELY(offset < 0 || length < 0 || static_cast<ALuint>(offset) > albuf->OriginalSize
1003 || static_cast<ALuint>(length) > albuf->OriginalSize-static_cast<ALuint>(offset))
1004 context->setError(AL_INVALID_VALUE, "Invalid data sub-range %d+%d on buffer %u",
1005 offset, length, buffer);
1006 else if UNLIKELY((static_cast<ALuint>(offset)%byte_align) != 0)
1007 context->setError(AL_INVALID_VALUE,
1008 "Sub-range offset %d is not a multiple of frame size %d (%d unpack alignment)",
1009 offset, byte_align, align);
1010 else if UNLIKELY((static_cast<ALuint>(length)%byte_align) != 0)
1011 context->setError(AL_INVALID_VALUE,
1012 "Sub-range length %d is not a multiple of frame size %d (%d unpack alignment)",
1013 length, byte_align, align);
1014 else
1016 /* offset -> byte offset, length -> sample count */
1017 size_t byteoff{static_cast<ALuint>(offset)/byte_align * align * frame_size};
1018 size_t samplen{static_cast<ALuint>(length)/byte_align * align};
1020 void *dst = albuf->mBuffer.mData.data() + byteoff;
1021 if(usrfmt->type == UserFmtIMA4 && albuf->mBuffer.mType == FmtShort)
1022 Convert_int16_ima4(static_cast<int16_t*>(dst), static_cast<const al::byte*>(data),
1023 num_chans, samplen, align);
1024 else if(usrfmt->type == UserFmtMSADPCM && albuf->mBuffer.mType == FmtShort)
1025 Convert_int16_msadpcm(static_cast<int16_t*>(dst),
1026 static_cast<const al::byte*>(data), num_chans, samplen, align);
1027 else
1029 assert(long{usrfmt->type} == long{albuf->mBuffer.mType});
1030 memcpy(dst, data, size_t{samplen} * frame_size);
1035 END_API_FUNC
1038 AL_API void AL_APIENTRY alBufferSamplesSOFT(ALuint /*buffer*/, ALuint /*samplerate*/,
1039 ALenum /*internalformat*/, ALsizei /*samples*/, ALenum /*channels*/, ALenum /*type*/,
1040 const ALvoid* /*data*/)
1041 START_API_FUNC
1043 ContextRef context{GetContextRef()};
1044 if UNLIKELY(!context) return;
1046 context->setError(AL_INVALID_OPERATION, "alBufferSamplesSOFT not supported");
1048 END_API_FUNC
1050 AL_API void AL_APIENTRY alBufferSubSamplesSOFT(ALuint /*buffer*/, ALsizei /*offset*/,
1051 ALsizei /*samples*/, ALenum /*channels*/, ALenum /*type*/, const ALvoid* /*data*/)
1052 START_API_FUNC
1054 ContextRef context{GetContextRef()};
1055 if UNLIKELY(!context) return;
1057 context->setError(AL_INVALID_OPERATION, "alBufferSubSamplesSOFT not supported");
1059 END_API_FUNC
1061 AL_API void AL_APIENTRY alGetBufferSamplesSOFT(ALuint /*buffer*/, ALsizei /*offset*/,
1062 ALsizei /*samples*/, ALenum /*channels*/, ALenum /*type*/, ALvoid* /*data*/)
1063 START_API_FUNC
1065 ContextRef context{GetContextRef()};
1066 if UNLIKELY(!context) return;
1068 context->setError(AL_INVALID_OPERATION, "alGetBufferSamplesSOFT not supported");
1070 END_API_FUNC
1072 AL_API ALboolean AL_APIENTRY alIsBufferFormatSupportedSOFT(ALenum /*format*/)
1073 START_API_FUNC
1075 ContextRef context{GetContextRef()};
1076 if UNLIKELY(!context) return AL_FALSE;
1078 context->setError(AL_INVALID_OPERATION, "alIsBufferFormatSupportedSOFT not supported");
1079 return AL_FALSE;
1081 END_API_FUNC
1084 AL_API void AL_APIENTRY alBufferf(ALuint buffer, ALenum param, ALfloat /*value*/)
1085 START_API_FUNC
1087 ContextRef context{GetContextRef()};
1088 if UNLIKELY(!context) return;
1090 ALCdevice *device{context->mDevice.get()};
1091 std::lock_guard<std::mutex> _{device->BufferLock};
1093 if UNLIKELY(LookupBuffer(device, buffer) == nullptr)
1094 context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
1095 else switch(param)
1097 default:
1098 context->setError(AL_INVALID_ENUM, "Invalid buffer float property 0x%04x", param);
1101 END_API_FUNC
1103 AL_API void AL_APIENTRY alBuffer3f(ALuint buffer, ALenum param,
1104 ALfloat /*value1*/, ALfloat /*value2*/, ALfloat /*value3*/)
1105 START_API_FUNC
1107 ContextRef context{GetContextRef()};
1108 if UNLIKELY(!context) return;
1110 ALCdevice *device{context->mDevice.get()};
1111 std::lock_guard<std::mutex> _{device->BufferLock};
1113 if UNLIKELY(LookupBuffer(device, buffer) == nullptr)
1114 context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
1115 else switch(param)
1117 default:
1118 context->setError(AL_INVALID_ENUM, "Invalid buffer 3-float property 0x%04x", param);
1121 END_API_FUNC
1123 AL_API void AL_APIENTRY alBufferfv(ALuint buffer, ALenum param, const ALfloat *values)
1124 START_API_FUNC
1126 ContextRef context{GetContextRef()};
1127 if UNLIKELY(!context) return;
1129 ALCdevice *device{context->mDevice.get()};
1130 std::lock_guard<std::mutex> _{device->BufferLock};
1132 if UNLIKELY(LookupBuffer(device, buffer) == nullptr)
1133 context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
1134 else if UNLIKELY(!values)
1135 context->setError(AL_INVALID_VALUE, "NULL pointer");
1136 else switch(param)
1138 default:
1139 context->setError(AL_INVALID_ENUM, "Invalid buffer float-vector property 0x%04x", param);
1142 END_API_FUNC
1145 AL_API void AL_APIENTRY alBufferi(ALuint buffer, ALenum param, ALint value)
1146 START_API_FUNC
1148 ContextRef context{GetContextRef()};
1149 if UNLIKELY(!context) return;
1151 ALCdevice *device{context->mDevice.get()};
1152 std::lock_guard<std::mutex> _{device->BufferLock};
1154 ALbuffer *albuf = LookupBuffer(device, buffer);
1155 if UNLIKELY(!albuf)
1156 context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
1157 else switch(param)
1159 case AL_UNPACK_BLOCK_ALIGNMENT_SOFT:
1160 if UNLIKELY(value < 0)
1161 context->setError(AL_INVALID_VALUE, "Invalid unpack block alignment %d", value);
1162 else
1163 albuf->UnpackAlign = static_cast<ALuint>(value);
1164 break;
1166 case AL_PACK_BLOCK_ALIGNMENT_SOFT:
1167 if UNLIKELY(value < 0)
1168 context->setError(AL_INVALID_VALUE, "Invalid pack block alignment %d", value);
1169 else
1170 albuf->PackAlign = static_cast<ALuint>(value);
1171 break;
1173 case AL_AMBISONIC_LAYOUT_SOFT:
1174 if UNLIKELY(ReadRef(albuf->ref) != 0)
1175 context->setError(AL_INVALID_OPERATION, "Modifying in-use buffer %u's ambisonic layout",
1176 buffer);
1177 else if UNLIKELY(value != AL_FUMA_SOFT && value != AL_ACN_SOFT)
1178 context->setError(AL_INVALID_VALUE, "Invalid unpack ambisonic layout %04x", value);
1179 else
1180 albuf->mBuffer.mAmbiLayout = static_cast<AmbiLayout>(value);
1181 break;
1183 case AL_AMBISONIC_SCALING_SOFT:
1184 if UNLIKELY(ReadRef(albuf->ref) != 0)
1185 context->setError(AL_INVALID_OPERATION, "Modifying in-use buffer %u's ambisonic scaling",
1186 buffer);
1187 else if UNLIKELY(value != AL_FUMA_SOFT && value != AL_SN3D_SOFT && value != AL_N3D_SOFT)
1188 context->setError(AL_INVALID_VALUE, "Invalid unpack ambisonic scaling %04x", value);
1189 else
1190 albuf->mBuffer.mAmbiScaling = static_cast<AmbiScaling>(value);
1191 break;
1193 case AL_UNPACK_AMBISONIC_ORDER_SOFT:
1194 if UNLIKELY(value < 1 || value > 14)
1195 context->setError(AL_INVALID_VALUE, "Invalid unpack ambisonic order %d", value);
1196 else
1197 albuf->UnpackAmbiOrder = static_cast<ALuint>(value);
1198 break;
1200 default:
1201 context->setError(AL_INVALID_ENUM, "Invalid buffer integer property 0x%04x", param);
1204 END_API_FUNC
1206 AL_API void AL_APIENTRY alBuffer3i(ALuint buffer, ALenum param,
1207 ALint /*value1*/, ALint /*value2*/, ALint /*value3*/)
1208 START_API_FUNC
1210 ContextRef context{GetContextRef()};
1211 if UNLIKELY(!context) return;
1213 ALCdevice *device{context->mDevice.get()};
1214 std::lock_guard<std::mutex> _{device->BufferLock};
1216 if UNLIKELY(LookupBuffer(device, buffer) == nullptr)
1217 context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
1218 else switch(param)
1220 default:
1221 context->setError(AL_INVALID_ENUM, "Invalid buffer 3-integer property 0x%04x", param);
1224 END_API_FUNC
1226 AL_API void AL_APIENTRY alBufferiv(ALuint buffer, ALenum param, const ALint *values)
1227 START_API_FUNC
1229 if(values)
1231 switch(param)
1233 case AL_UNPACK_BLOCK_ALIGNMENT_SOFT:
1234 case AL_PACK_BLOCK_ALIGNMENT_SOFT:
1235 case AL_AMBISONIC_LAYOUT_SOFT:
1236 case AL_AMBISONIC_SCALING_SOFT:
1237 case AL_UNPACK_AMBISONIC_ORDER_SOFT:
1238 alBufferi(buffer, param, values[0]);
1239 return;
1243 ContextRef context{GetContextRef()};
1244 if UNLIKELY(!context) return;
1246 ALCdevice *device{context->mDevice.get()};
1247 std::lock_guard<std::mutex> _{device->BufferLock};
1249 ALbuffer *albuf = LookupBuffer(device, buffer);
1250 if UNLIKELY(!albuf)
1251 context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
1252 else if UNLIKELY(!values)
1253 context->setError(AL_INVALID_VALUE, "NULL pointer");
1254 else switch(param)
1256 case AL_LOOP_POINTS_SOFT:
1257 if UNLIKELY(ReadRef(albuf->ref) != 0)
1258 context->setError(AL_INVALID_OPERATION, "Modifying in-use buffer %u's loop points",
1259 buffer);
1260 else if UNLIKELY(values[0] < 0 || values[0] >= values[1]
1261 || static_cast<ALuint>(values[1]) > albuf->mBuffer.mSampleLen)
1262 context->setError(AL_INVALID_VALUE, "Invalid loop point range %d -> %d on buffer %u",
1263 values[0], values[1], buffer);
1264 else
1266 albuf->LoopStart = static_cast<ALuint>(values[0]);
1267 albuf->LoopEnd = static_cast<ALuint>(values[1]);
1269 break;
1271 default:
1272 context->setError(AL_INVALID_ENUM, "Invalid buffer integer-vector property 0x%04x", param);
1275 END_API_FUNC
1278 AL_API void AL_APIENTRY alGetBufferf(ALuint buffer, ALenum param, ALfloat *value)
1279 START_API_FUNC
1281 ContextRef context{GetContextRef()};
1282 if UNLIKELY(!context) return;
1284 ALCdevice *device{context->mDevice.get()};
1285 std::lock_guard<std::mutex> _{device->BufferLock};
1287 ALbuffer *albuf = LookupBuffer(device, buffer);
1288 if UNLIKELY(!albuf)
1289 context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
1290 else if UNLIKELY(!value)
1291 context->setError(AL_INVALID_VALUE, "NULL pointer");
1292 else switch(param)
1294 default:
1295 context->setError(AL_INVALID_ENUM, "Invalid buffer float property 0x%04x", param);
1298 END_API_FUNC
1300 AL_API void AL_APIENTRY alGetBuffer3f(ALuint buffer, ALenum param, ALfloat *value1, ALfloat *value2, ALfloat *value3)
1301 START_API_FUNC
1303 ContextRef context{GetContextRef()};
1304 if UNLIKELY(!context) return;
1306 ALCdevice *device{context->mDevice.get()};
1307 std::lock_guard<std::mutex> _{device->BufferLock};
1309 if UNLIKELY(LookupBuffer(device, buffer) == nullptr)
1310 context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
1311 else if UNLIKELY(!value1 || !value2 || !value3)
1312 context->setError(AL_INVALID_VALUE, "NULL pointer");
1313 else switch(param)
1315 default:
1316 context->setError(AL_INVALID_ENUM, "Invalid buffer 3-float property 0x%04x", param);
1319 END_API_FUNC
1321 AL_API void AL_APIENTRY alGetBufferfv(ALuint buffer, ALenum param, ALfloat *values)
1322 START_API_FUNC
1324 switch(param)
1326 case AL_SEC_LENGTH_SOFT:
1327 alGetBufferf(buffer, param, values);
1328 return;
1331 ContextRef context{GetContextRef()};
1332 if UNLIKELY(!context) return;
1334 ALCdevice *device{context->mDevice.get()};
1335 std::lock_guard<std::mutex> _{device->BufferLock};
1337 if UNLIKELY(LookupBuffer(device, buffer) == nullptr)
1338 context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
1339 else if UNLIKELY(!values)
1340 context->setError(AL_INVALID_VALUE, "NULL pointer");
1341 else switch(param)
1343 default:
1344 context->setError(AL_INVALID_ENUM, "Invalid buffer float-vector property 0x%04x", param);
1347 END_API_FUNC
1350 AL_API void AL_APIENTRY alGetBufferi(ALuint buffer, ALenum param, ALint *value)
1351 START_API_FUNC
1353 ContextRef context{GetContextRef()};
1354 if UNLIKELY(!context) return;
1356 ALCdevice *device{context->mDevice.get()};
1357 std::lock_guard<std::mutex> _{device->BufferLock};
1358 ALbuffer *albuf = LookupBuffer(device, buffer);
1359 if UNLIKELY(!albuf)
1360 context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
1361 else if UNLIKELY(!value)
1362 context->setError(AL_INVALID_VALUE, "NULL pointer");
1363 else switch(param)
1365 case AL_FREQUENCY:
1366 *value = static_cast<ALint>(albuf->mBuffer.mSampleRate);
1367 break;
1369 case AL_BITS:
1370 *value = static_cast<ALint>(albuf->bytesFromFmt() * 8);
1371 break;
1373 case AL_CHANNELS:
1374 *value = static_cast<ALint>(albuf->channelsFromFmt());
1375 break;
1377 case AL_SIZE:
1378 *value = static_cast<ALint>(albuf->mBuffer.mSampleLen * albuf->frameSizeFromFmt());
1379 break;
1381 case AL_UNPACK_BLOCK_ALIGNMENT_SOFT:
1382 *value = static_cast<ALint>(albuf->UnpackAlign);
1383 break;
1385 case AL_PACK_BLOCK_ALIGNMENT_SOFT:
1386 *value = static_cast<ALint>(albuf->PackAlign);
1387 break;
1389 case AL_AMBISONIC_LAYOUT_SOFT:
1390 *value = static_cast<int>(albuf->mBuffer.mAmbiLayout);
1391 break;
1393 case AL_AMBISONIC_SCALING_SOFT:
1394 *value = static_cast<int>(albuf->mBuffer.mAmbiScaling);
1395 break;
1397 case AL_UNPACK_AMBISONIC_ORDER_SOFT:
1398 *value = static_cast<int>(albuf->UnpackAmbiOrder);
1399 break;
1401 default:
1402 context->setError(AL_INVALID_ENUM, "Invalid buffer integer property 0x%04x", param);
1405 END_API_FUNC
1407 AL_API void AL_APIENTRY alGetBuffer3i(ALuint buffer, ALenum param, ALint *value1, ALint *value2, ALint *value3)
1408 START_API_FUNC
1410 ContextRef context{GetContextRef()};
1411 if UNLIKELY(!context) return;
1413 ALCdevice *device{context->mDevice.get()};
1414 std::lock_guard<std::mutex> _{device->BufferLock};
1415 if UNLIKELY(LookupBuffer(device, buffer) == nullptr)
1416 context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
1417 else if UNLIKELY(!value1 || !value2 || !value3)
1418 context->setError(AL_INVALID_VALUE, "NULL pointer");
1419 else switch(param)
1421 default:
1422 context->setError(AL_INVALID_ENUM, "Invalid buffer 3-integer property 0x%04x", param);
1425 END_API_FUNC
1427 AL_API void AL_APIENTRY alGetBufferiv(ALuint buffer, ALenum param, ALint *values)
1428 START_API_FUNC
1430 switch(param)
1432 case AL_FREQUENCY:
1433 case AL_BITS:
1434 case AL_CHANNELS:
1435 case AL_SIZE:
1436 case AL_INTERNAL_FORMAT_SOFT:
1437 case AL_BYTE_LENGTH_SOFT:
1438 case AL_SAMPLE_LENGTH_SOFT:
1439 case AL_UNPACK_BLOCK_ALIGNMENT_SOFT:
1440 case AL_PACK_BLOCK_ALIGNMENT_SOFT:
1441 case AL_AMBISONIC_LAYOUT_SOFT:
1442 case AL_AMBISONIC_SCALING_SOFT:
1443 case AL_UNPACK_AMBISONIC_ORDER_SOFT:
1444 alGetBufferi(buffer, param, values);
1445 return;
1448 ContextRef context{GetContextRef()};
1449 if UNLIKELY(!context) return;
1451 ALCdevice *device{context->mDevice.get()};
1452 std::lock_guard<std::mutex> _{device->BufferLock};
1453 ALbuffer *albuf = LookupBuffer(device, buffer);
1454 if UNLIKELY(!albuf)
1455 context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
1456 else if UNLIKELY(!values)
1457 context->setError(AL_INVALID_VALUE, "NULL pointer");
1458 else switch(param)
1460 case AL_LOOP_POINTS_SOFT:
1461 values[0] = static_cast<ALint>(albuf->LoopStart);
1462 values[1] = static_cast<ALint>(albuf->LoopEnd);
1463 break;
1465 default:
1466 context->setError(AL_INVALID_ENUM, "Invalid buffer integer-vector property 0x%04x", param);
1469 END_API_FUNC
1472 AL_API void AL_APIENTRY alBufferCallbackSOFT(ALuint buffer, ALenum format, ALsizei freq,
1473 LPALBUFFERCALLBACKTYPESOFT callback, ALvoid *userptr, ALbitfieldSOFT flags)
1474 START_API_FUNC
1476 ContextRef context{GetContextRef()};
1477 if UNLIKELY(!context) return;
1479 ALCdevice *device{context->mDevice.get()};
1480 std::lock_guard<std::mutex> _{device->BufferLock};
1482 ALbuffer *albuf = LookupBuffer(device, buffer);
1483 if UNLIKELY(!albuf)
1484 context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
1485 else if UNLIKELY(freq < 1)
1486 context->setError(AL_INVALID_VALUE, "Invalid sample rate %d", freq);
1487 else if UNLIKELY(callback == nullptr)
1488 context->setError(AL_INVALID_VALUE, "NULL callback");
1489 else if UNLIKELY(flags != 0)
1490 context->setError(AL_INVALID_VALUE, "Invalid callback flags 0x%x", flags);
1491 else
1493 auto usrfmt = DecomposeUserFormat(format);
1494 if UNLIKELY(!usrfmt)
1495 context->setError(AL_INVALID_ENUM, "Invalid format 0x%04x", format);
1496 else
1497 PrepareCallback(context.get(), albuf, freq, usrfmt->channels, usrfmt->type, callback,
1498 userptr);
1501 END_API_FUNC
1503 AL_API void AL_APIENTRY alGetBufferPtrSOFT(ALuint buffer, ALenum param, ALvoid **value)
1504 START_API_FUNC
1506 ContextRef context{GetContextRef()};
1507 if UNLIKELY(!context) return;
1509 ALCdevice *device{context->mDevice.get()};
1510 std::lock_guard<std::mutex> _{device->BufferLock};
1511 ALbuffer *albuf = LookupBuffer(device, buffer);
1512 if UNLIKELY(!albuf)
1513 context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
1514 else if UNLIKELY(!value)
1515 context->setError(AL_INVALID_VALUE, "NULL pointer");
1516 else switch(param)
1518 case AL_BUFFER_CALLBACK_FUNCTION_SOFT:
1519 *value = reinterpret_cast<void*>(albuf->mBuffer.mCallback);
1520 break;
1521 case AL_BUFFER_CALLBACK_USER_PARAM_SOFT:
1522 *value = albuf->mBuffer.mUserData;
1523 break;
1525 default:
1526 context->setError(AL_INVALID_ENUM, "Invalid buffer pointer property 0x%04x", param);
1529 END_API_FUNC
1531 AL_API void AL_APIENTRY alGetBuffer3PtrSOFT(ALuint buffer, ALenum param, ALvoid **value1, ALvoid **value2, ALvoid **value3)
1532 START_API_FUNC
1534 ContextRef context{GetContextRef()};
1535 if UNLIKELY(!context) return;
1537 ALCdevice *device{context->mDevice.get()};
1538 std::lock_guard<std::mutex> _{device->BufferLock};
1539 if UNLIKELY(LookupBuffer(device, buffer) == nullptr)
1540 context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
1541 else if UNLIKELY(!value1 || !value2 || !value3)
1542 context->setError(AL_INVALID_VALUE, "NULL pointer");
1543 else switch(param)
1545 default:
1546 context->setError(AL_INVALID_ENUM, "Invalid buffer 3-pointer property 0x%04x", param);
1549 END_API_FUNC
1551 AL_API void AL_APIENTRY alGetBufferPtrvSOFT(ALuint buffer, ALenum param, ALvoid **values)
1552 START_API_FUNC
1554 switch(param)
1556 case AL_BUFFER_CALLBACK_FUNCTION_SOFT:
1557 case AL_BUFFER_CALLBACK_USER_PARAM_SOFT:
1558 alGetBufferPtrSOFT(buffer, param, values);
1559 return;
1562 ContextRef context{GetContextRef()};
1563 if UNLIKELY(!context) return;
1565 ALCdevice *device{context->mDevice.get()};
1566 std::lock_guard<std::mutex> _{device->BufferLock};
1567 if UNLIKELY(LookupBuffer(device, buffer) == nullptr)
1568 context->setError(AL_INVALID_NAME, "Invalid buffer ID %u", buffer);
1569 else if UNLIKELY(!values)
1570 context->setError(AL_INVALID_VALUE, "NULL pointer");
1571 else switch(param)
1573 default:
1574 context->setError(AL_INVALID_ENUM, "Invalid buffer pointer-vector property 0x%04x", param);
1577 END_API_FUNC
1580 BufferSubList::~BufferSubList()
1582 uint64_t usemask{~FreeMask};
1583 while(usemask)
1585 ALsizei idx{CTZ64(usemask)};
1586 al::destroy_at(Buffers+idx);
1587 usemask &= ~(1_u64 << idx);
1589 FreeMask = ~usemask;
1590 al_free(Buffers);
1591 Buffers = nullptr;