🛠️🐜 Antkeeper superbuild with dependencies included https://antkeeper.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

4307 lines
129 KiB

  1. /**
  2. * OpenAL cross platform audio library
  3. * Copyright (C) 1999-2007 by authors.
  4. * This library is free software; you can redistribute it and/or
  5. * modify it under the terms of the GNU Library General Public
  6. * License as published by the Free Software Foundation; either
  7. * version 2 of the License, or (at your option) any later version.
  8. *
  9. * This library is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. * Library General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU Library General Public
  15. * License along with this library; if not, write to the
  16. * Free Software Foundation, Inc.,
  17. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  18. * Or go to http://www.gnu.org/copyleft/lgpl.html
  19. */
  20. #include "config.h"
  21. #include "version.h"
  22. #include <stdlib.h>
  23. #include <stdio.h>
  24. #include <memory.h>
  25. #include <ctype.h>
  26. #include <signal.h>
  27. #include <cmath>
  28. #include <atomic>
  29. #include <mutex>
  30. #include <thread>
  31. #include <vector>
  32. #include <string>
  33. #include <numeric>
  34. #include <algorithm>
  35. #include <functional>
  36. #include "alMain.h"
  37. #include "alcontext.h"
  38. #include "alSource.h"
  39. #include "alListener.h"
  40. #include "alSource.h"
  41. #include "alBuffer.h"
  42. #include "alFilter.h"
  43. #include "alEffect.h"
  44. #include "alAuxEffectSlot.h"
  45. #include "alError.h"
  46. #include "mastering.h"
  47. #include "bformatdec.h"
  48. #include "uhjfilter.h"
  49. #include "alu.h"
  50. #include "alconfig.h"
  51. #include "ringbuffer.h"
  52. #include "filters/splitter.h"
  53. #include "bs2b.h"
  54. #include "fpu_modes.h"
  55. #include "cpu_caps.h"
  56. #include "compat.h"
  57. #include "threads.h"
  58. #include "alexcpt.h"
  59. #include "almalloc.h"
  60. #include "backends/base.h"
  61. #include "backends/null.h"
  62. #include "backends/loopback.h"
  63. #ifdef HAVE_JACK
  64. #include "backends/jack.h"
  65. #endif
  66. #ifdef HAVE_PULSEAUDIO
  67. #include "backends/pulseaudio.h"
  68. #endif
  69. #ifdef HAVE_ALSA
  70. #include "backends/alsa.h"
  71. #endif
  72. #ifdef HAVE_WASAPI
  73. #include "backends/wasapi.h"
  74. #endif
  75. #ifdef HAVE_COREAUDIO
  76. #include "backends/coreaudio.h"
  77. #endif
  78. #ifdef HAVE_OPENSL
  79. #include "backends/opensl.h"
  80. #endif
  81. #ifdef HAVE_SOLARIS
  82. #include "backends/solaris.h"
  83. #endif
  84. #ifdef HAVE_SNDIO
  85. #include "backends/sndio.h"
  86. #endif
  87. #ifdef HAVE_OSS
  88. #include "backends/oss.h"
  89. #endif
  90. #ifdef HAVE_QSA
  91. #include "backends/qsa.h"
  92. #endif
  93. #ifdef HAVE_DSOUND
  94. #include "backends/dsound.h"
  95. #endif
  96. #ifdef HAVE_WINMM
  97. #include "backends/winmm.h"
  98. #endif
  99. #ifdef HAVE_PORTAUDIO
  100. #include "backends/portaudio.h"
  101. #endif
  102. #ifdef HAVE_SDL2
  103. #include "backends/sdl2.h"
  104. #endif
  105. #ifdef HAVE_WAVE
  106. #include "backends/wave.h"
  107. #endif
  108. namespace {
  109. using namespace std::placeholders;
  110. using std::chrono::seconds;
  111. using std::chrono::nanoseconds;
  112. /************************************************
  113. * Backends
  114. ************************************************/
  115. struct BackendInfo {
  116. const char *name;
  117. BackendFactory& (*getFactory)(void);
  118. };
  119. BackendInfo BackendList[] = {
  120. #ifdef HAVE_JACK
  121. { "jack", JackBackendFactory::getFactory },
  122. #endif
  123. #ifdef HAVE_PULSEAUDIO
  124. { "pulse", PulseBackendFactory::getFactory },
  125. #endif
  126. #ifdef HAVE_ALSA
  127. { "alsa", AlsaBackendFactory::getFactory },
  128. #endif
  129. #ifdef HAVE_WASAPI
  130. { "wasapi", WasapiBackendFactory::getFactory },
  131. #endif
  132. #ifdef HAVE_COREAUDIO
  133. { "core", CoreAudioBackendFactory::getFactory },
  134. #endif
  135. #ifdef HAVE_OPENSL
  136. { "opensl", OSLBackendFactory::getFactory },
  137. #endif
  138. #ifdef HAVE_SOLARIS
  139. { "solaris", SolarisBackendFactory::getFactory },
  140. #endif
  141. #ifdef HAVE_SNDIO
  142. { "sndio", SndIOBackendFactory::getFactory },
  143. #endif
  144. #ifdef HAVE_OSS
  145. { "oss", OSSBackendFactory::getFactory },
  146. #endif
  147. #ifdef HAVE_QSA
  148. { "qsa", QSABackendFactory::getFactory },
  149. #endif
  150. #ifdef HAVE_DSOUND
  151. { "dsound", DSoundBackendFactory::getFactory },
  152. #endif
  153. #ifdef HAVE_WINMM
  154. { "winmm", WinMMBackendFactory::getFactory },
  155. #endif
  156. #ifdef HAVE_PORTAUDIO
  157. { "port", PortBackendFactory::getFactory },
  158. #endif
  159. #ifdef HAVE_SDL2
  160. { "sdl2", SDL2BackendFactory::getFactory },
  161. #endif
  162. { "null", NullBackendFactory::getFactory },
  163. #ifdef HAVE_WAVE
  164. { "wave", WaveBackendFactory::getFactory },
  165. #endif
  166. };
  167. auto BackendListEnd = std::end(BackendList);
  168. BackendInfo PlaybackBackend;
  169. BackendInfo CaptureBackend;
  170. /************************************************
  171. * Functions, enums, and errors
  172. ************************************************/
  173. #define DECL(x) { #x, (ALCvoid*)(x) }
  174. constexpr struct {
  175. const ALCchar *funcName;
  176. ALCvoid *address;
  177. } alcFunctions[] = {
  178. DECL(alcCreateContext),
  179. DECL(alcMakeContextCurrent),
  180. DECL(alcProcessContext),
  181. DECL(alcSuspendContext),
  182. DECL(alcDestroyContext),
  183. DECL(alcGetCurrentContext),
  184. DECL(alcGetContextsDevice),
  185. DECL(alcOpenDevice),
  186. DECL(alcCloseDevice),
  187. DECL(alcGetError),
  188. DECL(alcIsExtensionPresent),
  189. DECL(alcGetProcAddress),
  190. DECL(alcGetEnumValue),
  191. DECL(alcGetString),
  192. DECL(alcGetIntegerv),
  193. DECL(alcCaptureOpenDevice),
  194. DECL(alcCaptureCloseDevice),
  195. DECL(alcCaptureStart),
  196. DECL(alcCaptureStop),
  197. DECL(alcCaptureSamples),
  198. DECL(alcSetThreadContext),
  199. DECL(alcGetThreadContext),
  200. DECL(alcLoopbackOpenDeviceSOFT),
  201. DECL(alcIsRenderFormatSupportedSOFT),
  202. DECL(alcRenderSamplesSOFT),
  203. DECL(alcDevicePauseSOFT),
  204. DECL(alcDeviceResumeSOFT),
  205. DECL(alcGetStringiSOFT),
  206. DECL(alcResetDeviceSOFT),
  207. DECL(alcGetInteger64vSOFT),
  208. DECL(alEnable),
  209. DECL(alDisable),
  210. DECL(alIsEnabled),
  211. DECL(alGetString),
  212. DECL(alGetBooleanv),
  213. DECL(alGetIntegerv),
  214. DECL(alGetFloatv),
  215. DECL(alGetDoublev),
  216. DECL(alGetBoolean),
  217. DECL(alGetInteger),
  218. DECL(alGetFloat),
  219. DECL(alGetDouble),
  220. DECL(alGetError),
  221. DECL(alIsExtensionPresent),
  222. DECL(alGetProcAddress),
  223. DECL(alGetEnumValue),
  224. DECL(alListenerf),
  225. DECL(alListener3f),
  226. DECL(alListenerfv),
  227. DECL(alListeneri),
  228. DECL(alListener3i),
  229. DECL(alListeneriv),
  230. DECL(alGetListenerf),
  231. DECL(alGetListener3f),
  232. DECL(alGetListenerfv),
  233. DECL(alGetListeneri),
  234. DECL(alGetListener3i),
  235. DECL(alGetListeneriv),
  236. DECL(alGenSources),
  237. DECL(alDeleteSources),
  238. DECL(alIsSource),
  239. DECL(alSourcef),
  240. DECL(alSource3f),
  241. DECL(alSourcefv),
  242. DECL(alSourcei),
  243. DECL(alSource3i),
  244. DECL(alSourceiv),
  245. DECL(alGetSourcef),
  246. DECL(alGetSource3f),
  247. DECL(alGetSourcefv),
  248. DECL(alGetSourcei),
  249. DECL(alGetSource3i),
  250. DECL(alGetSourceiv),
  251. DECL(alSourcePlayv),
  252. DECL(alSourceStopv),
  253. DECL(alSourceRewindv),
  254. DECL(alSourcePausev),
  255. DECL(alSourcePlay),
  256. DECL(alSourceStop),
  257. DECL(alSourceRewind),
  258. DECL(alSourcePause),
  259. DECL(alSourceQueueBuffers),
  260. DECL(alSourceUnqueueBuffers),
  261. DECL(alGenBuffers),
  262. DECL(alDeleteBuffers),
  263. DECL(alIsBuffer),
  264. DECL(alBufferData),
  265. DECL(alBufferf),
  266. DECL(alBuffer3f),
  267. DECL(alBufferfv),
  268. DECL(alBufferi),
  269. DECL(alBuffer3i),
  270. DECL(alBufferiv),
  271. DECL(alGetBufferf),
  272. DECL(alGetBuffer3f),
  273. DECL(alGetBufferfv),
  274. DECL(alGetBufferi),
  275. DECL(alGetBuffer3i),
  276. DECL(alGetBufferiv),
  277. DECL(alDopplerFactor),
  278. DECL(alDopplerVelocity),
  279. DECL(alSpeedOfSound),
  280. DECL(alDistanceModel),
  281. DECL(alGenFilters),
  282. DECL(alDeleteFilters),
  283. DECL(alIsFilter),
  284. DECL(alFilteri),
  285. DECL(alFilteriv),
  286. DECL(alFilterf),
  287. DECL(alFilterfv),
  288. DECL(alGetFilteri),
  289. DECL(alGetFilteriv),
  290. DECL(alGetFilterf),
  291. DECL(alGetFilterfv),
  292. DECL(alGenEffects),
  293. DECL(alDeleteEffects),
  294. DECL(alIsEffect),
  295. DECL(alEffecti),
  296. DECL(alEffectiv),
  297. DECL(alEffectf),
  298. DECL(alEffectfv),
  299. DECL(alGetEffecti),
  300. DECL(alGetEffectiv),
  301. DECL(alGetEffectf),
  302. DECL(alGetEffectfv),
  303. DECL(alGenAuxiliaryEffectSlots),
  304. DECL(alDeleteAuxiliaryEffectSlots),
  305. DECL(alIsAuxiliaryEffectSlot),
  306. DECL(alAuxiliaryEffectSloti),
  307. DECL(alAuxiliaryEffectSlotiv),
  308. DECL(alAuxiliaryEffectSlotf),
  309. DECL(alAuxiliaryEffectSlotfv),
  310. DECL(alGetAuxiliaryEffectSloti),
  311. DECL(alGetAuxiliaryEffectSlotiv),
  312. DECL(alGetAuxiliaryEffectSlotf),
  313. DECL(alGetAuxiliaryEffectSlotfv),
  314. DECL(alDeferUpdatesSOFT),
  315. DECL(alProcessUpdatesSOFT),
  316. DECL(alSourcedSOFT),
  317. DECL(alSource3dSOFT),
  318. DECL(alSourcedvSOFT),
  319. DECL(alGetSourcedSOFT),
  320. DECL(alGetSource3dSOFT),
  321. DECL(alGetSourcedvSOFT),
  322. DECL(alSourcei64SOFT),
  323. DECL(alSource3i64SOFT),
  324. DECL(alSourcei64vSOFT),
  325. DECL(alGetSourcei64SOFT),
  326. DECL(alGetSource3i64SOFT),
  327. DECL(alGetSourcei64vSOFT),
  328. DECL(alGetStringiSOFT),
  329. DECL(alBufferStorageSOFT),
  330. DECL(alMapBufferSOFT),
  331. DECL(alUnmapBufferSOFT),
  332. DECL(alFlushMappedBufferSOFT),
  333. DECL(alEventControlSOFT),
  334. DECL(alEventCallbackSOFT),
  335. DECL(alGetPointerSOFT),
  336. DECL(alGetPointervSOFT),
  337. };
  338. #undef DECL
  339. #define DECL(x) { #x, (x) }
  340. constexpr struct {
  341. const ALCchar *enumName;
  342. ALCenum value;
  343. } alcEnumerations[] = {
  344. DECL(ALC_INVALID),
  345. DECL(ALC_FALSE),
  346. DECL(ALC_TRUE),
  347. DECL(ALC_MAJOR_VERSION),
  348. DECL(ALC_MINOR_VERSION),
  349. DECL(ALC_ATTRIBUTES_SIZE),
  350. DECL(ALC_ALL_ATTRIBUTES),
  351. DECL(ALC_DEFAULT_DEVICE_SPECIFIER),
  352. DECL(ALC_DEVICE_SPECIFIER),
  353. DECL(ALC_ALL_DEVICES_SPECIFIER),
  354. DECL(ALC_DEFAULT_ALL_DEVICES_SPECIFIER),
  355. DECL(ALC_EXTENSIONS),
  356. DECL(ALC_FREQUENCY),
  357. DECL(ALC_REFRESH),
  358. DECL(ALC_SYNC),
  359. DECL(ALC_MONO_SOURCES),
  360. DECL(ALC_STEREO_SOURCES),
  361. DECL(ALC_CAPTURE_DEVICE_SPECIFIER),
  362. DECL(ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER),
  363. DECL(ALC_CAPTURE_SAMPLES),
  364. DECL(ALC_CONNECTED),
  365. DECL(ALC_EFX_MAJOR_VERSION),
  366. DECL(ALC_EFX_MINOR_VERSION),
  367. DECL(ALC_MAX_AUXILIARY_SENDS),
  368. DECL(ALC_FORMAT_CHANNELS_SOFT),
  369. DECL(ALC_FORMAT_TYPE_SOFT),
  370. DECL(ALC_MONO_SOFT),
  371. DECL(ALC_STEREO_SOFT),
  372. DECL(ALC_QUAD_SOFT),
  373. DECL(ALC_5POINT1_SOFT),
  374. DECL(ALC_6POINT1_SOFT),
  375. DECL(ALC_7POINT1_SOFT),
  376. DECL(ALC_BFORMAT3D_SOFT),
  377. DECL(ALC_BYTE_SOFT),
  378. DECL(ALC_UNSIGNED_BYTE_SOFT),
  379. DECL(ALC_SHORT_SOFT),
  380. DECL(ALC_UNSIGNED_SHORT_SOFT),
  381. DECL(ALC_INT_SOFT),
  382. DECL(ALC_UNSIGNED_INT_SOFT),
  383. DECL(ALC_FLOAT_SOFT),
  384. DECL(ALC_HRTF_SOFT),
  385. DECL(ALC_DONT_CARE_SOFT),
  386. DECL(ALC_HRTF_STATUS_SOFT),
  387. DECL(ALC_HRTF_DISABLED_SOFT),
  388. DECL(ALC_HRTF_ENABLED_SOFT),
  389. DECL(ALC_HRTF_DENIED_SOFT),
  390. DECL(ALC_HRTF_REQUIRED_SOFT),
  391. DECL(ALC_HRTF_HEADPHONES_DETECTED_SOFT),
  392. DECL(ALC_HRTF_UNSUPPORTED_FORMAT_SOFT),
  393. DECL(ALC_NUM_HRTF_SPECIFIERS_SOFT),
  394. DECL(ALC_HRTF_SPECIFIER_SOFT),
  395. DECL(ALC_HRTF_ID_SOFT),
  396. DECL(ALC_AMBISONIC_LAYOUT_SOFT),
  397. DECL(ALC_AMBISONIC_SCALING_SOFT),
  398. DECL(ALC_AMBISONIC_ORDER_SOFT),
  399. DECL(ALC_ACN_SOFT),
  400. DECL(ALC_FUMA_SOFT),
  401. DECL(ALC_N3D_SOFT),
  402. DECL(ALC_SN3D_SOFT),
  403. DECL(ALC_OUTPUT_LIMITER_SOFT),
  404. DECL(ALC_NO_ERROR),
  405. DECL(ALC_INVALID_DEVICE),
  406. DECL(ALC_INVALID_CONTEXT),
  407. DECL(ALC_INVALID_ENUM),
  408. DECL(ALC_INVALID_VALUE),
  409. DECL(ALC_OUT_OF_MEMORY),
  410. DECL(AL_INVALID),
  411. DECL(AL_NONE),
  412. DECL(AL_FALSE),
  413. DECL(AL_TRUE),
  414. DECL(AL_SOURCE_RELATIVE),
  415. DECL(AL_CONE_INNER_ANGLE),
  416. DECL(AL_CONE_OUTER_ANGLE),
  417. DECL(AL_PITCH),
  418. DECL(AL_POSITION),
  419. DECL(AL_DIRECTION),
  420. DECL(AL_VELOCITY),
  421. DECL(AL_LOOPING),
  422. DECL(AL_BUFFER),
  423. DECL(AL_GAIN),
  424. DECL(AL_MIN_GAIN),
  425. DECL(AL_MAX_GAIN),
  426. DECL(AL_ORIENTATION),
  427. DECL(AL_REFERENCE_DISTANCE),
  428. DECL(AL_ROLLOFF_FACTOR),
  429. DECL(AL_CONE_OUTER_GAIN),
  430. DECL(AL_MAX_DISTANCE),
  431. DECL(AL_SEC_OFFSET),
  432. DECL(AL_SAMPLE_OFFSET),
  433. DECL(AL_BYTE_OFFSET),
  434. DECL(AL_SOURCE_TYPE),
  435. DECL(AL_STATIC),
  436. DECL(AL_STREAMING),
  437. DECL(AL_UNDETERMINED),
  438. DECL(AL_METERS_PER_UNIT),
  439. DECL(AL_LOOP_POINTS_SOFT),
  440. DECL(AL_DIRECT_CHANNELS_SOFT),
  441. DECL(AL_DIRECT_FILTER),
  442. DECL(AL_AUXILIARY_SEND_FILTER),
  443. DECL(AL_AIR_ABSORPTION_FACTOR),
  444. DECL(AL_ROOM_ROLLOFF_FACTOR),
  445. DECL(AL_CONE_OUTER_GAINHF),
  446. DECL(AL_DIRECT_FILTER_GAINHF_AUTO),
  447. DECL(AL_AUXILIARY_SEND_FILTER_GAIN_AUTO),
  448. DECL(AL_AUXILIARY_SEND_FILTER_GAINHF_AUTO),
  449. DECL(AL_SOURCE_STATE),
  450. DECL(AL_INITIAL),
  451. DECL(AL_PLAYING),
  452. DECL(AL_PAUSED),
  453. DECL(AL_STOPPED),
  454. DECL(AL_BUFFERS_QUEUED),
  455. DECL(AL_BUFFERS_PROCESSED),
  456. DECL(AL_FORMAT_MONO8),
  457. DECL(AL_FORMAT_MONO16),
  458. DECL(AL_FORMAT_MONO_FLOAT32),
  459. DECL(AL_FORMAT_MONO_DOUBLE_EXT),
  460. DECL(AL_FORMAT_STEREO8),
  461. DECL(AL_FORMAT_STEREO16),
  462. DECL(AL_FORMAT_STEREO_FLOAT32),
  463. DECL(AL_FORMAT_STEREO_DOUBLE_EXT),
  464. DECL(AL_FORMAT_MONO_IMA4),
  465. DECL(AL_FORMAT_STEREO_IMA4),
  466. DECL(AL_FORMAT_MONO_MSADPCM_SOFT),
  467. DECL(AL_FORMAT_STEREO_MSADPCM_SOFT),
  468. DECL(AL_FORMAT_QUAD8_LOKI),
  469. DECL(AL_FORMAT_QUAD16_LOKI),
  470. DECL(AL_FORMAT_QUAD8),
  471. DECL(AL_FORMAT_QUAD16),
  472. DECL(AL_FORMAT_QUAD32),
  473. DECL(AL_FORMAT_51CHN8),
  474. DECL(AL_FORMAT_51CHN16),
  475. DECL(AL_FORMAT_51CHN32),
  476. DECL(AL_FORMAT_61CHN8),
  477. DECL(AL_FORMAT_61CHN16),
  478. DECL(AL_FORMAT_61CHN32),
  479. DECL(AL_FORMAT_71CHN8),
  480. DECL(AL_FORMAT_71CHN16),
  481. DECL(AL_FORMAT_71CHN32),
  482. DECL(AL_FORMAT_REAR8),
  483. DECL(AL_FORMAT_REAR16),
  484. DECL(AL_FORMAT_REAR32),
  485. DECL(AL_FORMAT_MONO_MULAW),
  486. DECL(AL_FORMAT_MONO_MULAW_EXT),
  487. DECL(AL_FORMAT_STEREO_MULAW),
  488. DECL(AL_FORMAT_STEREO_MULAW_EXT),
  489. DECL(AL_FORMAT_QUAD_MULAW),
  490. DECL(AL_FORMAT_51CHN_MULAW),
  491. DECL(AL_FORMAT_61CHN_MULAW),
  492. DECL(AL_FORMAT_71CHN_MULAW),
  493. DECL(AL_FORMAT_REAR_MULAW),
  494. DECL(AL_FORMAT_MONO_ALAW_EXT),
  495. DECL(AL_FORMAT_STEREO_ALAW_EXT),
  496. DECL(AL_FORMAT_BFORMAT2D_8),
  497. DECL(AL_FORMAT_BFORMAT2D_16),
  498. DECL(AL_FORMAT_BFORMAT2D_FLOAT32),
  499. DECL(AL_FORMAT_BFORMAT2D_MULAW),
  500. DECL(AL_FORMAT_BFORMAT3D_8),
  501. DECL(AL_FORMAT_BFORMAT3D_16),
  502. DECL(AL_FORMAT_BFORMAT3D_FLOAT32),
  503. DECL(AL_FORMAT_BFORMAT3D_MULAW),
  504. DECL(AL_FREQUENCY),
  505. DECL(AL_BITS),
  506. DECL(AL_CHANNELS),
  507. DECL(AL_SIZE),
  508. DECL(AL_UNPACK_BLOCK_ALIGNMENT_SOFT),
  509. DECL(AL_PACK_BLOCK_ALIGNMENT_SOFT),
  510. DECL(AL_SOURCE_RADIUS),
  511. DECL(AL_STEREO_ANGLES),
  512. DECL(AL_UNUSED),
  513. DECL(AL_PENDING),
  514. DECL(AL_PROCESSED),
  515. DECL(AL_NO_ERROR),
  516. DECL(AL_INVALID_NAME),
  517. DECL(AL_INVALID_ENUM),
  518. DECL(AL_INVALID_VALUE),
  519. DECL(AL_INVALID_OPERATION),
  520. DECL(AL_OUT_OF_MEMORY),
  521. DECL(AL_VENDOR),
  522. DECL(AL_VERSION),
  523. DECL(AL_RENDERER),
  524. DECL(AL_EXTENSIONS),
  525. DECL(AL_DOPPLER_FACTOR),
  526. DECL(AL_DOPPLER_VELOCITY),
  527. DECL(AL_DISTANCE_MODEL),
  528. DECL(AL_SPEED_OF_SOUND),
  529. DECL(AL_SOURCE_DISTANCE_MODEL),
  530. DECL(AL_DEFERRED_UPDATES_SOFT),
  531. DECL(AL_GAIN_LIMIT_SOFT),
  532. DECL(AL_INVERSE_DISTANCE),
  533. DECL(AL_INVERSE_DISTANCE_CLAMPED),
  534. DECL(AL_LINEAR_DISTANCE),
  535. DECL(AL_LINEAR_DISTANCE_CLAMPED),
  536. DECL(AL_EXPONENT_DISTANCE),
  537. DECL(AL_EXPONENT_DISTANCE_CLAMPED),
  538. DECL(AL_FILTER_TYPE),
  539. DECL(AL_FILTER_NULL),
  540. DECL(AL_FILTER_LOWPASS),
  541. DECL(AL_FILTER_HIGHPASS),
  542. DECL(AL_FILTER_BANDPASS),
  543. DECL(AL_LOWPASS_GAIN),
  544. DECL(AL_LOWPASS_GAINHF),
  545. DECL(AL_HIGHPASS_GAIN),
  546. DECL(AL_HIGHPASS_GAINLF),
  547. DECL(AL_BANDPASS_GAIN),
  548. DECL(AL_BANDPASS_GAINHF),
  549. DECL(AL_BANDPASS_GAINLF),
  550. DECL(AL_EFFECT_TYPE),
  551. DECL(AL_EFFECT_NULL),
  552. DECL(AL_EFFECT_REVERB),
  553. DECL(AL_EFFECT_EAXREVERB),
  554. DECL(AL_EFFECT_CHORUS),
  555. DECL(AL_EFFECT_DISTORTION),
  556. DECL(AL_EFFECT_ECHO),
  557. DECL(AL_EFFECT_FLANGER),
  558. DECL(AL_EFFECT_PITCH_SHIFTER),
  559. DECL(AL_EFFECT_FREQUENCY_SHIFTER),
  560. #if 0
  561. DECL(AL_EFFECT_VOCAL_MORPHER),
  562. #endif
  563. DECL(AL_EFFECT_RING_MODULATOR),
  564. DECL(AL_EFFECT_AUTOWAH),
  565. DECL(AL_EFFECT_COMPRESSOR),
  566. DECL(AL_EFFECT_EQUALIZER),
  567. DECL(AL_EFFECT_DEDICATED_LOW_FREQUENCY_EFFECT),
  568. DECL(AL_EFFECT_DEDICATED_DIALOGUE),
  569. DECL(AL_EFFECTSLOT_EFFECT),
  570. DECL(AL_EFFECTSLOT_GAIN),
  571. DECL(AL_EFFECTSLOT_AUXILIARY_SEND_AUTO),
  572. DECL(AL_EFFECTSLOT_NULL),
  573. DECL(AL_EAXREVERB_DENSITY),
  574. DECL(AL_EAXREVERB_DIFFUSION),
  575. DECL(AL_EAXREVERB_GAIN),
  576. DECL(AL_EAXREVERB_GAINHF),
  577. DECL(AL_EAXREVERB_GAINLF),
  578. DECL(AL_EAXREVERB_DECAY_TIME),
  579. DECL(AL_EAXREVERB_DECAY_HFRATIO),
  580. DECL(AL_EAXREVERB_DECAY_LFRATIO),
  581. DECL(AL_EAXREVERB_REFLECTIONS_GAIN),
  582. DECL(AL_EAXREVERB_REFLECTIONS_DELAY),
  583. DECL(AL_EAXREVERB_REFLECTIONS_PAN),
  584. DECL(AL_EAXREVERB_LATE_REVERB_GAIN),
  585. DECL(AL_EAXREVERB_LATE_REVERB_DELAY),
  586. DECL(AL_EAXREVERB_LATE_REVERB_PAN),
  587. DECL(AL_EAXREVERB_ECHO_TIME),
  588. DECL(AL_EAXREVERB_ECHO_DEPTH),
  589. DECL(AL_EAXREVERB_MODULATION_TIME),
  590. DECL(AL_EAXREVERB_MODULATION_DEPTH),
  591. DECL(AL_EAXREVERB_AIR_ABSORPTION_GAINHF),
  592. DECL(AL_EAXREVERB_HFREFERENCE),
  593. DECL(AL_EAXREVERB_LFREFERENCE),
  594. DECL(AL_EAXREVERB_ROOM_ROLLOFF_FACTOR),
  595. DECL(AL_EAXREVERB_DECAY_HFLIMIT),
  596. DECL(AL_REVERB_DENSITY),
  597. DECL(AL_REVERB_DIFFUSION),
  598. DECL(AL_REVERB_GAIN),
  599. DECL(AL_REVERB_GAINHF),
  600. DECL(AL_REVERB_DECAY_TIME),
  601. DECL(AL_REVERB_DECAY_HFRATIO),
  602. DECL(AL_REVERB_REFLECTIONS_GAIN),
  603. DECL(AL_REVERB_REFLECTIONS_DELAY),
  604. DECL(AL_REVERB_LATE_REVERB_GAIN),
  605. DECL(AL_REVERB_LATE_REVERB_DELAY),
  606. DECL(AL_REVERB_AIR_ABSORPTION_GAINHF),
  607. DECL(AL_REVERB_ROOM_ROLLOFF_FACTOR),
  608. DECL(AL_REVERB_DECAY_HFLIMIT),
  609. DECL(AL_CHORUS_WAVEFORM),
  610. DECL(AL_CHORUS_PHASE),
  611. DECL(AL_CHORUS_RATE),
  612. DECL(AL_CHORUS_DEPTH),
  613. DECL(AL_CHORUS_FEEDBACK),
  614. DECL(AL_CHORUS_DELAY),
  615. DECL(AL_DISTORTION_EDGE),
  616. DECL(AL_DISTORTION_GAIN),
  617. DECL(AL_DISTORTION_LOWPASS_CUTOFF),
  618. DECL(AL_DISTORTION_EQCENTER),
  619. DECL(AL_DISTORTION_EQBANDWIDTH),
  620. DECL(AL_ECHO_DELAY),
  621. DECL(AL_ECHO_LRDELAY),
  622. DECL(AL_ECHO_DAMPING),
  623. DECL(AL_ECHO_FEEDBACK),
  624. DECL(AL_ECHO_SPREAD),
  625. DECL(AL_FLANGER_WAVEFORM),
  626. DECL(AL_FLANGER_PHASE),
  627. DECL(AL_FLANGER_RATE),
  628. DECL(AL_FLANGER_DEPTH),
  629. DECL(AL_FLANGER_FEEDBACK),
  630. DECL(AL_FLANGER_DELAY),
  631. DECL(AL_FREQUENCY_SHIFTER_FREQUENCY),
  632. DECL(AL_FREQUENCY_SHIFTER_LEFT_DIRECTION),
  633. DECL(AL_FREQUENCY_SHIFTER_RIGHT_DIRECTION),
  634. DECL(AL_RING_MODULATOR_FREQUENCY),
  635. DECL(AL_RING_MODULATOR_HIGHPASS_CUTOFF),
  636. DECL(AL_RING_MODULATOR_WAVEFORM),
  637. DECL(AL_PITCH_SHIFTER_COARSE_TUNE),
  638. DECL(AL_PITCH_SHIFTER_FINE_TUNE),
  639. DECL(AL_COMPRESSOR_ONOFF),
  640. DECL(AL_EQUALIZER_LOW_GAIN),
  641. DECL(AL_EQUALIZER_LOW_CUTOFF),
  642. DECL(AL_EQUALIZER_MID1_GAIN),
  643. DECL(AL_EQUALIZER_MID1_CENTER),
  644. DECL(AL_EQUALIZER_MID1_WIDTH),
  645. DECL(AL_EQUALIZER_MID2_GAIN),
  646. DECL(AL_EQUALIZER_MID2_CENTER),
  647. DECL(AL_EQUALIZER_MID2_WIDTH),
  648. DECL(AL_EQUALIZER_HIGH_GAIN),
  649. DECL(AL_EQUALIZER_HIGH_CUTOFF),
  650. DECL(AL_DEDICATED_GAIN),
  651. DECL(AL_AUTOWAH_ATTACK_TIME),
  652. DECL(AL_AUTOWAH_RELEASE_TIME),
  653. DECL(AL_AUTOWAH_RESONANCE),
  654. DECL(AL_AUTOWAH_PEAK_GAIN),
  655. DECL(AL_NUM_RESAMPLERS_SOFT),
  656. DECL(AL_DEFAULT_RESAMPLER_SOFT),
  657. DECL(AL_SOURCE_RESAMPLER_SOFT),
  658. DECL(AL_RESAMPLER_NAME_SOFT),
  659. DECL(AL_SOURCE_SPATIALIZE_SOFT),
  660. DECL(AL_AUTO_SOFT),
  661. DECL(AL_MAP_READ_BIT_SOFT),
  662. DECL(AL_MAP_WRITE_BIT_SOFT),
  663. DECL(AL_MAP_PERSISTENT_BIT_SOFT),
  664. DECL(AL_PRESERVE_DATA_BIT_SOFT),
  665. DECL(AL_EVENT_CALLBACK_FUNCTION_SOFT),
  666. DECL(AL_EVENT_CALLBACK_USER_PARAM_SOFT),
  667. DECL(AL_EVENT_TYPE_BUFFER_COMPLETED_SOFT),
  668. DECL(AL_EVENT_TYPE_SOURCE_STATE_CHANGED_SOFT),
  669. DECL(AL_EVENT_TYPE_ERROR_SOFT),
  670. DECL(AL_EVENT_TYPE_PERFORMANCE_SOFT),
  671. DECL(AL_EVENT_TYPE_DEPRECATED_SOFT),
  672. };
  673. #undef DECL
  674. constexpr ALCchar alcNoError[] = "No Error";
  675. constexpr ALCchar alcErrInvalidDevice[] = "Invalid Device";
  676. constexpr ALCchar alcErrInvalidContext[] = "Invalid Context";
  677. constexpr ALCchar alcErrInvalidEnum[] = "Invalid Enum";
  678. constexpr ALCchar alcErrInvalidValue[] = "Invalid Value";
  679. constexpr ALCchar alcErrOutOfMemory[] = "Out of Memory";
  680. /************************************************
  681. * Global variables
  682. ************************************************/
  683. /* Enumerated device names */
  684. constexpr ALCchar alcDefaultName[] = "OpenAL Soft\0";
  685. std::string alcAllDevicesList;
  686. std::string alcCaptureDeviceList;
  687. /* Default is always the first in the list */
  688. std::string alcDefaultAllDevicesSpecifier;
  689. std::string alcCaptureDefaultDeviceSpecifier;
  690. /* Default context extensions */
  691. constexpr ALchar alExtList[] =
  692. "AL_EXT_ALAW "
  693. "AL_EXT_BFORMAT "
  694. "AL_EXT_DOUBLE "
  695. "AL_EXT_EXPONENT_DISTANCE "
  696. "AL_EXT_FLOAT32 "
  697. "AL_EXT_IMA4 "
  698. "AL_EXT_LINEAR_DISTANCE "
  699. "AL_EXT_MCFORMATS "
  700. "AL_EXT_MULAW "
  701. "AL_EXT_MULAW_BFORMAT "
  702. "AL_EXT_MULAW_MCFORMATS "
  703. "AL_EXT_OFFSET "
  704. "AL_EXT_source_distance_model "
  705. "AL_EXT_SOURCE_RADIUS "
  706. "AL_EXT_STEREO_ANGLES "
  707. "AL_LOKI_quadriphonic "
  708. "AL_SOFT_block_alignment "
  709. "AL_SOFT_deferred_updates "
  710. "AL_SOFT_direct_channels "
  711. "AL_SOFTX_effect_chain "
  712. "AL_SOFTX_events "
  713. "AL_SOFTX_filter_gain_ex "
  714. "AL_SOFT_gain_clamp_ex "
  715. "AL_SOFT_loop_points "
  716. "AL_SOFTX_map_buffer "
  717. "AL_SOFT_MSADPCM "
  718. "AL_SOFT_source_latency "
  719. "AL_SOFT_source_length "
  720. "AL_SOFT_source_resampler "
  721. "AL_SOFT_source_spatialize";
  722. std::atomic<ALCenum> LastNullDeviceError{ALC_NO_ERROR};
  723. /* Thread-local current context */
  724. void ReleaseThreadCtx(ALCcontext *context)
  725. {
  726. auto ref = DecrementRef(&context->ref);
  727. TRACEREF("%p decreasing refcount to %u\n", context, ref);
  728. ERR("Context %p current for thread being destroyed, possible leak!\n", context);
  729. }
  730. std::atomic<void(*)(ALCcontext*)> ThreadCtxProc{ReleaseThreadCtx};
  731. class ThreadCtx {
  732. ALCcontext *ctx{nullptr};
  733. public:
  734. ~ThreadCtx()
  735. {
  736. auto destruct = ThreadCtxProc.load();
  737. if(destruct && ctx)
  738. destruct(ctx);
  739. ctx = nullptr;
  740. }
  741. ALCcontext *get() const noexcept { return ctx; }
  742. void set(ALCcontext *ctx_) noexcept { ctx = ctx_; }
  743. };
  744. thread_local ThreadCtx LocalContext;
  745. /* Process-wide current context */
  746. std::atomic<ALCcontext*> GlobalContext{nullptr};
  747. /* Flag to trap ALC device errors */
  748. bool TrapALCError{false};
  749. /* One-time configuration init control */
  750. std::once_flag alc_config_once{};
  751. /* Default effect that applies to sources that don't have an effect on send 0 */
  752. ALeffect DefaultEffect;
  753. /* Flag to specify if alcSuspendContext/alcProcessContext should defer/process
  754. * updates.
  755. */
  756. bool SuspendDefers{true};
  757. /************************************************
  758. * ALC information
  759. ************************************************/
  760. constexpr ALCchar alcNoDeviceExtList[] =
  761. "ALC_ENUMERATE_ALL_EXT "
  762. "ALC_ENUMERATION_EXT "
  763. "ALC_EXT_CAPTURE "
  764. "ALC_EXT_thread_local_context "
  765. "ALC_SOFT_loopback";
  766. constexpr ALCchar alcExtensionList[] =
  767. "ALC_ENUMERATE_ALL_EXT "
  768. "ALC_ENUMERATION_EXT "
  769. "ALC_EXT_CAPTURE "
  770. "ALC_EXT_DEDICATED "
  771. "ALC_EXT_disconnect "
  772. "ALC_EXT_EFX "
  773. "ALC_EXT_thread_local_context "
  774. "ALC_SOFT_device_clock "
  775. "ALC_SOFT_HRTF "
  776. "ALC_SOFT_loopback "
  777. "ALC_SOFT_output_limiter "
  778. "ALC_SOFT_pause_device";
  779. constexpr ALCint alcMajorVersion = 1;
  780. constexpr ALCint alcMinorVersion = 1;
  781. constexpr ALCint alcEFXMajorVersion = 1;
  782. constexpr ALCint alcEFXMinorVersion = 0;
  783. /************************************************
  784. * Device lists
  785. ************************************************/
  786. al::vector<ALCdevice*> DeviceList;
  787. al::vector<ALCcontext*> ContextList;
  788. std::recursive_mutex ListLock;
  789. } // namespace
  790. /* Mixing thread piority level */
  791. ALint RTPrioLevel;
  792. FILE *gLogFile{stderr};
  793. #ifdef _DEBUG
  794. LogLevel gLogLevel{LogWarning};
  795. #else
  796. LogLevel gLogLevel{LogError};
  797. #endif
  798. /************************************************
  799. * Library initialization
  800. ************************************************/
  801. #if defined(_WIN32) && !defined(AL_LIBTYPE_STATIC)
  802. BOOL APIENTRY DllMain(HINSTANCE module, DWORD reason, LPVOID /*reserved*/)
  803. {
  804. switch(reason)
  805. {
  806. case DLL_PROCESS_ATTACH:
  807. /* Pin the DLL so we won't get unloaded until the process terminates */
  808. GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_PIN | GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
  809. (WCHAR*)module, &module);
  810. break;
  811. case DLL_PROCESS_DETACH:
  812. break;
  813. }
  814. return TRUE;
  815. }
  816. #endif
  817. static void alc_initconfig(void)
  818. {
  819. const char *str{getenv("ALSOFT_LOGLEVEL")};
  820. if(str)
  821. {
  822. long lvl = strtol(str, nullptr, 0);
  823. if(lvl >= NoLog && lvl <= LogRef)
  824. gLogLevel = static_cast<LogLevel>(lvl);
  825. }
  826. str = getenv("ALSOFT_LOGFILE");
  827. if(str && str[0])
  828. {
  829. #ifdef _WIN32
  830. std::wstring wname{utf8_to_wstr(str)};
  831. FILE *logfile = _wfopen(wname.c_str(), L"wt");
  832. #else
  833. FILE *logfile = fopen(str, "wt");
  834. #endif
  835. if(logfile) gLogFile = logfile;
  836. else ERR("Failed to open log file '%s'\n", str);
  837. }
  838. TRACE("Initializing library v%s-%s %s\n", ALSOFT_VERSION,
  839. ALSOFT_GIT_COMMIT_HASH, ALSOFT_GIT_BRANCH);
  840. {
  841. std::string names;
  842. if(std::begin(BackendList) != BackendListEnd)
  843. names += BackendList[0].name;
  844. for(auto backend = std::begin(BackendList)+1;backend != BackendListEnd;++backend)
  845. {
  846. names += ", ";
  847. names += backend->name;
  848. }
  849. TRACE("Supported backends: %s\n", names.c_str());
  850. }
  851. ReadALConfig();
  852. str = getenv("__ALSOFT_SUSPEND_CONTEXT");
  853. if(str && *str)
  854. {
  855. if(strcasecmp(str, "ignore") == 0)
  856. {
  857. SuspendDefers = false;
  858. TRACE("Selected context suspend behavior, \"ignore\"\n");
  859. }
  860. else
  861. ERR("Unhandled context suspend behavior setting: \"%s\"\n", str);
  862. }
  863. int capfilter{0};
  864. #if defined(HAVE_SSE4_1)
  865. capfilter |= CPU_CAP_SSE | CPU_CAP_SSE2 | CPU_CAP_SSE3 | CPU_CAP_SSE4_1;
  866. #elif defined(HAVE_SSE3)
  867. capfilter |= CPU_CAP_SSE | CPU_CAP_SSE2 | CPU_CAP_SSE3;
  868. #elif defined(HAVE_SSE2)
  869. capfilter |= CPU_CAP_SSE | CPU_CAP_SSE2;
  870. #elif defined(HAVE_SSE)
  871. capfilter |= CPU_CAP_SSE;
  872. #endif
  873. #ifdef HAVE_NEON
  874. capfilter |= CPU_CAP_NEON;
  875. #endif
  876. if(ConfigValueStr(nullptr, nullptr, "disable-cpu-exts", &str))
  877. {
  878. if(strcasecmp(str, "all") == 0)
  879. capfilter = 0;
  880. else
  881. {
  882. const char *next = str;
  883. do {
  884. str = next;
  885. while(isspace(str[0]))
  886. str++;
  887. next = strchr(str, ',');
  888. if(!str[0] || str[0] == ',')
  889. continue;
  890. size_t len{next ? static_cast<size_t>(next-str) : strlen(str)};
  891. while(len > 0 && isspace(str[len-1]))
  892. len--;
  893. if(len == 3 && strncasecmp(str, "sse", len) == 0)
  894. capfilter &= ~CPU_CAP_SSE;
  895. else if(len == 4 && strncasecmp(str, "sse2", len) == 0)
  896. capfilter &= ~CPU_CAP_SSE2;
  897. else if(len == 4 && strncasecmp(str, "sse3", len) == 0)
  898. capfilter &= ~CPU_CAP_SSE3;
  899. else if(len == 6 && strncasecmp(str, "sse4.1", len) == 0)
  900. capfilter &= ~CPU_CAP_SSE4_1;
  901. else if(len == 4 && strncasecmp(str, "neon", len) == 0)
  902. capfilter &= ~CPU_CAP_NEON;
  903. else
  904. WARN("Invalid CPU extension \"%s\"\n", str);
  905. } while(next++);
  906. }
  907. }
  908. FillCPUCaps(capfilter);
  909. #ifdef _WIN32
  910. RTPrioLevel = 1;
  911. #else
  912. RTPrioLevel = 0;
  913. #endif
  914. ConfigValueInt(nullptr, nullptr, "rt-prio", &RTPrioLevel);
  915. aluInit();
  916. aluInitMixer();
  917. str = getenv("ALSOFT_TRAP_ERROR");
  918. if(str && (strcasecmp(str, "true") == 0 || strtol(str, nullptr, 0) == 1))
  919. {
  920. TrapALError = AL_TRUE;
  921. TrapALCError = true;
  922. }
  923. else
  924. {
  925. str = getenv("ALSOFT_TRAP_AL_ERROR");
  926. if(str && (strcasecmp(str, "true") == 0 || strtol(str, nullptr, 0) == 1))
  927. TrapALError = AL_TRUE;
  928. TrapALError = GetConfigValueBool(nullptr, nullptr, "trap-al-error", TrapALError);
  929. str = getenv("ALSOFT_TRAP_ALC_ERROR");
  930. if(str && (strcasecmp(str, "true") == 0 || strtol(str, nullptr, 0) == 1))
  931. TrapALCError = true;
  932. TrapALCError = !!GetConfigValueBool(nullptr, nullptr, "trap-alc-error", TrapALCError);
  933. }
  934. float valf{};
  935. if(ConfigValueFloat(nullptr, "reverb", "boost", &valf))
  936. ReverbBoost *= std::pow(10.0f, valf / 20.0f);
  937. const char *devs{getenv("ALSOFT_DRIVERS")};
  938. if((devs && devs[0]) || ConfigValueStr(nullptr, nullptr, "drivers", &devs))
  939. {
  940. auto backendlist_cur = std::begin(BackendList);
  941. bool endlist{true};
  942. const char *next = devs;
  943. do {
  944. devs = next;
  945. while(isspace(devs[0]))
  946. devs++;
  947. next = strchr(devs, ',');
  948. const bool delitem{devs[0] == '-'};
  949. if(devs[0] == '-') devs++;
  950. if(!devs[0] || devs[0] == ',')
  951. {
  952. endlist = false;
  953. continue;
  954. }
  955. endlist = true;
  956. size_t len{next ? (static_cast<size_t>(next-devs)) : strlen(devs)};
  957. while(len > 0 && isspace(devs[len-1])) --len;
  958. #ifdef HAVE_WASAPI
  959. /* HACK: For backwards compatibility, convert backend references of
  960. * mmdevapi to wasapi. This should eventually be removed.
  961. */
  962. if(len == 8 && strncmp(devs, "mmdevapi", len) == 0)
  963. {
  964. devs = "wasapi";
  965. len = 6;
  966. }
  967. #endif
  968. auto find_backend = [devs,len](const BackendInfo &backend) -> bool
  969. { return len == strlen(backend.name) && strncmp(backend.name, devs, len) == 0; };
  970. auto this_backend = std::find_if(std::begin(BackendList), BackendListEnd,
  971. find_backend);
  972. if(this_backend == BackendListEnd)
  973. continue;
  974. if(delitem)
  975. BackendListEnd = std::move(this_backend+1, BackendListEnd, this_backend);
  976. else
  977. backendlist_cur = std::rotate(backendlist_cur, this_backend, this_backend+1);
  978. } while(next++);
  979. if(endlist)
  980. BackendListEnd = backendlist_cur;
  981. }
  982. auto init_backend = [](BackendInfo &backend) -> bool
  983. {
  984. if(PlaybackBackend.name && CaptureBackend.name)
  985. return true;
  986. BackendFactory &factory = backend.getFactory();
  987. if(!factory.init())
  988. {
  989. WARN("Failed to initialize backend \"%s\"\n", backend.name);
  990. return true;
  991. }
  992. TRACE("Initialized backend \"%s\"\n", backend.name);
  993. if(!PlaybackBackend.name && factory.querySupport(BackendType::Playback))
  994. {
  995. PlaybackBackend = backend;
  996. TRACE("Added \"%s\" for playback\n", PlaybackBackend.name);
  997. }
  998. if(!CaptureBackend.name && factory.querySupport(BackendType::Capture))
  999. {
  1000. CaptureBackend = backend;
  1001. TRACE("Added \"%s\" for capture\n", CaptureBackend.name);
  1002. }
  1003. return false;
  1004. };
  1005. BackendListEnd = std::remove_if(std::begin(BackendList), BackendListEnd, init_backend);
  1006. LoopbackBackendFactory::getFactory().init();
  1007. if(!PlaybackBackend.name)
  1008. WARN("No playback backend available!\n");
  1009. if(!CaptureBackend.name)
  1010. WARN("No capture backend available!\n");
  1011. if(ConfigValueStr(nullptr, nullptr, "excludefx", &str))
  1012. {
  1013. const char *next = str;
  1014. do {
  1015. str = next;
  1016. next = strchr(str, ',');
  1017. if(!str[0] || next == str)
  1018. continue;
  1019. size_t len{next ? static_cast<size_t>(next-str) : strlen(str)};
  1020. for(size_t n{0u};n < countof(gEffectList);n++)
  1021. {
  1022. if(len == strlen(gEffectList[n].name) &&
  1023. strncmp(gEffectList[n].name, str, len) == 0)
  1024. DisabledEffects[gEffectList[n].type] = AL_TRUE;
  1025. }
  1026. } while(next++);
  1027. }
  1028. InitEffect(&DefaultEffect);
  1029. str = getenv("ALSOFT_DEFAULT_REVERB");
  1030. if((str && str[0]) || ConfigValueStr(nullptr, nullptr, "default-reverb", &str))
  1031. LoadReverbPreset(str, &DefaultEffect);
  1032. }
  1033. #define DO_INITCONFIG() std::call_once(alc_config_once, [](){alc_initconfig();})
  1034. /************************************************
  1035. * Device enumeration
  1036. ************************************************/
  1037. static void ProbeDevices(std::string *list, BackendInfo *backendinfo, DevProbe type)
  1038. {
  1039. DO_INITCONFIG();
  1040. std::lock_guard<std::recursive_mutex> _{ListLock};
  1041. list->clear();
  1042. if(backendinfo->getFactory)
  1043. backendinfo->getFactory().probe(type, list);
  1044. }
  1045. static void ProbeAllDevicesList(void)
  1046. { ProbeDevices(&alcAllDevicesList, &PlaybackBackend, DevProbe::Playback); }
  1047. static void ProbeCaptureDeviceList(void)
  1048. { ProbeDevices(&alcCaptureDeviceList, &CaptureBackend, DevProbe::Capture); }
  1049. /************************************************
  1050. * Device format information
  1051. ************************************************/
  1052. const ALCchar *DevFmtTypeString(DevFmtType type) noexcept
  1053. {
  1054. switch(type)
  1055. {
  1056. case DevFmtByte: return "Signed Byte";
  1057. case DevFmtUByte: return "Unsigned Byte";
  1058. case DevFmtShort: return "Signed Short";
  1059. case DevFmtUShort: return "Unsigned Short";
  1060. case DevFmtInt: return "Signed Int";
  1061. case DevFmtUInt: return "Unsigned Int";
  1062. case DevFmtFloat: return "Float";
  1063. }
  1064. return "(unknown type)";
  1065. }
  1066. const ALCchar *DevFmtChannelsString(DevFmtChannels chans) noexcept
  1067. {
  1068. switch(chans)
  1069. {
  1070. case DevFmtMono: return "Mono";
  1071. case DevFmtStereo: return "Stereo";
  1072. case DevFmtQuad: return "Quadraphonic";
  1073. case DevFmtX51: return "5.1 Surround";
  1074. case DevFmtX51Rear: return "5.1 Surround (Rear)";
  1075. case DevFmtX61: return "6.1 Surround";
  1076. case DevFmtX71: return "7.1 Surround";
  1077. case DevFmtAmbi3D: return "Ambisonic 3D";
  1078. }
  1079. return "(unknown channels)";
  1080. }
  1081. ALsizei BytesFromDevFmt(DevFmtType type) noexcept
  1082. {
  1083. switch(type)
  1084. {
  1085. case DevFmtByte: return sizeof(ALbyte);
  1086. case DevFmtUByte: return sizeof(ALubyte);
  1087. case DevFmtShort: return sizeof(ALshort);
  1088. case DevFmtUShort: return sizeof(ALushort);
  1089. case DevFmtInt: return sizeof(ALint);
  1090. case DevFmtUInt: return sizeof(ALuint);
  1091. case DevFmtFloat: return sizeof(ALfloat);
  1092. }
  1093. return 0;
  1094. }
  1095. ALsizei ChannelsFromDevFmt(DevFmtChannels chans, ALsizei ambiorder) noexcept
  1096. {
  1097. switch(chans)
  1098. {
  1099. case DevFmtMono: return 1;
  1100. case DevFmtStereo: return 2;
  1101. case DevFmtQuad: return 4;
  1102. case DevFmtX51: return 6;
  1103. case DevFmtX51Rear: return 6;
  1104. case DevFmtX61: return 7;
  1105. case DevFmtX71: return 8;
  1106. case DevFmtAmbi3D: return (ambiorder+1) * (ambiorder+1);
  1107. }
  1108. return 0;
  1109. }
  1110. static ALboolean DecomposeDevFormat(ALenum format, DevFmtChannels *chans, DevFmtType *type)
  1111. {
  1112. static const struct {
  1113. ALenum format;
  1114. DevFmtChannels channels;
  1115. DevFmtType type;
  1116. } list[] = {
  1117. { AL_FORMAT_MONO8, DevFmtMono, DevFmtUByte },
  1118. { AL_FORMAT_MONO16, DevFmtMono, DevFmtShort },
  1119. { AL_FORMAT_MONO_FLOAT32, DevFmtMono, DevFmtFloat },
  1120. { AL_FORMAT_STEREO8, DevFmtStereo, DevFmtUByte },
  1121. { AL_FORMAT_STEREO16, DevFmtStereo, DevFmtShort },
  1122. { AL_FORMAT_STEREO_FLOAT32, DevFmtStereo, DevFmtFloat },
  1123. { AL_FORMAT_QUAD8, DevFmtQuad, DevFmtUByte },
  1124. { AL_FORMAT_QUAD16, DevFmtQuad, DevFmtShort },
  1125. { AL_FORMAT_QUAD32, DevFmtQuad, DevFmtFloat },
  1126. { AL_FORMAT_51CHN8, DevFmtX51, DevFmtUByte },
  1127. { AL_FORMAT_51CHN16, DevFmtX51, DevFmtShort },
  1128. { AL_FORMAT_51CHN32, DevFmtX51, DevFmtFloat },
  1129. { AL_FORMAT_61CHN8, DevFmtX61, DevFmtUByte },
  1130. { AL_FORMAT_61CHN16, DevFmtX61, DevFmtShort },
  1131. { AL_FORMAT_61CHN32, DevFmtX61, DevFmtFloat },
  1132. { AL_FORMAT_71CHN8, DevFmtX71, DevFmtUByte },
  1133. { AL_FORMAT_71CHN16, DevFmtX71, DevFmtShort },
  1134. { AL_FORMAT_71CHN32, DevFmtX71, DevFmtFloat },
  1135. };
  1136. ALuint i;
  1137. for(i = 0;i < COUNTOF(list);i++)
  1138. {
  1139. if(list[i].format == format)
  1140. {
  1141. *chans = list[i].channels;
  1142. *type = list[i].type;
  1143. return AL_TRUE;
  1144. }
  1145. }
  1146. return AL_FALSE;
  1147. }
  1148. static ALCboolean IsValidALCType(ALCenum type)
  1149. {
  1150. switch(type)
  1151. {
  1152. case ALC_BYTE_SOFT:
  1153. case ALC_UNSIGNED_BYTE_SOFT:
  1154. case ALC_SHORT_SOFT:
  1155. case ALC_UNSIGNED_SHORT_SOFT:
  1156. case ALC_INT_SOFT:
  1157. case ALC_UNSIGNED_INT_SOFT:
  1158. case ALC_FLOAT_SOFT:
  1159. return ALC_TRUE;
  1160. }
  1161. return ALC_FALSE;
  1162. }
  1163. static ALCboolean IsValidALCChannels(ALCenum channels)
  1164. {
  1165. switch(channels)
  1166. {
  1167. case ALC_MONO_SOFT:
  1168. case ALC_STEREO_SOFT:
  1169. case ALC_QUAD_SOFT:
  1170. case ALC_5POINT1_SOFT:
  1171. case ALC_6POINT1_SOFT:
  1172. case ALC_7POINT1_SOFT:
  1173. case ALC_BFORMAT3D_SOFT:
  1174. return ALC_TRUE;
  1175. }
  1176. return ALC_FALSE;
  1177. }
  1178. static ALCboolean IsValidAmbiLayout(ALCenum layout)
  1179. {
  1180. switch(layout)
  1181. {
  1182. case ALC_ACN_SOFT:
  1183. case ALC_FUMA_SOFT:
  1184. return ALC_TRUE;
  1185. }
  1186. return ALC_FALSE;
  1187. }
  1188. static ALCboolean IsValidAmbiScaling(ALCenum scaling)
  1189. {
  1190. switch(scaling)
  1191. {
  1192. case ALC_N3D_SOFT:
  1193. case ALC_SN3D_SOFT:
  1194. case ALC_FUMA_SOFT:
  1195. return ALC_TRUE;
  1196. }
  1197. return ALC_FALSE;
  1198. }
  1199. /************************************************
  1200. * Miscellaneous ALC helpers
  1201. ************************************************/
  1202. /* SetDefaultWFXChannelOrder
  1203. *
  1204. * Sets the default channel order used by WaveFormatEx.
  1205. */
  1206. void SetDefaultWFXChannelOrder(ALCdevice *device)
  1207. {
  1208. device->RealOut.ChannelIndex.fill(-1);
  1209. switch(device->FmtChans)
  1210. {
  1211. case DevFmtMono:
  1212. device->RealOut.ChannelIndex[FrontCenter] = 0;
  1213. break;
  1214. case DevFmtStereo:
  1215. device->RealOut.ChannelIndex[FrontLeft] = 0;
  1216. device->RealOut.ChannelIndex[FrontRight] = 1;
  1217. break;
  1218. case DevFmtQuad:
  1219. device->RealOut.ChannelIndex[FrontLeft] = 0;
  1220. device->RealOut.ChannelIndex[FrontRight] = 1;
  1221. device->RealOut.ChannelIndex[BackLeft] = 2;
  1222. device->RealOut.ChannelIndex[BackRight] = 3;
  1223. break;
  1224. case DevFmtX51:
  1225. device->RealOut.ChannelIndex[FrontLeft] = 0;
  1226. device->RealOut.ChannelIndex[FrontRight] = 1;
  1227. device->RealOut.ChannelIndex[FrontCenter] = 2;
  1228. device->RealOut.ChannelIndex[LFE] = 3;
  1229. device->RealOut.ChannelIndex[SideLeft] = 4;
  1230. device->RealOut.ChannelIndex[SideRight] = 5;
  1231. break;
  1232. case DevFmtX51Rear:
  1233. device->RealOut.ChannelIndex[FrontLeft] = 0;
  1234. device->RealOut.ChannelIndex[FrontRight] = 1;
  1235. device->RealOut.ChannelIndex[FrontCenter] = 2;
  1236. device->RealOut.ChannelIndex[LFE] = 3;
  1237. device->RealOut.ChannelIndex[BackLeft] = 4;
  1238. device->RealOut.ChannelIndex[BackRight] = 5;
  1239. break;
  1240. case DevFmtX61:
  1241. device->RealOut.ChannelIndex[FrontLeft] = 0;
  1242. device->RealOut.ChannelIndex[FrontRight] = 1;
  1243. device->RealOut.ChannelIndex[FrontCenter] = 2;
  1244. device->RealOut.ChannelIndex[LFE] = 3;
  1245. device->RealOut.ChannelIndex[BackCenter] = 4;
  1246. device->RealOut.ChannelIndex[SideLeft] = 5;
  1247. device->RealOut.ChannelIndex[SideRight] = 6;
  1248. break;
  1249. case DevFmtX71:
  1250. device->RealOut.ChannelIndex[FrontLeft] = 0;
  1251. device->RealOut.ChannelIndex[FrontRight] = 1;
  1252. device->RealOut.ChannelIndex[FrontCenter] = 2;
  1253. device->RealOut.ChannelIndex[LFE] = 3;
  1254. device->RealOut.ChannelIndex[BackLeft] = 4;
  1255. device->RealOut.ChannelIndex[BackRight] = 5;
  1256. device->RealOut.ChannelIndex[SideLeft] = 6;
  1257. device->RealOut.ChannelIndex[SideRight] = 7;
  1258. break;
  1259. case DevFmtAmbi3D:
  1260. device->RealOut.ChannelIndex[Aux0] = 0;
  1261. if(device->mAmbiOrder > 0)
  1262. {
  1263. device->RealOut.ChannelIndex[Aux1] = 1;
  1264. device->RealOut.ChannelIndex[Aux2] = 2;
  1265. device->RealOut.ChannelIndex[Aux3] = 3;
  1266. }
  1267. if(device->mAmbiOrder > 1)
  1268. {
  1269. device->RealOut.ChannelIndex[Aux4] = 4;
  1270. device->RealOut.ChannelIndex[Aux5] = 5;
  1271. device->RealOut.ChannelIndex[Aux6] = 6;
  1272. device->RealOut.ChannelIndex[Aux7] = 7;
  1273. device->RealOut.ChannelIndex[Aux8] = 8;
  1274. }
  1275. if(device->mAmbiOrder > 2)
  1276. {
  1277. device->RealOut.ChannelIndex[Aux9] = 9;
  1278. device->RealOut.ChannelIndex[Aux10] = 10;
  1279. device->RealOut.ChannelIndex[Aux11] = 11;
  1280. device->RealOut.ChannelIndex[Aux12] = 12;
  1281. device->RealOut.ChannelIndex[Aux13] = 13;
  1282. device->RealOut.ChannelIndex[Aux14] = 14;
  1283. device->RealOut.ChannelIndex[Aux15] = 15;
  1284. }
  1285. break;
  1286. }
  1287. }
  1288. /* SetDefaultChannelOrder
  1289. *
  1290. * Sets the default channel order used by most non-WaveFormatEx-based APIs.
  1291. */
  1292. void SetDefaultChannelOrder(ALCdevice *device)
  1293. {
  1294. device->RealOut.ChannelIndex.fill(-1);
  1295. switch(device->FmtChans)
  1296. {
  1297. case DevFmtX51Rear:
  1298. device->RealOut.ChannelIndex[FrontLeft] = 0;
  1299. device->RealOut.ChannelIndex[FrontRight] = 1;
  1300. device->RealOut.ChannelIndex[BackLeft] = 2;
  1301. device->RealOut.ChannelIndex[BackRight] = 3;
  1302. device->RealOut.ChannelIndex[FrontCenter] = 4;
  1303. device->RealOut.ChannelIndex[LFE] = 5;
  1304. return;
  1305. case DevFmtX71:
  1306. device->RealOut.ChannelIndex[FrontLeft] = 0;
  1307. device->RealOut.ChannelIndex[FrontRight] = 1;
  1308. device->RealOut.ChannelIndex[BackLeft] = 2;
  1309. device->RealOut.ChannelIndex[BackRight] = 3;
  1310. device->RealOut.ChannelIndex[FrontCenter] = 4;
  1311. device->RealOut.ChannelIndex[LFE] = 5;
  1312. device->RealOut.ChannelIndex[SideLeft] = 6;
  1313. device->RealOut.ChannelIndex[SideRight] = 7;
  1314. return;
  1315. /* Same as WFX order */
  1316. case DevFmtMono:
  1317. case DevFmtStereo:
  1318. case DevFmtQuad:
  1319. case DevFmtX51:
  1320. case DevFmtX61:
  1321. case DevFmtAmbi3D:
  1322. SetDefaultWFXChannelOrder(device);
  1323. break;
  1324. }
  1325. }
  1326. /* ALCcontext_DeferUpdates
  1327. *
  1328. * Defers/suspends updates for the given context's listener and sources. This
  1329. * does *NOT* stop mixing, but rather prevents certain property changes from
  1330. * taking effect.
  1331. */
  1332. void ALCcontext_DeferUpdates(ALCcontext *context)
  1333. {
  1334. context->DeferUpdates.store(true);
  1335. }
  1336. /* ALCcontext_ProcessUpdates
  1337. *
  1338. * Resumes update processing after being deferred.
  1339. */
  1340. void ALCcontext_ProcessUpdates(ALCcontext *context)
  1341. {
  1342. std::lock_guard<std::mutex> _{context->PropLock};
  1343. if(context->DeferUpdates.exchange(false))
  1344. {
  1345. /* Tell the mixer to stop applying updates, then wait for any active
  1346. * updating to finish, before providing updates.
  1347. */
  1348. context->HoldUpdates.store(true, std::memory_order_release);
  1349. while((context->UpdateCount.load(std::memory_order_acquire)&1) != 0)
  1350. std::this_thread::yield();
  1351. if(!context->PropsClean.test_and_set(std::memory_order_acq_rel))
  1352. UpdateContextProps(context);
  1353. if(!context->Listener.PropsClean.test_and_set(std::memory_order_acq_rel))
  1354. UpdateListenerProps(context);
  1355. UpdateAllEffectSlotProps(context);
  1356. UpdateAllSourceProps(context);
  1357. /* Now with all updates declared, let the mixer continue applying them
  1358. * so they all happen at once.
  1359. */
  1360. context->HoldUpdates.store(false, std::memory_order_release);
  1361. }
  1362. }
  1363. /* alcSetError
  1364. *
  1365. * Stores the latest ALC device error
  1366. */
  1367. static void alcSetError(ALCdevice *device, ALCenum errorCode)
  1368. {
  1369. WARN("Error generated on device %p, code 0x%04x\n", device, errorCode);
  1370. if(TrapALCError)
  1371. {
  1372. #ifdef _WIN32
  1373. /* DebugBreak() will cause an exception if there is no debugger */
  1374. if(IsDebuggerPresent())
  1375. DebugBreak();
  1376. #elif defined(SIGTRAP)
  1377. raise(SIGTRAP);
  1378. #endif
  1379. }
  1380. if(device)
  1381. device->LastError.store(errorCode);
  1382. else
  1383. LastNullDeviceError.store(errorCode);
  1384. }
  1385. static std::unique_ptr<Compressor> CreateDeviceLimiter(const ALCdevice *device, const ALfloat threshold)
  1386. {
  1387. return CompressorInit(device->RealOut.NumChannels, device->Frequency,
  1388. AL_TRUE, AL_TRUE, AL_TRUE, AL_TRUE, AL_TRUE, 0.001f, 0.002f,
  1389. 0.0f, 0.0f, threshold, INFINITY, 0.0f, 0.020f, 0.200f);
  1390. }
  1391. /* UpdateClockBase
  1392. *
  1393. * Updates the device's base clock time with however many samples have been
  1394. * done. This is used so frequency changes on the device don't cause the time
  1395. * to jump forward or back. Must not be called while the device is running/
  1396. * mixing.
  1397. */
  1398. static inline void UpdateClockBase(ALCdevice *device)
  1399. {
  1400. IncrementRef(&device->MixCount);
  1401. device->ClockBase += nanoseconds{seconds{device->SamplesDone}} / device->Frequency;
  1402. device->SamplesDone = 0;
  1403. IncrementRef(&device->MixCount);
  1404. }
  1405. /* UpdateDeviceParams
  1406. *
  1407. * Updates device parameters according to the attribute list (caller is
  1408. * responsible for holding the list lock).
  1409. */
  1410. static ALCenum UpdateDeviceParams(ALCdevice *device, const ALCint *attrList)
  1411. {
  1412. HrtfRequestMode hrtf_userreq = Hrtf_Default;
  1413. HrtfRequestMode hrtf_appreq = Hrtf_Default;
  1414. ALCenum gainLimiter = device->LimiterState;
  1415. const ALsizei old_sends = device->NumAuxSends;
  1416. ALsizei new_sends = device->NumAuxSends;
  1417. DevFmtChannels oldChans;
  1418. DevFmtType oldType;
  1419. ALboolean update_failed;
  1420. ALCsizei hrtf_id = -1;
  1421. ALCcontext *context;
  1422. ALCuint oldFreq;
  1423. int val;
  1424. if((!attrList || !attrList[0]) && device->Type == Loopback)
  1425. {
  1426. WARN("Missing attributes for loopback device\n");
  1427. return ALC_INVALID_VALUE;
  1428. }
  1429. // Check for attributes
  1430. if(attrList && attrList[0])
  1431. {
  1432. ALCenum alayout = AL_NONE;
  1433. ALCenum ascale = AL_NONE;
  1434. ALCenum schans = AL_NONE;
  1435. ALCenum stype = AL_NONE;
  1436. ALCsizei attrIdx = 0;
  1437. ALCsizei aorder = 0;
  1438. ALCuint freq = 0;
  1439. const char *devname{nullptr};
  1440. const bool loopback{device->Type == Loopback};
  1441. if(!loopback)
  1442. {
  1443. devname = device->DeviceName.c_str();
  1444. /* If a context is already running on the device, stop playback so
  1445. * the device attributes can be updated.
  1446. */
  1447. if((device->Flags&DEVICE_RUNNING))
  1448. device->Backend->stop();
  1449. device->Flags &= ~DEVICE_RUNNING;
  1450. }
  1451. auto numMono = static_cast<ALsizei>(device->NumMonoSources);
  1452. auto numStereo = static_cast<ALsizei>(device->NumStereoSources);
  1453. auto numSends = ALsizei{old_sends};
  1454. #define TRACE_ATTR(a, v) TRACE("%s = %d\n", #a, v)
  1455. while(attrList[attrIdx])
  1456. {
  1457. switch(attrList[attrIdx])
  1458. {
  1459. case ALC_FORMAT_CHANNELS_SOFT:
  1460. schans = attrList[attrIdx + 1];
  1461. TRACE_ATTR(ALC_FORMAT_CHANNELS_SOFT, schans);
  1462. break;
  1463. case ALC_FORMAT_TYPE_SOFT:
  1464. stype = attrList[attrIdx + 1];
  1465. TRACE_ATTR(ALC_FORMAT_TYPE_SOFT, stype);
  1466. break;
  1467. case ALC_FREQUENCY:
  1468. freq = attrList[attrIdx + 1];
  1469. TRACE_ATTR(ALC_FREQUENCY, freq);
  1470. break;
  1471. case ALC_AMBISONIC_LAYOUT_SOFT:
  1472. alayout = attrList[attrIdx + 1];
  1473. TRACE_ATTR(ALC_AMBISONIC_LAYOUT_SOFT, alayout);
  1474. break;
  1475. case ALC_AMBISONIC_SCALING_SOFT:
  1476. ascale = attrList[attrIdx + 1];
  1477. TRACE_ATTR(ALC_AMBISONIC_SCALING_SOFT, ascale);
  1478. break;
  1479. case ALC_AMBISONIC_ORDER_SOFT:
  1480. aorder = attrList[attrIdx + 1];
  1481. TRACE_ATTR(ALC_AMBISONIC_ORDER_SOFT, aorder);
  1482. break;
  1483. case ALC_MONO_SOURCES:
  1484. numMono = attrList[attrIdx + 1];
  1485. TRACE_ATTR(ALC_MONO_SOURCES, numMono);
  1486. numMono = maxi(numMono, 0);
  1487. break;
  1488. case ALC_STEREO_SOURCES:
  1489. numStereo = attrList[attrIdx + 1];
  1490. TRACE_ATTR(ALC_STEREO_SOURCES, numStereo);
  1491. numStereo = maxi(numStereo, 0);
  1492. break;
  1493. case ALC_MAX_AUXILIARY_SENDS:
  1494. numSends = attrList[attrIdx + 1];
  1495. TRACE_ATTR(ALC_MAX_AUXILIARY_SENDS, numSends);
  1496. numSends = clampi(numSends, 0, MAX_SENDS);
  1497. break;
  1498. case ALC_HRTF_SOFT:
  1499. TRACE_ATTR(ALC_HRTF_SOFT, attrList[attrIdx + 1]);
  1500. if(attrList[attrIdx + 1] == ALC_FALSE)
  1501. hrtf_appreq = Hrtf_Disable;
  1502. else if(attrList[attrIdx + 1] == ALC_TRUE)
  1503. hrtf_appreq = Hrtf_Enable;
  1504. else
  1505. hrtf_appreq = Hrtf_Default;
  1506. break;
  1507. case ALC_HRTF_ID_SOFT:
  1508. hrtf_id = attrList[attrIdx + 1];
  1509. TRACE_ATTR(ALC_HRTF_ID_SOFT, hrtf_id);
  1510. break;
  1511. case ALC_OUTPUT_LIMITER_SOFT:
  1512. gainLimiter = attrList[attrIdx + 1];
  1513. TRACE_ATTR(ALC_OUTPUT_LIMITER_SOFT, gainLimiter);
  1514. break;
  1515. default:
  1516. TRACE("0x%04X = %d (0x%x)\n", attrList[attrIdx],
  1517. attrList[attrIdx + 1], attrList[attrIdx + 1]);
  1518. break;
  1519. }
  1520. attrIdx += 2;
  1521. }
  1522. #undef TRACE_ATTR
  1523. if(loopback)
  1524. {
  1525. if(!schans || !stype || !freq)
  1526. {
  1527. WARN("Missing format for loopback device\n");
  1528. return ALC_INVALID_VALUE;
  1529. }
  1530. if(!IsValidALCChannels(schans) || !IsValidALCType(stype) || freq < MIN_OUTPUT_RATE)
  1531. return ALC_INVALID_VALUE;
  1532. if(schans == ALC_BFORMAT3D_SOFT)
  1533. {
  1534. if(!alayout || !ascale || !aorder)
  1535. {
  1536. WARN("Missing ambisonic info for loopback device\n");
  1537. return ALC_INVALID_VALUE;
  1538. }
  1539. if(!IsValidAmbiLayout(alayout) || !IsValidAmbiScaling(ascale))
  1540. return ALC_INVALID_VALUE;
  1541. if(aorder < 1 || aorder > MAX_AMBI_ORDER)
  1542. return ALC_INVALID_VALUE;
  1543. if((alayout == ALC_FUMA_SOFT || ascale == ALC_FUMA_SOFT) && aorder > 3)
  1544. return ALC_INVALID_VALUE;
  1545. }
  1546. }
  1547. if((device->Flags&DEVICE_RUNNING))
  1548. device->Backend->stop();
  1549. device->Flags &= ~DEVICE_RUNNING;
  1550. UpdateClockBase(device);
  1551. if(!loopback)
  1552. {
  1553. device->BufferSize = DEFAULT_UPDATE_SIZE * DEFAULT_NUM_UPDATES;
  1554. device->UpdateSize = DEFAULT_UPDATE_SIZE;
  1555. device->Frequency = DEFAULT_OUTPUT_RATE;
  1556. ConfigValueUInt(devname, nullptr, "frequency", &freq);
  1557. if(freq < 1)
  1558. device->Flags &= ~DEVICE_FREQUENCY_REQUEST;
  1559. else
  1560. {
  1561. freq = maxi(freq, MIN_OUTPUT_RATE);
  1562. device->UpdateSize = (device->UpdateSize*freq + device->Frequency/2) /
  1563. device->Frequency;
  1564. device->BufferSize = (device->BufferSize*freq + device->Frequency/2) /
  1565. device->Frequency;
  1566. device->Frequency = freq;
  1567. device->Flags |= DEVICE_FREQUENCY_REQUEST;
  1568. }
  1569. ConfigValueUInt(devname, nullptr, "period_size", &device->UpdateSize);
  1570. device->UpdateSize = clampu(device->UpdateSize, 64, 8192);
  1571. ALuint periods{};
  1572. if(ConfigValueUInt(devname, nullptr, "periods", &periods))
  1573. device->BufferSize = device->UpdateSize * clampu(periods, 2, 16);
  1574. else
  1575. device->BufferSize = maxu(device->BufferSize, device->UpdateSize*2);
  1576. }
  1577. else
  1578. {
  1579. device->Frequency = freq;
  1580. device->FmtChans = static_cast<DevFmtChannels>(schans);
  1581. device->FmtType = static_cast<DevFmtType>(stype);
  1582. if(schans == ALC_BFORMAT3D_SOFT)
  1583. {
  1584. device->mAmbiOrder = aorder;
  1585. device->mAmbiLayout = static_cast<AmbiLayout>(alayout);
  1586. device->mAmbiScale = static_cast<AmbiNorm>(ascale);
  1587. }
  1588. }
  1589. if(numMono > INT_MAX-numStereo)
  1590. numMono = INT_MAX-numStereo;
  1591. numMono += numStereo;
  1592. if(ConfigValueInt(devname, nullptr, "sources", &numMono))
  1593. {
  1594. if(numMono <= 0)
  1595. numMono = 256;
  1596. }
  1597. else
  1598. numMono = maxi(numMono, 256);
  1599. numStereo = mini(numStereo, numMono);
  1600. numMono -= numStereo;
  1601. device->SourcesMax = numMono + numStereo;
  1602. device->NumMonoSources = numMono;
  1603. device->NumStereoSources = numStereo;
  1604. if(ConfigValueInt(devname, nullptr, "sends", &new_sends))
  1605. new_sends = mini(numSends, clampi(new_sends, 0, MAX_SENDS));
  1606. else
  1607. new_sends = numSends;
  1608. }
  1609. if((device->Flags&DEVICE_RUNNING))
  1610. return ALC_NO_ERROR;
  1611. device->Uhj_Encoder = nullptr;
  1612. device->Bs2b = nullptr;
  1613. device->Limiter = nullptr;
  1614. device->ChannelDelay.clear();
  1615. device->ChannelDelay.shrink_to_fit();
  1616. device->Dry.Buffer = nullptr;
  1617. device->Dry.NumChannels = 0;
  1618. device->RealOut.Buffer = nullptr;
  1619. device->RealOut.NumChannels = 0;
  1620. device->MixBuffer.clear();
  1621. device->MixBuffer.shrink_to_fit();
  1622. UpdateClockBase(device);
  1623. device->FixedLatency = nanoseconds::zero();
  1624. device->DitherSeed = DITHER_RNG_SEED;
  1625. /*************************************************************************
  1626. * Update device format request if HRTF is requested
  1627. */
  1628. device->HrtfStatus = ALC_HRTF_DISABLED_SOFT;
  1629. if(device->Type != Loopback)
  1630. {
  1631. const char *hrtf;
  1632. if(ConfigValueStr(device->DeviceName.c_str(), nullptr, "hrtf", &hrtf))
  1633. {
  1634. if(strcasecmp(hrtf, "true") == 0)
  1635. hrtf_userreq = Hrtf_Enable;
  1636. else if(strcasecmp(hrtf, "false") == 0)
  1637. hrtf_userreq = Hrtf_Disable;
  1638. else if(strcasecmp(hrtf, "auto") != 0)
  1639. ERR("Unexpected hrtf value: %s\n", hrtf);
  1640. }
  1641. if(hrtf_userreq == Hrtf_Enable || (hrtf_userreq != Hrtf_Disable && hrtf_appreq == Hrtf_Enable))
  1642. {
  1643. HrtfEntry *hrtf{nullptr};
  1644. if(device->HrtfList.empty())
  1645. device->HrtfList = EnumerateHrtf(device->DeviceName.c_str());
  1646. if(!device->HrtfList.empty())
  1647. {
  1648. if(hrtf_id >= 0 && static_cast<size_t>(hrtf_id) < device->HrtfList.size())
  1649. hrtf = GetLoadedHrtf(device->HrtfList[hrtf_id].hrtf);
  1650. else
  1651. hrtf = GetLoadedHrtf(device->HrtfList.front().hrtf);
  1652. }
  1653. if(hrtf)
  1654. {
  1655. device->FmtChans = DevFmtStereo;
  1656. device->Frequency = hrtf->sampleRate;
  1657. device->Flags |= DEVICE_CHANNELS_REQUEST | DEVICE_FREQUENCY_REQUEST;
  1658. if(HrtfEntry *oldhrtf{device->mHrtf})
  1659. oldhrtf->DecRef();
  1660. device->mHrtf = hrtf;
  1661. }
  1662. else
  1663. {
  1664. hrtf_userreq = Hrtf_Default;
  1665. hrtf_appreq = Hrtf_Disable;
  1666. device->HrtfStatus = ALC_HRTF_UNSUPPORTED_FORMAT_SOFT;
  1667. }
  1668. }
  1669. }
  1670. oldFreq = device->Frequency;
  1671. oldChans = device->FmtChans;
  1672. oldType = device->FmtType;
  1673. TRACE("Pre-reset: %s%s, %s%s, %s%uhz, %u / %u buffer\n",
  1674. (device->Flags&DEVICE_CHANNELS_REQUEST)?"*":"", DevFmtChannelsString(device->FmtChans),
  1675. (device->Flags&DEVICE_SAMPLE_TYPE_REQUEST)?"*":"", DevFmtTypeString(device->FmtType),
  1676. (device->Flags&DEVICE_FREQUENCY_REQUEST)?"*":"", device->Frequency,
  1677. device->UpdateSize, device->BufferSize);
  1678. try {
  1679. if(device->Backend->reset() == ALC_FALSE)
  1680. return ALC_INVALID_DEVICE;
  1681. }
  1682. catch(std::exception &e) {
  1683. ERR("Device reset failed: %s\n", e.what());
  1684. return ALC_INVALID_DEVICE;
  1685. }
  1686. if(device->FmtChans != oldChans && (device->Flags&DEVICE_CHANNELS_REQUEST))
  1687. {
  1688. ERR("Failed to set %s, got %s instead\n", DevFmtChannelsString(oldChans),
  1689. DevFmtChannelsString(device->FmtChans));
  1690. device->Flags &= ~DEVICE_CHANNELS_REQUEST;
  1691. }
  1692. if(device->FmtType != oldType && (device->Flags&DEVICE_SAMPLE_TYPE_REQUEST))
  1693. {
  1694. ERR("Failed to set %s, got %s instead\n", DevFmtTypeString(oldType),
  1695. DevFmtTypeString(device->FmtType));
  1696. device->Flags &= ~DEVICE_SAMPLE_TYPE_REQUEST;
  1697. }
  1698. if(device->Frequency != oldFreq && (device->Flags&DEVICE_FREQUENCY_REQUEST))
  1699. {
  1700. ERR("Failed to set %uhz, got %uhz instead\n", oldFreq, device->Frequency);
  1701. device->Flags &= ~DEVICE_FREQUENCY_REQUEST;
  1702. }
  1703. if((device->UpdateSize&3) != 0)
  1704. {
  1705. if((CPUCapFlags&CPU_CAP_SSE))
  1706. WARN("SSE performs best with multiple of 4 update sizes (%u)\n", device->UpdateSize);
  1707. if((CPUCapFlags&CPU_CAP_NEON))
  1708. WARN("NEON performs best with multiple of 4 update sizes (%u)\n", device->UpdateSize);
  1709. }
  1710. TRACE("Post-reset: %s, %s, %uhz, %u / %u buffer\n",
  1711. DevFmtChannelsString(device->FmtChans), DevFmtTypeString(device->FmtType),
  1712. device->Frequency, device->UpdateSize, device->BufferSize);
  1713. aluInitRenderer(device, hrtf_id, hrtf_appreq, hrtf_userreq);
  1714. TRACE("Channel config, Main: %d, Real: %d\n", device->Dry.NumChannels,
  1715. device->RealOut.NumChannels);
  1716. /* Allocate extra channels for any post-filter output. */
  1717. const ALsizei num_chans{device->Dry.NumChannels + device->RealOut.NumChannels};
  1718. TRACE("Allocating %d channels, %zu bytes\n", num_chans,
  1719. num_chans*sizeof(device->MixBuffer[0]));
  1720. device->MixBuffer.resize(num_chans);
  1721. device->Dry.Buffer = &reinterpret_cast<ALfloat(&)[BUFFERSIZE]>(device->MixBuffer[0]);
  1722. if(device->RealOut.NumChannels != 0)
  1723. device->RealOut.Buffer = device->Dry.Buffer + device->Dry.NumChannels;
  1724. else
  1725. {
  1726. device->RealOut.Buffer = device->Dry.Buffer;
  1727. device->RealOut.NumChannels = device->Dry.NumChannels;
  1728. }
  1729. device->NumAuxSends = new_sends;
  1730. TRACE("Max sources: %d (%d + %d), effect slots: %d, sends: %d\n",
  1731. device->SourcesMax, device->NumMonoSources, device->NumStereoSources,
  1732. device->AuxiliaryEffectSlotMax, device->NumAuxSends);
  1733. device->DitherDepth = 0.0f;
  1734. if(GetConfigValueBool(device->DeviceName.c_str(), nullptr, "dither", 1))
  1735. {
  1736. ALint depth = 0;
  1737. ConfigValueInt(device->DeviceName.c_str(), nullptr, "dither-depth", &depth);
  1738. if(depth <= 0)
  1739. {
  1740. switch(device->FmtType)
  1741. {
  1742. case DevFmtByte:
  1743. case DevFmtUByte:
  1744. depth = 8;
  1745. break;
  1746. case DevFmtShort:
  1747. case DevFmtUShort:
  1748. depth = 16;
  1749. break;
  1750. case DevFmtInt:
  1751. case DevFmtUInt:
  1752. case DevFmtFloat:
  1753. break;
  1754. }
  1755. }
  1756. if(depth > 0)
  1757. {
  1758. depth = clampi(depth, 2, 24);
  1759. device->DitherDepth = std::pow(2.0f, static_cast<ALfloat>(depth-1));
  1760. }
  1761. }
  1762. if(!(device->DitherDepth > 0.0f))
  1763. TRACE("Dithering disabled\n");
  1764. else
  1765. TRACE("Dithering enabled (%d-bit, %g)\n", float2int(std::log2(device->DitherDepth)+0.5f)+1,
  1766. device->DitherDepth);
  1767. device->LimiterState = gainLimiter;
  1768. if(ConfigValueBool(device->DeviceName.c_str(), nullptr, "output-limiter", &val))
  1769. gainLimiter = val ? ALC_TRUE : ALC_FALSE;
  1770. /* Valid values for gainLimiter are ALC_DONT_CARE_SOFT, ALC_TRUE, and
  1771. * ALC_FALSE. For ALC_DONT_CARE_SOFT, use the limiter for integer-based
  1772. * output (where samples must be clamped), and don't for floating-point
  1773. * (which can take unclamped samples).
  1774. */
  1775. if(gainLimiter == ALC_DONT_CARE_SOFT)
  1776. {
  1777. switch(device->FmtType)
  1778. {
  1779. case DevFmtByte:
  1780. case DevFmtUByte:
  1781. case DevFmtShort:
  1782. case DevFmtUShort:
  1783. case DevFmtInt:
  1784. case DevFmtUInt:
  1785. gainLimiter = ALC_TRUE;
  1786. break;
  1787. case DevFmtFloat:
  1788. gainLimiter = ALC_FALSE;
  1789. break;
  1790. }
  1791. }
  1792. if(gainLimiter == ALC_FALSE)
  1793. TRACE("Output limiter disabled\n");
  1794. else
  1795. {
  1796. ALfloat thrshld = 1.0f;
  1797. switch(device->FmtType)
  1798. {
  1799. case DevFmtByte:
  1800. case DevFmtUByte:
  1801. thrshld = 127.0f / 128.0f;
  1802. break;
  1803. case DevFmtShort:
  1804. case DevFmtUShort:
  1805. thrshld = 32767.0f / 32768.0f;
  1806. break;
  1807. case DevFmtInt:
  1808. case DevFmtUInt:
  1809. case DevFmtFloat:
  1810. break;
  1811. }
  1812. if(device->DitherDepth > 0.0f)
  1813. thrshld -= 1.0f / device->DitherDepth;
  1814. const float thrshld_dB{std::log10(thrshld) * 20.0f};
  1815. auto limiter = CreateDeviceLimiter(device, thrshld_dB);
  1816. /* Convert the lookahead from samples to nanosamples to nanoseconds. */
  1817. device->FixedLatency += nanoseconds{seconds{limiter->getLookAhead()}} / device->Frequency;
  1818. device->Limiter = std::move(limiter);
  1819. TRACE("Output limiter enabled, %.4fdB limit\n", thrshld_dB);
  1820. }
  1821. aluSelectPostProcess(device);
  1822. TRACE("Fixed device latency: %ldns\n", (long)device->FixedLatency.count());
  1823. /* Need to delay returning failure until replacement Send arrays have been
  1824. * allocated with the appropriate size.
  1825. */
  1826. update_failed = AL_FALSE;
  1827. FPUCtl mixer_mode{};
  1828. context = device->ContextList.load();
  1829. while(context)
  1830. {
  1831. if(context->DefaultSlot)
  1832. {
  1833. ALeffectslot *slot = context->DefaultSlot.get();
  1834. aluInitEffectPanning(slot, device);
  1835. EffectState *state{slot->Effect.State};
  1836. state->mOutBuffer = device->Dry.Buffer;
  1837. state->mOutChannels = device->Dry.NumChannels;
  1838. if(state->deviceUpdate(device) == AL_FALSE)
  1839. update_failed = AL_TRUE;
  1840. else
  1841. UpdateEffectSlotProps(slot, context);
  1842. }
  1843. std::unique_lock<std::mutex> proplock{context->PropLock};
  1844. std::unique_lock<std::mutex> slotlock{context->EffectSlotLock};
  1845. for(auto &sublist : context->EffectSlotList)
  1846. {
  1847. uint64_t usemask = ~sublist.FreeMask;
  1848. while(usemask)
  1849. {
  1850. ALsizei idx = CTZ64(usemask);
  1851. ALeffectslot *slot = sublist.EffectSlots + idx;
  1852. usemask &= ~(1_u64 << idx);
  1853. aluInitEffectPanning(slot, device);
  1854. EffectState *state{slot->Effect.State};
  1855. state->mOutBuffer = device->Dry.Buffer;
  1856. state->mOutChannels = device->Dry.NumChannels;
  1857. if(state->deviceUpdate(device) == AL_FALSE)
  1858. update_failed = AL_TRUE;
  1859. else
  1860. UpdateEffectSlotProps(slot, context);
  1861. }
  1862. }
  1863. slotlock.unlock();
  1864. std::unique_lock<std::mutex> srclock{context->SourceLock};
  1865. for(auto &sublist : context->SourceList)
  1866. {
  1867. uint64_t usemask = ~sublist.FreeMask;
  1868. while(usemask)
  1869. {
  1870. ALsizei idx = CTZ64(usemask);
  1871. ALsource *source = sublist.Sources + idx;
  1872. usemask &= ~(1_u64 << idx);
  1873. if(old_sends != device->NumAuxSends)
  1874. {
  1875. ALsizei s;
  1876. for(s = device->NumAuxSends;s < old_sends;s++)
  1877. {
  1878. if(source->Send[s].Slot)
  1879. DecrementRef(&source->Send[s].Slot->ref);
  1880. source->Send[s].Slot = nullptr;
  1881. }
  1882. source->Send.resize(device->NumAuxSends);
  1883. source->Send.shrink_to_fit();
  1884. for(s = old_sends;s < device->NumAuxSends;s++)
  1885. {
  1886. source->Send[s].Slot = nullptr;
  1887. source->Send[s].Gain = 1.0f;
  1888. source->Send[s].GainHF = 1.0f;
  1889. source->Send[s].HFReference = LOWPASSFREQREF;
  1890. source->Send[s].GainLF = 1.0f;
  1891. source->Send[s].LFReference = HIGHPASSFREQREF;
  1892. }
  1893. }
  1894. source->PropsClean.clear(std::memory_order_release);
  1895. }
  1896. }
  1897. /* Clear any pre-existing voice property structs, in case the number of
  1898. * auxiliary sends is changing. Active sources will have updates
  1899. * respecified in UpdateAllSourceProps.
  1900. */
  1901. ALvoiceProps *vprops{context->FreeVoiceProps.exchange(nullptr, std::memory_order_acq_rel)};
  1902. while(vprops)
  1903. {
  1904. ALvoiceProps *next = vprops->next.load(std::memory_order_relaxed);
  1905. delete vprops;
  1906. vprops = next;
  1907. }
  1908. AllocateVoices(context, context->MaxVoices, old_sends);
  1909. auto voices_end = context->Voices + context->VoiceCount.load(std::memory_order_relaxed);
  1910. std::for_each(context->Voices, voices_end,
  1911. [device](ALvoice *voice) -> void
  1912. {
  1913. delete voice->mUpdate.exchange(nullptr, std::memory_order_acq_rel);
  1914. /* Force the voice to stopped if it was stopping. */
  1915. ALvoice::State vstate{ALvoice::Stopping};
  1916. voice->mPlayState.compare_exchange_strong(vstate, ALvoice::Stopped,
  1917. std::memory_order_acquire, std::memory_order_acquire);
  1918. if(voice->mSourceID.load(std::memory_order_relaxed) == 0u)
  1919. return;
  1920. if(device->AvgSpeakerDist > 0.0f)
  1921. {
  1922. /* Reinitialize the NFC filters for new parameters. */
  1923. ALfloat w1 = SPEEDOFSOUNDMETRESPERSEC /
  1924. (device->AvgSpeakerDist * device->Frequency);
  1925. std::for_each(voice->mDirect.Params, voice->mDirect.Params+voice->mNumChannels,
  1926. [w1](DirectParams &params) noexcept -> void
  1927. { params.NFCtrlFilter.init(w1); }
  1928. );
  1929. }
  1930. }
  1931. );
  1932. srclock.unlock();
  1933. context->PropsClean.test_and_set(std::memory_order_release);
  1934. UpdateContextProps(context);
  1935. context->Listener.PropsClean.test_and_set(std::memory_order_release);
  1936. UpdateListenerProps(context);
  1937. UpdateAllSourceProps(context);
  1938. context = context->next.load(std::memory_order_relaxed);
  1939. }
  1940. mixer_mode.leave();
  1941. if(update_failed)
  1942. return ALC_INVALID_DEVICE;
  1943. if(!(device->Flags&DEVICE_PAUSED))
  1944. {
  1945. if(device->Backend->start() == ALC_FALSE)
  1946. return ALC_INVALID_DEVICE;
  1947. device->Flags |= DEVICE_RUNNING;
  1948. }
  1949. return ALC_NO_ERROR;
  1950. }
  1951. ALCdevice::ALCdevice(DeviceType type) : Type{type}
  1952. {
  1953. }
  1954. /* ALCdevice::~ALCdevice
  1955. *
  1956. * Frees the device structure, and destroys any objects the app failed to
  1957. * delete. Called once there's no more references on the device.
  1958. */
  1959. ALCdevice::~ALCdevice()
  1960. {
  1961. TRACE("%p\n", this);
  1962. Backend = nullptr;
  1963. size_t count{std::accumulate(BufferList.cbegin(), BufferList.cend(), size_t{0u},
  1964. [](size_t cur, const BufferSubList &sublist) noexcept -> size_t
  1965. { return cur + POPCNT64(~sublist.FreeMask); }
  1966. )};
  1967. if(count > 0)
  1968. WARN("%zu Buffer%s not deleted\n", count, (count==1)?"":"s");
  1969. count = std::accumulate(EffectList.cbegin(), EffectList.cend(), size_t{0u},
  1970. [](size_t cur, const EffectSubList &sublist) noexcept -> size_t
  1971. { return cur + POPCNT64(~sublist.FreeMask); }
  1972. );
  1973. if(count > 0)
  1974. WARN("%zu Effect%s not deleted\n", count, (count==1)?"":"s");
  1975. count = std::accumulate(FilterList.cbegin(), FilterList.cend(), size_t{0u},
  1976. [](size_t cur, const FilterSubList &sublist) noexcept -> size_t
  1977. { return cur + POPCNT64(~sublist.FreeMask); }
  1978. );
  1979. if(count > 0)
  1980. WARN("%zu Filter%s not deleted\n", count, (count==1)?"":"s");
  1981. if(mHrtf)
  1982. mHrtf->DecRef();
  1983. mHrtf = nullptr;
  1984. }
  1985. static void ALCdevice_IncRef(ALCdevice *device)
  1986. {
  1987. auto ref = IncrementRef(&device->ref);
  1988. TRACEREF("%p increasing refcount to %u\n", device, ref);
  1989. }
  1990. static void ALCdevice_DecRef(ALCdevice *device)
  1991. {
  1992. auto ref = DecrementRef(&device->ref);
  1993. TRACEREF("%p decreasing refcount to %u\n", device, ref);
  1994. if(UNLIKELY(ref == 0)) delete device;
  1995. }
  1996. /* Simple RAII device reference. Takes the reference of the provided ALCdevice,
  1997. * and decrements it when leaving scope. Movable (transfer reference) but not
  1998. * copyable (no new references).
  1999. */
  2000. class DeviceRef {
  2001. ALCdevice *mDev{nullptr};
  2002. void reset() noexcept
  2003. {
  2004. if(mDev)
  2005. ALCdevice_DecRef(mDev);
  2006. mDev = nullptr;
  2007. }
  2008. public:
  2009. DeviceRef() noexcept = default;
  2010. DeviceRef(DeviceRef&& rhs) noexcept : mDev{rhs.mDev}
  2011. { rhs.mDev = nullptr; }
  2012. explicit DeviceRef(ALCdevice *dev) noexcept : mDev(dev) { }
  2013. ~DeviceRef() { reset(); }
  2014. DeviceRef& operator=(const DeviceRef&) = delete;
  2015. DeviceRef& operator=(DeviceRef&& rhs) noexcept
  2016. {
  2017. reset();
  2018. mDev = rhs.mDev;
  2019. rhs.mDev = nullptr;
  2020. return *this;
  2021. }
  2022. operator bool() const noexcept { return mDev != nullptr; }
  2023. ALCdevice* operator->() noexcept { return mDev; }
  2024. ALCdevice* get() noexcept { return mDev; }
  2025. ALCdevice* release() noexcept
  2026. {
  2027. ALCdevice *ret{mDev};
  2028. mDev = nullptr;
  2029. return ret;
  2030. }
  2031. };
  2032. /* VerifyDevice
  2033. *
  2034. * Checks if the device handle is valid, and returns a new reference if so.
  2035. */
  2036. static DeviceRef VerifyDevice(ALCdevice *device)
  2037. {
  2038. std::lock_guard<std::recursive_mutex> _{ListLock};
  2039. auto iter = std::lower_bound(DeviceList.cbegin(), DeviceList.cend(), device);
  2040. if(iter != DeviceList.cend() && *iter == device)
  2041. {
  2042. ALCdevice_IncRef(*iter);
  2043. return DeviceRef{*iter};
  2044. }
  2045. return DeviceRef{};
  2046. }
  2047. ALCcontext::ALCcontext(ALCdevice *device) : Device{device}
  2048. {
  2049. PropsClean.test_and_set(std::memory_order_relaxed);
  2050. }
  2051. /* InitContext
  2052. *
  2053. * Initializes context fields
  2054. */
  2055. static ALvoid InitContext(ALCcontext *Context)
  2056. {
  2057. ALlistener &listener = Context->Listener;
  2058. ALeffectslotArray *auxslots;
  2059. //Validate Context
  2060. if(!Context->DefaultSlot)
  2061. auxslots = ALeffectslot::CreatePtrArray(0);
  2062. else
  2063. {
  2064. auxslots = ALeffectslot::CreatePtrArray(1);
  2065. (*auxslots)[0] = Context->DefaultSlot.get();
  2066. }
  2067. Context->ActiveAuxSlots.store(auxslots, std::memory_order_relaxed);
  2068. //Set globals
  2069. Context->mDistanceModel = DistanceModel::Default;
  2070. Context->SourceDistanceModel = AL_FALSE;
  2071. Context->DopplerFactor = 1.0f;
  2072. Context->DopplerVelocity = 1.0f;
  2073. Context->SpeedOfSound = SPEEDOFSOUNDMETRESPERSEC;
  2074. Context->MetersPerUnit = AL_DEFAULT_METERS_PER_UNIT;
  2075. Context->ExtensionList = alExtList;
  2076. listener.Params.Matrix = alu::Matrix::Identity();
  2077. listener.Params.Velocity = alu::Vector{};
  2078. listener.Params.Gain = listener.Gain;
  2079. listener.Params.MetersPerUnit = Context->MetersPerUnit;
  2080. listener.Params.DopplerFactor = Context->DopplerFactor;
  2081. listener.Params.SpeedOfSound = Context->SpeedOfSound * Context->DopplerVelocity;
  2082. listener.Params.ReverbSpeedOfSound = listener.Params.SpeedOfSound *
  2083. listener.Params.MetersPerUnit;
  2084. listener.Params.SourceDistanceModel = Context->SourceDistanceModel;
  2085. listener.Params.mDistanceModel = Context->mDistanceModel;
  2086. Context->AsyncEvents = CreateRingBuffer(511, sizeof(AsyncEvent), false);
  2087. StartEventThrd(Context);
  2088. }
  2089. /* ALCcontext::~ALCcontext()
  2090. *
  2091. * Cleans up the context, and destroys any remaining objects the app failed to
  2092. * delete. Called once there's no more references on the context.
  2093. */
  2094. ALCcontext::~ALCcontext()
  2095. {
  2096. TRACE("%p\n", this);
  2097. ALcontextProps *cprops{Update.exchange(nullptr, std::memory_order_relaxed)};
  2098. if(cprops)
  2099. {
  2100. TRACE("Freed unapplied context update %p\n", cprops);
  2101. al_free(cprops);
  2102. }
  2103. size_t count{0};
  2104. cprops = FreeContextProps.exchange(nullptr, std::memory_order_acquire);
  2105. while(cprops)
  2106. {
  2107. ALcontextProps *next{cprops->next.load(std::memory_order_relaxed)};
  2108. al_free(cprops);
  2109. cprops = next;
  2110. ++count;
  2111. }
  2112. TRACE("Freed %zu context property object%s\n", count, (count==1)?"":"s");
  2113. count = std::accumulate(SourceList.cbegin(), SourceList.cend(), size_t{0u},
  2114. [](size_t cur, const SourceSubList &sublist) noexcept -> size_t
  2115. { return cur + POPCNT64(~sublist.FreeMask); }
  2116. );
  2117. if(count > 0)
  2118. WARN("%zu Source%s not deleted\n", count, (count==1)?"":"s");
  2119. SourceList.clear();
  2120. NumSources = 0;
  2121. count = 0;
  2122. ALeffectslotProps *eprops{FreeEffectslotProps.exchange(nullptr, std::memory_order_acquire)};
  2123. while(eprops)
  2124. {
  2125. ALeffectslotProps *next{eprops->next.load(std::memory_order_relaxed)};
  2126. if(eprops->State) eprops->State->DecRef();
  2127. al_free(eprops);
  2128. eprops = next;
  2129. ++count;
  2130. }
  2131. TRACE("Freed %zu AuxiliaryEffectSlot property object%s\n", count, (count==1)?"":"s");
  2132. delete ActiveAuxSlots.exchange(nullptr, std::memory_order_relaxed);
  2133. DefaultSlot = nullptr;
  2134. count = std::accumulate(EffectSlotList.cbegin(), EffectSlotList.cend(), size_t{0u},
  2135. [](size_t cur, const EffectSlotSubList &sublist) noexcept -> size_t
  2136. { return cur + POPCNT64(~sublist.FreeMask); }
  2137. );
  2138. if(count > 0)
  2139. WARN("%zu AuxiliaryEffectSlot%s not deleted\n", count, (count==1)?"":"s");
  2140. EffectSlotList.clear();
  2141. NumEffectSlots = 0;
  2142. count = 0;
  2143. ALvoiceProps *vprops{FreeVoiceProps.exchange(nullptr, std::memory_order_acquire)};
  2144. while(vprops)
  2145. {
  2146. ALvoiceProps *next{vprops->next.load(std::memory_order_relaxed)};
  2147. delete vprops;
  2148. vprops = next;
  2149. ++count;
  2150. }
  2151. TRACE("Freed %zu voice property object%s\n", count, (count==1)?"":"s");
  2152. std::for_each(Voices, Voices + MaxVoices, DeinitVoice);
  2153. al_free(Voices);
  2154. Voices = nullptr;
  2155. VoiceCount.store(0, std::memory_order_relaxed);
  2156. MaxVoices = 0;
  2157. ALlistenerProps *lprops{Listener.Update.exchange(nullptr, std::memory_order_relaxed)};
  2158. if(lprops)
  2159. {
  2160. TRACE("Freed unapplied listener update %p\n", lprops);
  2161. al_free(lprops);
  2162. }
  2163. count = 0;
  2164. lprops = FreeListenerProps.exchange(nullptr, std::memory_order_acquire);
  2165. while(lprops)
  2166. {
  2167. ALlistenerProps *next{lprops->next.load(std::memory_order_relaxed)};
  2168. al_free(lprops);
  2169. lprops = next;
  2170. ++count;
  2171. }
  2172. TRACE("Freed %zu listener property object%s\n", count, (count==1)?"":"s");
  2173. if(AsyncEvents)
  2174. {
  2175. count = 0;
  2176. auto evt_vec = AsyncEvents->getReadVector();
  2177. while(evt_vec.first.len > 0)
  2178. {
  2179. reinterpret_cast<AsyncEvent*>(evt_vec.first.buf)->~AsyncEvent();
  2180. evt_vec.first.buf += sizeof(AsyncEvent);
  2181. evt_vec.first.len -= 1;
  2182. ++count;
  2183. }
  2184. while(evt_vec.second.len > 0)
  2185. {
  2186. reinterpret_cast<AsyncEvent*>(evt_vec.second.buf)->~AsyncEvent();
  2187. evt_vec.second.buf += sizeof(AsyncEvent);
  2188. evt_vec.second.len -= 1;
  2189. ++count;
  2190. }
  2191. if(count > 0)
  2192. TRACE("Destructed %zu orphaned event%s\n", count, (count==1)?"":"s");
  2193. }
  2194. ALCdevice_DecRef(Device);
  2195. }
  2196. /* ReleaseContext
  2197. *
  2198. * Removes the context reference from the given device and removes it from
  2199. * being current on the running thread or globally. Returns true if other
  2200. * contexts still exist on the device.
  2201. */
  2202. static bool ReleaseContext(ALCcontext *context, ALCdevice *device)
  2203. {
  2204. if(LocalContext.get() == context)
  2205. {
  2206. WARN("%p released while current on thread\n", context);
  2207. LocalContext.set(nullptr);
  2208. ALCcontext_DecRef(context);
  2209. }
  2210. ALCcontext *origctx{context};
  2211. if(GlobalContext.compare_exchange_strong(origctx, nullptr))
  2212. ALCcontext_DecRef(context);
  2213. bool ret{true};
  2214. { BackendLockGuard _{*device->Backend};
  2215. origctx = context;
  2216. ALCcontext *newhead{context->next.load(std::memory_order_relaxed)};
  2217. if(!device->ContextList.compare_exchange_strong(origctx, newhead))
  2218. {
  2219. ALCcontext *list;
  2220. do {
  2221. /* origctx is what the desired context failed to match. Try
  2222. * swapping out the next one in the list.
  2223. */
  2224. list = origctx;
  2225. origctx = context;
  2226. } while(!list->next.compare_exchange_strong(origctx, newhead));
  2227. }
  2228. else
  2229. ret = !!newhead;
  2230. }
  2231. /* Make sure the context is finished and no longer processing in the mixer
  2232. * before sending the message queue kill event. The backend's lock does
  2233. * this, although waiting for a non-odd mix count would work too.
  2234. */
  2235. StopEventThrd(context);
  2236. ALCcontext_DecRef(context);
  2237. return ret;
  2238. }
  2239. static void ALCcontext_IncRef(ALCcontext *context)
  2240. {
  2241. auto ref = IncrementRef(&context->ref);
  2242. TRACEREF("%p increasing refcount to %u\n", context, ref);
  2243. }
  2244. void ALCcontext_DecRef(ALCcontext *context)
  2245. {
  2246. auto ref = DecrementRef(&context->ref);
  2247. TRACEREF("%p decreasing refcount to %u\n", context, ref);
  2248. if(UNLIKELY(ref == 0)) delete context;
  2249. }
  2250. /* VerifyContext
  2251. *
  2252. * Checks if the given context is valid, returning a new reference to it if so.
  2253. */
  2254. static ContextRef VerifyContext(ALCcontext *context)
  2255. {
  2256. std::lock_guard<std::recursive_mutex> _{ListLock};
  2257. auto iter = std::lower_bound(ContextList.cbegin(), ContextList.cend(), context);
  2258. if(iter != ContextList.cend() && *iter == context)
  2259. {
  2260. ALCcontext_IncRef(*iter);
  2261. return ContextRef{*iter};
  2262. }
  2263. return ContextRef{};
  2264. }
  2265. /* GetContextRef
  2266. *
  2267. * Returns a new reference to the currently active context for this thread.
  2268. */
  2269. ContextRef GetContextRef(void)
  2270. {
  2271. ALCcontext *context{LocalContext.get()};
  2272. if(context)
  2273. ALCcontext_IncRef(context);
  2274. else
  2275. {
  2276. std::lock_guard<std::recursive_mutex> _{ListLock};
  2277. context = GlobalContext.load(std::memory_order_acquire);
  2278. if(context) ALCcontext_IncRef(context);
  2279. }
  2280. return ContextRef{context};
  2281. }
  2282. void AllocateVoices(ALCcontext *context, ALsizei num_voices, ALsizei old_sends)
  2283. {
  2284. ALCdevice *device{context->Device};
  2285. const ALsizei num_sends{device->NumAuxSends};
  2286. if(num_voices == context->MaxVoices && num_sends == old_sends)
  2287. return;
  2288. /* Allocate the voice pointers, voices, and the voices' stored source
  2289. * property set (including the dynamically-sized Send[] array) in one
  2290. * chunk.
  2291. */
  2292. const size_t sizeof_voice{RoundUp(ALvoice::Sizeof(num_sends), 16)};
  2293. const size_t size{sizeof(ALvoice*) + sizeof_voice};
  2294. auto voices = static_cast<ALvoice**>(al_calloc(16, RoundUp(size*num_voices, 16)));
  2295. auto voice = reinterpret_cast<ALvoice*>(reinterpret_cast<char*>(voices) + RoundUp(num_voices*sizeof(ALvoice*), 16));
  2296. auto viter = voices;
  2297. if(context->Voices)
  2298. {
  2299. const ALsizei v_count = mini(context->VoiceCount.load(std::memory_order_relaxed),
  2300. num_voices);
  2301. const ALsizei s_count = mini(old_sends, num_sends);
  2302. /* Copy the old voice data to the new storage. */
  2303. auto copy_voice = [&voice,num_sends,sizeof_voice,s_count](ALvoice *old_voice) -> ALvoice*
  2304. {
  2305. voice = new (voice) ALvoice{static_cast<size_t>(num_sends)};
  2306. /* Make sure the old voice's Update (if any) is cleared so it
  2307. * doesn't get deleted on deinit.
  2308. */
  2309. voice->mUpdate.store(old_voice->mUpdate.exchange(nullptr, std::memory_order_relaxed),
  2310. std::memory_order_relaxed);
  2311. voice->mSourceID.store(old_voice->mSourceID.load(std::memory_order_relaxed),
  2312. std::memory_order_relaxed);
  2313. voice->mPlayState.store(old_voice->mPlayState.load(std::memory_order_relaxed),
  2314. std::memory_order_relaxed);
  2315. voice->mProps = old_voice->mProps;
  2316. /* Clear extraneous property set sends. */
  2317. std::fill(std::begin(voice->mProps.Send)+s_count, std::end(voice->mProps.Send),
  2318. ALvoiceProps::SendData{});
  2319. voice->mPosition.store(old_voice->mPosition.load(std::memory_order_relaxed),
  2320. std::memory_order_relaxed);
  2321. voice->mPositionFrac.store(old_voice->mPositionFrac.load(std::memory_order_relaxed),
  2322. std::memory_order_relaxed);
  2323. voice->mCurrentBuffer.store(old_voice->mCurrentBuffer.load(std::memory_order_relaxed),
  2324. std::memory_order_relaxed);
  2325. voice->mLoopBuffer.store(old_voice->mLoopBuffer.load(std::memory_order_relaxed),
  2326. std::memory_order_relaxed);
  2327. voice->mFrequency = old_voice->mFrequency;
  2328. voice->mFmtChannels = old_voice->mFmtChannels;
  2329. voice->mNumChannels = old_voice->mNumChannels;
  2330. voice->mSampleSize = old_voice->mSampleSize;
  2331. voice->mStep = old_voice->mStep;
  2332. voice->mResampler = old_voice->mResampler;
  2333. voice->mResampleState = old_voice->mResampleState;
  2334. voice->mFlags = old_voice->mFlags;
  2335. std::copy(old_voice->mResampleData.begin(), old_voice->mResampleData.end(),
  2336. voice->mResampleData.end());
  2337. voice->mDirect = old_voice->mDirect;
  2338. std::copy_n(old_voice->mSend.begin(), s_count, voice->mSend.begin());
  2339. /* Set this voice's reference. */
  2340. ALvoice *ret = voice;
  2341. /* Increment pointer to the next storage space. */
  2342. voice = reinterpret_cast<ALvoice*>(reinterpret_cast<char*>(voice) + sizeof_voice);
  2343. return ret;
  2344. };
  2345. viter = std::transform(context->Voices, context->Voices+v_count, viter, copy_voice);
  2346. /* Deinit old voices. */
  2347. auto voices_end = context->Voices + context->MaxVoices;
  2348. std::for_each(context->Voices, voices_end, DeinitVoice);
  2349. }
  2350. /* Finish setting the voices and references. */
  2351. auto init_voice = [&voice,num_sends,sizeof_voice]() -> ALvoice*
  2352. {
  2353. ALvoice *ret = new (voice) ALvoice{static_cast<size_t>(num_sends)};
  2354. voice = reinterpret_cast<ALvoice*>(reinterpret_cast<char*>(voice) + sizeof_voice);
  2355. return ret;
  2356. };
  2357. std::generate(viter, voices+num_voices, init_voice);
  2358. al_free(context->Voices);
  2359. context->Voices = voices;
  2360. context->MaxVoices = num_voices;
  2361. context->VoiceCount = mini(context->VoiceCount.load(std::memory_order_relaxed), num_voices);
  2362. }
  2363. /************************************************
  2364. * Standard ALC functions
  2365. ************************************************/
  2366. /* alcGetError
  2367. *
  2368. * Return last ALC generated error code for the given device
  2369. */
  2370. ALC_API ALCenum ALC_APIENTRY alcGetError(ALCdevice *device)
  2371. START_API_FUNC
  2372. {
  2373. DeviceRef dev{VerifyDevice(device)};
  2374. if(dev) return dev->LastError.exchange(ALC_NO_ERROR);
  2375. return LastNullDeviceError.exchange(ALC_NO_ERROR);
  2376. }
  2377. END_API_FUNC
  2378. /* alcSuspendContext
  2379. *
  2380. * Suspends updates for the given context
  2381. */
  2382. ALC_API ALCvoid ALC_APIENTRY alcSuspendContext(ALCcontext *context)
  2383. START_API_FUNC
  2384. {
  2385. if(!SuspendDefers)
  2386. return;
  2387. ContextRef ctx{VerifyContext(context)};
  2388. if(!ctx)
  2389. alcSetError(nullptr, ALC_INVALID_CONTEXT);
  2390. else
  2391. ALCcontext_DeferUpdates(ctx.get());
  2392. }
  2393. END_API_FUNC
  2394. /* alcProcessContext
  2395. *
  2396. * Resumes processing updates for the given context
  2397. */
  2398. ALC_API ALCvoid ALC_APIENTRY alcProcessContext(ALCcontext *context)
  2399. START_API_FUNC
  2400. {
  2401. if(!SuspendDefers)
  2402. return;
  2403. ContextRef ctx{VerifyContext(context)};
  2404. if(!ctx)
  2405. alcSetError(nullptr, ALC_INVALID_CONTEXT);
  2406. else
  2407. ALCcontext_ProcessUpdates(ctx.get());
  2408. }
  2409. END_API_FUNC
  2410. /* alcGetString
  2411. *
  2412. * Returns information about the device, and error strings
  2413. */
  2414. ALC_API const ALCchar* ALC_APIENTRY alcGetString(ALCdevice *Device, ALCenum param)
  2415. START_API_FUNC
  2416. {
  2417. const ALCchar *value = nullptr;
  2418. DeviceRef dev;
  2419. switch(param)
  2420. {
  2421. case ALC_NO_ERROR:
  2422. value = alcNoError;
  2423. break;
  2424. case ALC_INVALID_ENUM:
  2425. value = alcErrInvalidEnum;
  2426. break;
  2427. case ALC_INVALID_VALUE:
  2428. value = alcErrInvalidValue;
  2429. break;
  2430. case ALC_INVALID_DEVICE:
  2431. value = alcErrInvalidDevice;
  2432. break;
  2433. case ALC_INVALID_CONTEXT:
  2434. value = alcErrInvalidContext;
  2435. break;
  2436. case ALC_OUT_OF_MEMORY:
  2437. value = alcErrOutOfMemory;
  2438. break;
  2439. case ALC_DEVICE_SPECIFIER:
  2440. value = alcDefaultName;
  2441. break;
  2442. case ALC_ALL_DEVICES_SPECIFIER:
  2443. dev = VerifyDevice(Device);
  2444. if(dev)
  2445. value = dev->DeviceName.c_str();
  2446. else
  2447. {
  2448. ProbeAllDevicesList();
  2449. value = alcAllDevicesList.c_str();
  2450. }
  2451. break;
  2452. case ALC_CAPTURE_DEVICE_SPECIFIER:
  2453. dev = VerifyDevice(Device);
  2454. if(dev)
  2455. value = dev->DeviceName.c_str();
  2456. else
  2457. {
  2458. ProbeCaptureDeviceList();
  2459. value = alcCaptureDeviceList.c_str();
  2460. }
  2461. break;
  2462. /* Default devices are always first in the list */
  2463. case ALC_DEFAULT_DEVICE_SPECIFIER:
  2464. value = alcDefaultName;
  2465. break;
  2466. case ALC_DEFAULT_ALL_DEVICES_SPECIFIER:
  2467. if(alcAllDevicesList.empty())
  2468. ProbeAllDevicesList();
  2469. /* Copy first entry as default. */
  2470. alcDefaultAllDevicesSpecifier = alcAllDevicesList.c_str();
  2471. value = alcDefaultAllDevicesSpecifier.c_str();
  2472. break;
  2473. case ALC_CAPTURE_DEFAULT_DEVICE_SPECIFIER:
  2474. if(alcCaptureDeviceList.empty())
  2475. ProbeCaptureDeviceList();
  2476. /* Copy first entry as default. */
  2477. alcCaptureDefaultDeviceSpecifier = alcCaptureDeviceList.c_str();
  2478. value = alcCaptureDefaultDeviceSpecifier.c_str();
  2479. break;
  2480. case ALC_EXTENSIONS:
  2481. dev = VerifyDevice(Device);
  2482. if(dev) value = alcExtensionList;
  2483. else value = alcNoDeviceExtList;
  2484. break;
  2485. case ALC_HRTF_SPECIFIER_SOFT:
  2486. dev = VerifyDevice(Device);
  2487. if(!dev)
  2488. alcSetError(nullptr, ALC_INVALID_DEVICE);
  2489. else
  2490. {
  2491. std::lock_guard<std::mutex> _{dev->StateLock};
  2492. value = (dev->mHrtf ? dev->HrtfName.c_str() : "");
  2493. }
  2494. break;
  2495. default:
  2496. dev = VerifyDevice(Device);
  2497. alcSetError(dev.get(), ALC_INVALID_ENUM);
  2498. break;
  2499. }
  2500. return value;
  2501. }
  2502. END_API_FUNC
  2503. static inline ALCsizei NumAttrsForDevice(ALCdevice *device)
  2504. {
  2505. if(device->Type == Capture) return 9;
  2506. if(device->Type != Loopback) return 29;
  2507. if(device->FmtChans == DevFmtAmbi3D)
  2508. return 35;
  2509. return 29;
  2510. }
  2511. static ALCsizei GetIntegerv(ALCdevice *device, ALCenum param, ALCsizei size, ALCint *values)
  2512. {
  2513. ALCsizei i;
  2514. if(size <= 0 || values == nullptr)
  2515. {
  2516. alcSetError(device, ALC_INVALID_VALUE);
  2517. return 0;
  2518. }
  2519. if(!device)
  2520. {
  2521. switch(param)
  2522. {
  2523. case ALC_MAJOR_VERSION:
  2524. values[0] = alcMajorVersion;
  2525. return 1;
  2526. case ALC_MINOR_VERSION:
  2527. values[0] = alcMinorVersion;
  2528. return 1;
  2529. case ALC_ATTRIBUTES_SIZE:
  2530. case ALC_ALL_ATTRIBUTES:
  2531. case ALC_FREQUENCY:
  2532. case ALC_REFRESH:
  2533. case ALC_SYNC:
  2534. case ALC_MONO_SOURCES:
  2535. case ALC_STEREO_SOURCES:
  2536. case ALC_CAPTURE_SAMPLES:
  2537. case ALC_FORMAT_CHANNELS_SOFT:
  2538. case ALC_FORMAT_TYPE_SOFT:
  2539. case ALC_AMBISONIC_LAYOUT_SOFT:
  2540. case ALC_AMBISONIC_SCALING_SOFT:
  2541. case ALC_AMBISONIC_ORDER_SOFT:
  2542. case ALC_MAX_AMBISONIC_ORDER_SOFT:
  2543. alcSetError(nullptr, ALC_INVALID_DEVICE);
  2544. return 0;
  2545. default:
  2546. alcSetError(nullptr, ALC_INVALID_ENUM);
  2547. return 0;
  2548. }
  2549. return 0;
  2550. }
  2551. if(device->Type == Capture)
  2552. {
  2553. switch(param)
  2554. {
  2555. case ALC_ATTRIBUTES_SIZE:
  2556. values[0] = NumAttrsForDevice(device);
  2557. return 1;
  2558. case ALC_ALL_ATTRIBUTES:
  2559. i = 0;
  2560. if(size < NumAttrsForDevice(device))
  2561. alcSetError(device, ALC_INVALID_VALUE);
  2562. else
  2563. {
  2564. std::lock_guard<std::mutex> _{device->StateLock};
  2565. values[i++] = ALC_MAJOR_VERSION;
  2566. values[i++] = alcMajorVersion;
  2567. values[i++] = ALC_MINOR_VERSION;
  2568. values[i++] = alcMinorVersion;
  2569. values[i++] = ALC_CAPTURE_SAMPLES;
  2570. values[i++] = device->Backend->availableSamples();
  2571. values[i++] = ALC_CONNECTED;
  2572. values[i++] = device->Connected.load(std::memory_order_relaxed);
  2573. values[i++] = 0;
  2574. }
  2575. return i;
  2576. case ALC_MAJOR_VERSION:
  2577. values[0] = alcMajorVersion;
  2578. return 1;
  2579. case ALC_MINOR_VERSION:
  2580. values[0] = alcMinorVersion;
  2581. return 1;
  2582. case ALC_CAPTURE_SAMPLES:
  2583. { std::lock_guard<std::mutex> _{device->StateLock};
  2584. values[0] = device->Backend->availableSamples();
  2585. }
  2586. return 1;
  2587. case ALC_CONNECTED:
  2588. { std::lock_guard<std::mutex> _{device->StateLock};
  2589. values[0] = device->Connected.load(std::memory_order_acquire);
  2590. }
  2591. return 1;
  2592. default:
  2593. alcSetError(device, ALC_INVALID_ENUM);
  2594. return 0;
  2595. }
  2596. return 0;
  2597. }
  2598. /* render device */
  2599. switch(param)
  2600. {
  2601. case ALC_ATTRIBUTES_SIZE:
  2602. values[0] = NumAttrsForDevice(device);
  2603. return 1;
  2604. case ALC_ALL_ATTRIBUTES:
  2605. i = 0;
  2606. if(size < NumAttrsForDevice(device))
  2607. alcSetError(device, ALC_INVALID_VALUE);
  2608. else
  2609. {
  2610. std::lock_guard<std::mutex> _{device->StateLock};
  2611. values[i++] = ALC_MAJOR_VERSION;
  2612. values[i++] = alcMajorVersion;
  2613. values[i++] = ALC_MINOR_VERSION;
  2614. values[i++] = alcMinorVersion;
  2615. values[i++] = ALC_EFX_MAJOR_VERSION;
  2616. values[i++] = alcEFXMajorVersion;
  2617. values[i++] = ALC_EFX_MINOR_VERSION;
  2618. values[i++] = alcEFXMinorVersion;
  2619. values[i++] = ALC_FREQUENCY;
  2620. values[i++] = device->Frequency;
  2621. if(device->Type != Loopback)
  2622. {
  2623. values[i++] = ALC_REFRESH;
  2624. values[i++] = device->Frequency / device->UpdateSize;
  2625. values[i++] = ALC_SYNC;
  2626. values[i++] = ALC_FALSE;
  2627. }
  2628. else
  2629. {
  2630. if(device->FmtChans == DevFmtAmbi3D)
  2631. {
  2632. values[i++] = ALC_AMBISONIC_LAYOUT_SOFT;
  2633. values[i++] = static_cast<ALCint>(device->mAmbiLayout);
  2634. values[i++] = ALC_AMBISONIC_SCALING_SOFT;
  2635. values[i++] = static_cast<ALCint>(device->mAmbiScale);
  2636. values[i++] = ALC_AMBISONIC_ORDER_SOFT;
  2637. values[i++] = device->mAmbiOrder;
  2638. }
  2639. values[i++] = ALC_FORMAT_CHANNELS_SOFT;
  2640. values[i++] = device->FmtChans;
  2641. values[i++] = ALC_FORMAT_TYPE_SOFT;
  2642. values[i++] = device->FmtType;
  2643. }
  2644. values[i++] = ALC_MONO_SOURCES;
  2645. values[i++] = device->NumMonoSources;
  2646. values[i++] = ALC_STEREO_SOURCES;
  2647. values[i++] = device->NumStereoSources;
  2648. values[i++] = ALC_MAX_AUXILIARY_SENDS;
  2649. values[i++] = device->NumAuxSends;
  2650. values[i++] = ALC_HRTF_SOFT;
  2651. values[i++] = (device->mHrtf ? ALC_TRUE : ALC_FALSE);
  2652. values[i++] = ALC_HRTF_STATUS_SOFT;
  2653. values[i++] = device->HrtfStatus;
  2654. values[i++] = ALC_OUTPUT_LIMITER_SOFT;
  2655. values[i++] = device->Limiter ? ALC_TRUE : ALC_FALSE;
  2656. values[i++] = ALC_MAX_AMBISONIC_ORDER_SOFT;
  2657. values[i++] = MAX_AMBI_ORDER;
  2658. values[i++] = 0;
  2659. }
  2660. return i;
  2661. case ALC_MAJOR_VERSION:
  2662. values[0] = alcMajorVersion;
  2663. return 1;
  2664. case ALC_MINOR_VERSION:
  2665. values[0] = alcMinorVersion;
  2666. return 1;
  2667. case ALC_EFX_MAJOR_VERSION:
  2668. values[0] = alcEFXMajorVersion;
  2669. return 1;
  2670. case ALC_EFX_MINOR_VERSION:
  2671. values[0] = alcEFXMinorVersion;
  2672. return 1;
  2673. case ALC_FREQUENCY:
  2674. values[0] = device->Frequency;
  2675. return 1;
  2676. case ALC_REFRESH:
  2677. if(device->Type == Loopback)
  2678. {
  2679. alcSetError(device, ALC_INVALID_DEVICE);
  2680. return 0;
  2681. }
  2682. { std::lock_guard<std::mutex> _{device->StateLock};
  2683. values[0] = device->Frequency / device->UpdateSize;
  2684. }
  2685. return 1;
  2686. case ALC_SYNC:
  2687. if(device->Type == Loopback)
  2688. {
  2689. alcSetError(device, ALC_INVALID_DEVICE);
  2690. return 0;
  2691. }
  2692. values[0] = ALC_FALSE;
  2693. return 1;
  2694. case ALC_FORMAT_CHANNELS_SOFT:
  2695. if(device->Type != Loopback)
  2696. {
  2697. alcSetError(device, ALC_INVALID_DEVICE);
  2698. return 0;
  2699. }
  2700. values[0] = device->FmtChans;
  2701. return 1;
  2702. case ALC_FORMAT_TYPE_SOFT:
  2703. if(device->Type != Loopback)
  2704. {
  2705. alcSetError(device, ALC_INVALID_DEVICE);
  2706. return 0;
  2707. }
  2708. values[0] = device->FmtType;
  2709. return 1;
  2710. case ALC_AMBISONIC_LAYOUT_SOFT:
  2711. if(device->Type != Loopback || device->FmtChans != DevFmtAmbi3D)
  2712. {
  2713. alcSetError(device, ALC_INVALID_DEVICE);
  2714. return 0;
  2715. }
  2716. values[0] = static_cast<ALCint>(device->mAmbiLayout);
  2717. return 1;
  2718. case ALC_AMBISONIC_SCALING_SOFT:
  2719. if(device->Type != Loopback || device->FmtChans != DevFmtAmbi3D)
  2720. {
  2721. alcSetError(device, ALC_INVALID_DEVICE);
  2722. return 0;
  2723. }
  2724. values[0] = static_cast<ALCint>(device->mAmbiScale);
  2725. return 1;
  2726. case ALC_AMBISONIC_ORDER_SOFT:
  2727. if(device->Type != Loopback || device->FmtChans != DevFmtAmbi3D)
  2728. {
  2729. alcSetError(device, ALC_INVALID_DEVICE);
  2730. return 0;
  2731. }
  2732. values[0] = device->mAmbiOrder;
  2733. return 1;
  2734. case ALC_MONO_SOURCES:
  2735. values[0] = device->NumMonoSources;
  2736. return 1;
  2737. case ALC_STEREO_SOURCES:
  2738. values[0] = device->NumStereoSources;
  2739. return 1;
  2740. case ALC_MAX_AUXILIARY_SENDS:
  2741. values[0] = device->NumAuxSends;
  2742. return 1;
  2743. case ALC_CONNECTED:
  2744. { std::lock_guard<std::mutex> _{device->StateLock};
  2745. values[0] = device->Connected.load(std::memory_order_acquire);
  2746. }
  2747. return 1;
  2748. case ALC_HRTF_SOFT:
  2749. values[0] = (device->mHrtf ? ALC_TRUE : ALC_FALSE);
  2750. return 1;
  2751. case ALC_HRTF_STATUS_SOFT:
  2752. values[0] = device->HrtfStatus;
  2753. return 1;
  2754. case ALC_NUM_HRTF_SPECIFIERS_SOFT:
  2755. { std::lock_guard<std::mutex> _{device->StateLock};
  2756. device->HrtfList.clear();
  2757. device->HrtfList = EnumerateHrtf(device->DeviceName.c_str());
  2758. values[0] = static_cast<ALCint>(device->HrtfList.size());
  2759. }
  2760. return 1;
  2761. case ALC_OUTPUT_LIMITER_SOFT:
  2762. values[0] = device->Limiter ? ALC_TRUE : ALC_FALSE;
  2763. return 1;
  2764. case ALC_MAX_AMBISONIC_ORDER_SOFT:
  2765. values[0] = MAX_AMBI_ORDER;
  2766. return 1;
  2767. default:
  2768. alcSetError(device, ALC_INVALID_ENUM);
  2769. return 0;
  2770. }
  2771. return 0;
  2772. }
  2773. /* alcGetIntegerv
  2774. *
  2775. * Returns information about the device and the version of OpenAL
  2776. */
  2777. ALC_API void ALC_APIENTRY alcGetIntegerv(ALCdevice *device, ALCenum param, ALCsizei size, ALCint *values)
  2778. START_API_FUNC
  2779. {
  2780. DeviceRef dev{VerifyDevice(device)};
  2781. if(size <= 0 || values == nullptr)
  2782. alcSetError(dev.get(), ALC_INVALID_VALUE);
  2783. else
  2784. GetIntegerv(dev.get(), param, size, values);
  2785. }
  2786. END_API_FUNC
  2787. ALC_API void ALC_APIENTRY alcGetInteger64vSOFT(ALCdevice *device, ALCenum pname, ALCsizei size, ALCint64SOFT *values)
  2788. START_API_FUNC
  2789. {
  2790. DeviceRef dev{VerifyDevice(device)};
  2791. if(size <= 0 || values == nullptr)
  2792. alcSetError(dev.get(), ALC_INVALID_VALUE);
  2793. else if(!dev || dev->Type == Capture)
  2794. {
  2795. al::vector<ALCint> ivals(size);
  2796. size = GetIntegerv(dev.get(), pname, size, ivals.data());
  2797. std::copy(ivals.begin(), ivals.begin()+size, values);
  2798. }
  2799. else /* render device */
  2800. {
  2801. switch(pname)
  2802. {
  2803. case ALC_ATTRIBUTES_SIZE:
  2804. *values = NumAttrsForDevice(dev.get())+4;
  2805. break;
  2806. case ALC_ALL_ATTRIBUTES:
  2807. if(size < NumAttrsForDevice(dev.get())+4)
  2808. alcSetError(dev.get(), ALC_INVALID_VALUE);
  2809. else
  2810. {
  2811. ALsizei i{0};
  2812. std::lock_guard<std::mutex> _{dev->StateLock};
  2813. values[i++] = ALC_FREQUENCY;
  2814. values[i++] = dev->Frequency;
  2815. if(dev->Type != Loopback)
  2816. {
  2817. values[i++] = ALC_REFRESH;
  2818. values[i++] = dev->Frequency / dev->UpdateSize;
  2819. values[i++] = ALC_SYNC;
  2820. values[i++] = ALC_FALSE;
  2821. }
  2822. else
  2823. {
  2824. if(dev->FmtChans == DevFmtAmbi3D)
  2825. {
  2826. values[i++] = ALC_AMBISONIC_LAYOUT_SOFT;
  2827. values[i++] = static_cast<ALCint64SOFT>(dev->mAmbiLayout);
  2828. values[i++] = ALC_AMBISONIC_SCALING_SOFT;
  2829. values[i++] = static_cast<ALCint64SOFT>(dev->mAmbiScale);
  2830. values[i++] = ALC_AMBISONIC_ORDER_SOFT;
  2831. values[i++] = dev->mAmbiOrder;
  2832. }
  2833. values[i++] = ALC_FORMAT_CHANNELS_SOFT;
  2834. values[i++] = dev->FmtChans;
  2835. values[i++] = ALC_FORMAT_TYPE_SOFT;
  2836. values[i++] = dev->FmtType;
  2837. }
  2838. values[i++] = ALC_MONO_SOURCES;
  2839. values[i++] = dev->NumMonoSources;
  2840. values[i++] = ALC_STEREO_SOURCES;
  2841. values[i++] = dev->NumStereoSources;
  2842. values[i++] = ALC_MAX_AUXILIARY_SENDS;
  2843. values[i++] = dev->NumAuxSends;
  2844. values[i++] = ALC_HRTF_SOFT;
  2845. values[i++] = (dev->mHrtf ? ALC_TRUE : ALC_FALSE);
  2846. values[i++] = ALC_HRTF_STATUS_SOFT;
  2847. values[i++] = dev->HrtfStatus;
  2848. values[i++] = ALC_OUTPUT_LIMITER_SOFT;
  2849. values[i++] = dev->Limiter ? ALC_TRUE : ALC_FALSE;
  2850. ClockLatency clock{GetClockLatency(dev.get())};
  2851. values[i++] = ALC_DEVICE_CLOCK_SOFT;
  2852. values[i++] = clock.ClockTime.count();
  2853. values[i++] = ALC_DEVICE_LATENCY_SOFT;
  2854. values[i++] = clock.Latency.count();
  2855. values[i++] = 0;
  2856. }
  2857. break;
  2858. case ALC_DEVICE_CLOCK_SOFT:
  2859. { std::lock_guard<std::mutex> _{dev->StateLock};
  2860. nanoseconds basecount;
  2861. ALuint samplecount;
  2862. ALuint refcount;
  2863. do {
  2864. while(((refcount=ReadRef(&dev->MixCount))&1) != 0)
  2865. std::this_thread::yield();
  2866. basecount = dev->ClockBase;
  2867. samplecount = dev->SamplesDone;
  2868. } while(refcount != ReadRef(&dev->MixCount));
  2869. basecount += nanoseconds{seconds{samplecount}} / dev->Frequency;
  2870. *values = basecount.count();
  2871. }
  2872. break;
  2873. case ALC_DEVICE_LATENCY_SOFT:
  2874. { std::lock_guard<std::mutex> _{dev->StateLock};
  2875. ClockLatency clock{GetClockLatency(dev.get())};
  2876. *values = clock.Latency.count();
  2877. }
  2878. break;
  2879. case ALC_DEVICE_CLOCK_LATENCY_SOFT:
  2880. if(size < 2)
  2881. alcSetError(dev.get(), ALC_INVALID_VALUE);
  2882. else
  2883. {
  2884. std::lock_guard<std::mutex> _{dev->StateLock};
  2885. ClockLatency clock{GetClockLatency(dev.get())};
  2886. values[0] = clock.ClockTime.count();
  2887. values[1] = clock.Latency.count();
  2888. }
  2889. break;
  2890. default:
  2891. al::vector<ALCint> ivals(size);
  2892. size = GetIntegerv(dev.get(), pname, size, ivals.data());
  2893. std::copy(ivals.begin(), ivals.begin()+size, values);
  2894. break;
  2895. }
  2896. }
  2897. }
  2898. END_API_FUNC
  2899. /* alcIsExtensionPresent
  2900. *
  2901. * Determines if there is support for a particular extension
  2902. */
  2903. ALC_API ALCboolean ALC_APIENTRY alcIsExtensionPresent(ALCdevice *device, const ALCchar *extName)
  2904. START_API_FUNC
  2905. {
  2906. DeviceRef dev{VerifyDevice(device)};
  2907. if(!extName)
  2908. alcSetError(dev.get(), ALC_INVALID_VALUE);
  2909. else
  2910. {
  2911. size_t len = strlen(extName);
  2912. const char *ptr = (dev ? alcExtensionList : alcNoDeviceExtList);
  2913. while(ptr && *ptr)
  2914. {
  2915. if(strncasecmp(ptr, extName, len) == 0 &&
  2916. (ptr[len] == '\0' || isspace(ptr[len])))
  2917. return ALC_TRUE;
  2918. if((ptr=strchr(ptr, ' ')) != nullptr)
  2919. {
  2920. do {
  2921. ++ptr;
  2922. } while(isspace(*ptr));
  2923. }
  2924. }
  2925. }
  2926. return ALC_FALSE;
  2927. }
  2928. END_API_FUNC
  2929. /* alcGetProcAddress
  2930. *
  2931. * Retrieves the function address for a particular extension function
  2932. */
  2933. ALC_API ALCvoid* ALC_APIENTRY alcGetProcAddress(ALCdevice *device, const ALCchar *funcName)
  2934. START_API_FUNC
  2935. {
  2936. if(!funcName)
  2937. {
  2938. DeviceRef dev{VerifyDevice(device)};
  2939. alcSetError(dev.get(), ALC_INVALID_VALUE);
  2940. }
  2941. else
  2942. {
  2943. for(const auto &func : alcFunctions)
  2944. {
  2945. if(strcmp(func.funcName, funcName) == 0)
  2946. return func.address;
  2947. }
  2948. }
  2949. return nullptr;
  2950. }
  2951. END_API_FUNC
  2952. /* alcGetEnumValue
  2953. *
  2954. * Get the value for a particular ALC enumeration name
  2955. */
  2956. ALC_API ALCenum ALC_APIENTRY alcGetEnumValue(ALCdevice *device, const ALCchar *enumName)
  2957. START_API_FUNC
  2958. {
  2959. if(!enumName)
  2960. {
  2961. DeviceRef dev{VerifyDevice(device)};
  2962. alcSetError(dev.get(), ALC_INVALID_VALUE);
  2963. }
  2964. else
  2965. {
  2966. for(const auto &enm : alcEnumerations)
  2967. {
  2968. if(strcmp(enm.enumName, enumName) == 0)
  2969. return enm.value;
  2970. }
  2971. }
  2972. return 0;
  2973. }
  2974. END_API_FUNC
  2975. /* alcCreateContext
  2976. *
  2977. * Create and attach a context to the given device.
  2978. */
  2979. ALC_API ALCcontext* ALC_APIENTRY alcCreateContext(ALCdevice *device, const ALCint *attrList)
  2980. START_API_FUNC
  2981. {
  2982. /* Explicitly hold the list lock while taking the StateLock in case the
  2983. * device is asynchronously destroyed, to ensure this new context is
  2984. * properly cleaned up after being made.
  2985. */
  2986. std::unique_lock<std::recursive_mutex> listlock{ListLock};
  2987. DeviceRef dev{VerifyDevice(device)};
  2988. if(!dev || dev->Type == Capture || !dev->Connected.load(std::memory_order_relaxed))
  2989. {
  2990. listlock.unlock();
  2991. alcSetError(dev.get(), ALC_INVALID_DEVICE);
  2992. return nullptr;
  2993. }
  2994. std::unique_lock<std::mutex> statelock{dev->StateLock};
  2995. listlock.unlock();
  2996. dev->LastError.store(ALC_NO_ERROR);
  2997. ContextRef context{new ALCcontext{dev.get()}};
  2998. ALCdevice_IncRef(context->Device);
  2999. ALCenum err{UpdateDeviceParams(dev.get(), attrList)};
  3000. if(err != ALC_NO_ERROR)
  3001. {
  3002. alcSetError(dev.get(), err);
  3003. if(err == ALC_INVALID_DEVICE)
  3004. aluHandleDisconnect(dev.get(), "Device update failure");
  3005. statelock.unlock();
  3006. return nullptr;
  3007. }
  3008. AllocateVoices(context.get(), 256, dev->NumAuxSends);
  3009. if(DefaultEffect.type != AL_EFFECT_NULL && dev->Type == Playback)
  3010. {
  3011. void *ptr{al_calloc(16, sizeof(ALeffectslot))};
  3012. context->DefaultSlot = std::unique_ptr<ALeffectslot>{new (ptr) ALeffectslot{}};
  3013. if(InitEffectSlot(context->DefaultSlot.get()) == AL_NO_ERROR)
  3014. aluInitEffectPanning(context->DefaultSlot.get(), dev.get());
  3015. else
  3016. {
  3017. context->DefaultSlot = nullptr;
  3018. ERR("Failed to initialize the default effect slot\n");
  3019. }
  3020. }
  3021. InitContext(context.get());
  3022. ALfloat valf{};
  3023. if(ConfigValueFloat(dev->DeviceName.c_str(), nullptr, "volume-adjust", &valf))
  3024. {
  3025. if(!std::isfinite(valf))
  3026. ERR("volume-adjust must be finite: %f\n", valf);
  3027. else
  3028. {
  3029. ALfloat db = clampf(valf, -24.0f, 24.0f);
  3030. if(db != valf)
  3031. WARN("volume-adjust clamped: %f, range: +/-%f\n", valf, 24.0f);
  3032. context->GainBoost = std::pow(10.0f, db/20.0f);
  3033. TRACE("volume-adjust gain: %f\n", context->GainBoost);
  3034. }
  3035. }
  3036. UpdateListenerProps(context.get());
  3037. {
  3038. {
  3039. std::lock_guard<std::recursive_mutex> _{ListLock};
  3040. auto iter = std::lower_bound(ContextList.cbegin(), ContextList.cend(), context.get());
  3041. ContextList.insert(iter, context.get());
  3042. ALCcontext_IncRef(context.get());
  3043. }
  3044. ALCcontext *head = dev->ContextList.load();
  3045. do {
  3046. context->next.store(head, std::memory_order_relaxed);
  3047. } while(!dev->ContextList.compare_exchange_weak(head, context.get()));
  3048. }
  3049. statelock.unlock();
  3050. if(context->DefaultSlot)
  3051. {
  3052. if(InitializeEffect(context.get(), context->DefaultSlot.get(), &DefaultEffect) == AL_NO_ERROR)
  3053. UpdateEffectSlotProps(context->DefaultSlot.get(), context.get());
  3054. else
  3055. ERR("Failed to initialize the default effect\n");
  3056. }
  3057. TRACE("Created context %p\n", context.get());
  3058. return context.get();
  3059. }
  3060. END_API_FUNC
  3061. /* alcDestroyContext
  3062. *
  3063. * Remove a context from its device
  3064. */
  3065. ALC_API ALCvoid ALC_APIENTRY alcDestroyContext(ALCcontext *context)
  3066. START_API_FUNC
  3067. {
  3068. std::unique_lock<std::recursive_mutex> listlock{ListLock};
  3069. auto iter = std::lower_bound(ContextList.cbegin(), ContextList.cend(), context);
  3070. if(iter == ContextList.cend() || *iter != context)
  3071. {
  3072. listlock.unlock();
  3073. alcSetError(nullptr, ALC_INVALID_CONTEXT);
  3074. return;
  3075. }
  3076. /* Hold an extra reference to this context so it remains valid until the
  3077. * ListLock is released.
  3078. */
  3079. ALCcontext_IncRef(*iter);
  3080. ContextRef ctx{*iter};
  3081. ContextList.erase(iter);
  3082. if(ALCdevice *Device{ctx->Device})
  3083. {
  3084. std::lock_guard<std::mutex> _{Device->StateLock};
  3085. if(!ReleaseContext(ctx.get(), Device) && (Device->Flags&DEVICE_RUNNING))
  3086. {
  3087. Device->Backend->stop();
  3088. Device->Flags &= ~DEVICE_RUNNING;
  3089. }
  3090. }
  3091. listlock.unlock();
  3092. }
  3093. END_API_FUNC
  3094. /* alcGetCurrentContext
  3095. *
  3096. * Returns the currently active context on the calling thread
  3097. */
  3098. ALC_API ALCcontext* ALC_APIENTRY alcGetCurrentContext(void)
  3099. START_API_FUNC
  3100. {
  3101. ALCcontext *Context{LocalContext.get()};
  3102. if(!Context) Context = GlobalContext.load();
  3103. return Context;
  3104. }
  3105. END_API_FUNC
  3106. /* alcGetThreadContext
  3107. *
  3108. * Returns the currently active thread-local context
  3109. */
  3110. ALC_API ALCcontext* ALC_APIENTRY alcGetThreadContext(void)
  3111. START_API_FUNC
  3112. { return LocalContext.get(); }
  3113. END_API_FUNC
  3114. /* alcMakeContextCurrent
  3115. *
  3116. * Makes the given context the active process-wide context, and removes the
  3117. * thread-local context for the calling thread.
  3118. */
  3119. ALC_API ALCboolean ALC_APIENTRY alcMakeContextCurrent(ALCcontext *context)
  3120. START_API_FUNC
  3121. {
  3122. /* context must be valid or nullptr */
  3123. ContextRef ctx;
  3124. if(context)
  3125. {
  3126. ctx = VerifyContext(context);
  3127. if(!ctx)
  3128. {
  3129. alcSetError(nullptr, ALC_INVALID_CONTEXT);
  3130. return ALC_FALSE;
  3131. }
  3132. }
  3133. /* Release this reference (if any) to store it in the GlobalContext
  3134. * pointer. Take ownership of the reference (if any) that was previously
  3135. * stored there.
  3136. */
  3137. ctx = ContextRef{GlobalContext.exchange(ctx.release())};
  3138. /* Reset (decrement) the previous global reference by replacing it with the
  3139. * thread-local context. Take ownership of the thread-local context
  3140. * reference (if any), clearing the storage to null.
  3141. */
  3142. ctx = ContextRef{LocalContext.get()};
  3143. if(ctx) LocalContext.set(nullptr);
  3144. /* Reset (decrement) the previous thread-local reference. */
  3145. return ALC_TRUE;
  3146. }
  3147. END_API_FUNC
  3148. /* alcSetThreadContext
  3149. *
  3150. * Makes the given context the active context for the current thread
  3151. */
  3152. ALC_API ALCboolean ALC_APIENTRY alcSetThreadContext(ALCcontext *context)
  3153. START_API_FUNC
  3154. {
  3155. /* context must be valid or nullptr */
  3156. ContextRef ctx;
  3157. if(context)
  3158. {
  3159. ctx = VerifyContext(context);
  3160. if(!ctx)
  3161. {
  3162. alcSetError(nullptr, ALC_INVALID_CONTEXT);
  3163. return ALC_FALSE;
  3164. }
  3165. }
  3166. /* context's reference count is already incremented */
  3167. ContextRef old{LocalContext.get()};
  3168. LocalContext.set(ctx.release());
  3169. return ALC_TRUE;
  3170. }
  3171. END_API_FUNC
  3172. /* alcGetContextsDevice
  3173. *
  3174. * Returns the device that a particular context is attached to
  3175. */
  3176. ALC_API ALCdevice* ALC_APIENTRY alcGetContextsDevice(ALCcontext *Context)
  3177. START_API_FUNC
  3178. {
  3179. ContextRef ctx{VerifyContext(Context)};
  3180. if(!ctx)
  3181. {
  3182. alcSetError(nullptr, ALC_INVALID_CONTEXT);
  3183. return nullptr;
  3184. }
  3185. return ctx->Device;
  3186. }
  3187. END_API_FUNC
  3188. /* alcOpenDevice
  3189. *
  3190. * Opens the named device.
  3191. */
  3192. ALC_API ALCdevice* ALC_APIENTRY alcOpenDevice(const ALCchar *deviceName)
  3193. START_API_FUNC
  3194. {
  3195. DO_INITCONFIG();
  3196. if(!PlaybackBackend.name)
  3197. {
  3198. alcSetError(nullptr, ALC_INVALID_VALUE);
  3199. return nullptr;
  3200. }
  3201. if(deviceName && (!deviceName[0] || strcasecmp(deviceName, alcDefaultName) == 0 || strcasecmp(deviceName, "openal-soft") == 0
  3202. #ifdef _WIN32
  3203. /* Some old Windows apps hardcode these expecting OpenAL to use a
  3204. * specific audio API, even when they're not enumerated. Creative's
  3205. * router effectively ignores them too.
  3206. */
  3207. || strcasecmp(deviceName, "DirectSound3D") == 0 || strcasecmp(deviceName, "DirectSound") == 0
  3208. || strcasecmp(deviceName, "MMSYSTEM") == 0
  3209. #endif
  3210. ))
  3211. deviceName = nullptr;
  3212. DeviceRef device{new ALCdevice{Playback}};
  3213. /* Set output format */
  3214. device->FmtChans = DevFmtChannelsDefault;
  3215. device->FmtType = DevFmtTypeDefault;
  3216. device->Frequency = DEFAULT_OUTPUT_RATE;
  3217. device->UpdateSize = DEFAULT_UPDATE_SIZE;
  3218. device->BufferSize = DEFAULT_UPDATE_SIZE * DEFAULT_NUM_UPDATES;
  3219. device->LimiterState = ALC_TRUE;
  3220. device->SourcesMax = 256;
  3221. device->AuxiliaryEffectSlotMax = 64;
  3222. device->NumAuxSends = DEFAULT_SENDS;
  3223. try {
  3224. /* Create the device backend. */
  3225. device->Backend = PlaybackBackend.getFactory().createBackend(device.get(),
  3226. BackendType::Playback);
  3227. /* Find a playback device to open */
  3228. ALCenum err{device->Backend->open(deviceName)};
  3229. if(err != ALC_NO_ERROR)
  3230. {
  3231. alcSetError(nullptr, err);
  3232. return nullptr;
  3233. }
  3234. }
  3235. catch(al::backend_exception &e) {
  3236. WARN("Failed to open playback device: %s\n", e.what());
  3237. alcSetError(nullptr, e.errorCode());
  3238. return nullptr;
  3239. }
  3240. deviceName = device->DeviceName.c_str();
  3241. const ALCchar *fmt{};
  3242. if(ConfigValueStr(deviceName, nullptr, "channels", &fmt))
  3243. {
  3244. static constexpr struct ChannelMap {
  3245. const char name[16];
  3246. DevFmtChannels chans;
  3247. ALsizei order;
  3248. } chanlist[] = {
  3249. { "mono", DevFmtMono, 0 },
  3250. { "stereo", DevFmtStereo, 0 },
  3251. { "quad", DevFmtQuad, 0 },
  3252. { "surround51", DevFmtX51, 0 },
  3253. { "surround61", DevFmtX61, 0 },
  3254. { "surround71", DevFmtX71, 0 },
  3255. { "surround51rear", DevFmtX51Rear, 0 },
  3256. { "ambi1", DevFmtAmbi3D, 1 },
  3257. { "ambi2", DevFmtAmbi3D, 2 },
  3258. { "ambi3", DevFmtAmbi3D, 3 },
  3259. };
  3260. auto iter = std::find_if(std::begin(chanlist), std::end(chanlist),
  3261. [fmt](const ChannelMap &entry) -> bool
  3262. { return strcasecmp(entry.name, fmt) == 0; }
  3263. );
  3264. if(iter == std::end(chanlist))
  3265. ERR("Unsupported channels: %s\n", fmt);
  3266. else
  3267. {
  3268. device->FmtChans = iter->chans;
  3269. device->mAmbiOrder = iter->order;
  3270. device->Flags |= DEVICE_CHANNELS_REQUEST;
  3271. }
  3272. }
  3273. if(ConfigValueStr(deviceName, nullptr, "sample-type", &fmt))
  3274. {
  3275. static constexpr struct TypeMap {
  3276. const char name[16];
  3277. DevFmtType type;
  3278. } typelist[] = {
  3279. { "int8", DevFmtByte },
  3280. { "uint8", DevFmtUByte },
  3281. { "int16", DevFmtShort },
  3282. { "uint16", DevFmtUShort },
  3283. { "int32", DevFmtInt },
  3284. { "uint32", DevFmtUInt },
  3285. { "float32", DevFmtFloat },
  3286. };
  3287. auto iter = std::find_if(std::begin(typelist), std::end(typelist),
  3288. [fmt](const TypeMap &entry) -> bool
  3289. { return strcasecmp(entry.name, fmt) == 0; }
  3290. );
  3291. if(iter == std::end(typelist))
  3292. ERR("Unsupported sample-type: %s\n", fmt);
  3293. else
  3294. {
  3295. device->FmtType = iter->type;
  3296. device->Flags |= DEVICE_SAMPLE_TYPE_REQUEST;
  3297. }
  3298. }
  3299. ALuint freq{};
  3300. if(ConfigValueUInt(deviceName, nullptr, "frequency", &freq) && freq > 0)
  3301. {
  3302. if(freq < MIN_OUTPUT_RATE)
  3303. {
  3304. ERR("%uhz request clamped to %uhz minimum\n", freq, MIN_OUTPUT_RATE);
  3305. freq = MIN_OUTPUT_RATE;
  3306. }
  3307. device->UpdateSize = (device->UpdateSize*freq + device->Frequency/2) / device->Frequency;
  3308. device->BufferSize = (device->BufferSize*freq + device->Frequency/2) / device->Frequency;
  3309. device->Frequency = freq;
  3310. device->Flags |= DEVICE_FREQUENCY_REQUEST;
  3311. }
  3312. ConfigValueUInt(deviceName, nullptr, "period_size", &device->UpdateSize);
  3313. device->UpdateSize = clampu(device->UpdateSize, 64, 8192);
  3314. ALuint periods{};
  3315. if(ConfigValueUInt(deviceName, nullptr, "periods", &periods))
  3316. device->BufferSize = device->UpdateSize * clampu(periods, 2, 16);
  3317. else
  3318. device->BufferSize = maxu(device->BufferSize, device->UpdateSize*2);
  3319. ConfigValueUInt(deviceName, nullptr, "sources", &device->SourcesMax);
  3320. if(device->SourcesMax == 0) device->SourcesMax = 256;
  3321. ConfigValueUInt(deviceName, nullptr, "slots", &device->AuxiliaryEffectSlotMax);
  3322. if(device->AuxiliaryEffectSlotMax == 0) device->AuxiliaryEffectSlotMax = 64;
  3323. else device->AuxiliaryEffectSlotMax = minu(device->AuxiliaryEffectSlotMax, INT_MAX);
  3324. if(ConfigValueInt(deviceName, nullptr, "sends", &device->NumAuxSends))
  3325. device->NumAuxSends = clampi(
  3326. DEFAULT_SENDS, 0, clampi(device->NumAuxSends, 0, MAX_SENDS)
  3327. );
  3328. device->NumStereoSources = 1;
  3329. device->NumMonoSources = device->SourcesMax - device->NumStereoSources;
  3330. if(ConfigValueStr(deviceName, nullptr, "ambi-format", &fmt))
  3331. {
  3332. if(strcasecmp(fmt, "fuma") == 0)
  3333. {
  3334. if(device->mAmbiOrder > 3)
  3335. ERR("FuMa is incompatible with %d%s order ambisonics (up to third-order only)\n",
  3336. device->mAmbiOrder,
  3337. (((device->mAmbiOrder%100)/10) == 1) ? "th" :
  3338. ((device->mAmbiOrder%10) == 1) ? "st" :
  3339. ((device->mAmbiOrder%10) == 2) ? "nd" :
  3340. ((device->mAmbiOrder%10) == 3) ? "rd" : "th");
  3341. else
  3342. {
  3343. device->mAmbiLayout = AmbiLayout::FuMa;
  3344. device->mAmbiScale = AmbiNorm::FuMa;
  3345. }
  3346. }
  3347. else if(strcasecmp(fmt, "ambix") == 0 || strcasecmp(fmt, "acn+sn3d") == 0)
  3348. {
  3349. device->mAmbiLayout = AmbiLayout::ACN;
  3350. device->mAmbiScale = AmbiNorm::SN3D;
  3351. }
  3352. else if(strcasecmp(fmt, "acn+n3d") == 0)
  3353. {
  3354. device->mAmbiLayout = AmbiLayout::ACN;
  3355. device->mAmbiScale = AmbiNorm::N3D;
  3356. }
  3357. else
  3358. ERR("Unsupported ambi-format: %s\n", fmt);
  3359. }
  3360. {
  3361. std::lock_guard<std::recursive_mutex> _{ListLock};
  3362. auto iter = std::lower_bound(DeviceList.cbegin(), DeviceList.cend(), device.get());
  3363. DeviceList.insert(iter, device.get());
  3364. ALCdevice_IncRef(device.get());
  3365. }
  3366. TRACE("Created device %p, \"%s\"\n", device.get(), device->DeviceName.c_str());
  3367. return device.get();
  3368. }
  3369. END_API_FUNC
  3370. /* alcCloseDevice
  3371. *
  3372. * Closes the given device.
  3373. */
  3374. ALC_API ALCboolean ALC_APIENTRY alcCloseDevice(ALCdevice *device)
  3375. START_API_FUNC
  3376. {
  3377. std::unique_lock<std::recursive_mutex> listlock{ListLock};
  3378. auto iter = std::lower_bound(DeviceList.cbegin(), DeviceList.cend(), device);
  3379. if(iter == DeviceList.cend() || *iter != device)
  3380. {
  3381. alcSetError(nullptr, ALC_INVALID_DEVICE);
  3382. return ALC_FALSE;
  3383. }
  3384. if((*iter)->Type == Capture)
  3385. {
  3386. alcSetError(*iter, ALC_INVALID_DEVICE);
  3387. return ALC_FALSE;
  3388. }
  3389. std::unique_lock<std::mutex> statelock{device->StateLock};
  3390. /* Erase the device, and any remaining contexts left on it, from their
  3391. * respective lists.
  3392. */
  3393. DeviceList.erase(iter);
  3394. ALCcontext *ctx{device->ContextList.load()};
  3395. while(ctx != nullptr)
  3396. {
  3397. ALCcontext *next = ctx->next.load(std::memory_order_relaxed);
  3398. auto iter = std::lower_bound(ContextList.cbegin(), ContextList.cend(), ctx);
  3399. if(iter != ContextList.cend() && *iter == ctx)
  3400. ContextList.erase(iter);
  3401. ctx = next;
  3402. }
  3403. listlock.unlock();
  3404. ctx = device->ContextList.load(std::memory_order_relaxed);
  3405. while(ctx != nullptr)
  3406. {
  3407. ALCcontext *next = ctx->next.load(std::memory_order_relaxed);
  3408. WARN("Releasing context %p\n", ctx);
  3409. ReleaseContext(ctx, device);
  3410. ctx = next;
  3411. }
  3412. if((device->Flags&DEVICE_RUNNING))
  3413. device->Backend->stop();
  3414. device->Flags &= ~DEVICE_RUNNING;
  3415. statelock.unlock();
  3416. ALCdevice_DecRef(device);
  3417. return ALC_TRUE;
  3418. }
  3419. END_API_FUNC
  3420. /************************************************
  3421. * ALC capture functions
  3422. ************************************************/
  3423. ALC_API ALCdevice* ALC_APIENTRY alcCaptureOpenDevice(const ALCchar *deviceName, ALCuint frequency, ALCenum format, ALCsizei samples)
  3424. START_API_FUNC
  3425. {
  3426. DO_INITCONFIG();
  3427. if(!CaptureBackend.name)
  3428. {
  3429. alcSetError(nullptr, ALC_INVALID_VALUE);
  3430. return nullptr;
  3431. }
  3432. if(samples <= 0)
  3433. {
  3434. alcSetError(nullptr, ALC_INVALID_VALUE);
  3435. return nullptr;
  3436. }
  3437. if(deviceName && (!deviceName[0] || strcasecmp(deviceName, alcDefaultName) == 0 || strcasecmp(deviceName, "openal-soft") == 0))
  3438. deviceName = nullptr;
  3439. DeviceRef device{new ALCdevice{Capture}};
  3440. device->Frequency = frequency;
  3441. device->Flags |= DEVICE_FREQUENCY_REQUEST;
  3442. if(DecomposeDevFormat(format, &device->FmtChans, &device->FmtType) == AL_FALSE)
  3443. {
  3444. alcSetError(nullptr, ALC_INVALID_ENUM);
  3445. return nullptr;
  3446. }
  3447. device->Flags |= DEVICE_CHANNELS_REQUEST | DEVICE_SAMPLE_TYPE_REQUEST;
  3448. device->UpdateSize = samples;
  3449. device->BufferSize = samples;
  3450. try {
  3451. device->Backend = CaptureBackend.getFactory().createBackend(device.get(),
  3452. BackendType::Capture);
  3453. TRACE("Capture format: %s, %s, %uhz, %u / %u buffer\n",
  3454. DevFmtChannelsString(device->FmtChans), DevFmtTypeString(device->FmtType),
  3455. device->Frequency, device->UpdateSize, device->BufferSize);
  3456. ALCenum err{device->Backend->open(deviceName)};
  3457. if(err != ALC_NO_ERROR)
  3458. {
  3459. alcSetError(nullptr, err);
  3460. return nullptr;
  3461. }
  3462. }
  3463. catch(al::backend_exception &e) {
  3464. WARN("Failed to open capture device: %s\n", e.what());
  3465. alcSetError(nullptr, e.errorCode());
  3466. return nullptr;
  3467. }
  3468. {
  3469. std::lock_guard<std::recursive_mutex> _{ListLock};
  3470. auto iter = std::lower_bound(DeviceList.cbegin(), DeviceList.cend(), device.get());
  3471. DeviceList.insert(iter, device.get());
  3472. ALCdevice_IncRef(device.get());
  3473. }
  3474. TRACE("Created device %p, \"%s\"\n", device.get(), device->DeviceName.c_str());
  3475. return device.get();
  3476. }
  3477. END_API_FUNC
  3478. ALC_API ALCboolean ALC_APIENTRY alcCaptureCloseDevice(ALCdevice *device)
  3479. START_API_FUNC
  3480. {
  3481. std::unique_lock<std::recursive_mutex> listlock{ListLock};
  3482. auto iter = std::lower_bound(DeviceList.cbegin(), DeviceList.cend(), device);
  3483. if(iter == DeviceList.cend() || *iter != device)
  3484. {
  3485. alcSetError(nullptr, ALC_INVALID_DEVICE);
  3486. return ALC_FALSE;
  3487. }
  3488. if((*iter)->Type != Capture)
  3489. {
  3490. alcSetError(*iter, ALC_INVALID_DEVICE);
  3491. return ALC_FALSE;
  3492. }
  3493. DeviceList.erase(iter);
  3494. listlock.unlock();
  3495. { std::lock_guard<std::mutex> _{device->StateLock};
  3496. if((device->Flags&DEVICE_RUNNING))
  3497. device->Backend->stop();
  3498. device->Flags &= ~DEVICE_RUNNING;
  3499. }
  3500. ALCdevice_DecRef(device);
  3501. return ALC_TRUE;
  3502. }
  3503. END_API_FUNC
  3504. ALC_API void ALC_APIENTRY alcCaptureStart(ALCdevice *device)
  3505. START_API_FUNC
  3506. {
  3507. DeviceRef dev{VerifyDevice(device)};
  3508. if(!dev || dev->Type != Capture)
  3509. {
  3510. alcSetError(dev.get(), ALC_INVALID_DEVICE);
  3511. return;
  3512. }
  3513. std::lock_guard<std::mutex> _{dev->StateLock};
  3514. if(!dev->Connected.load(std::memory_order_acquire))
  3515. alcSetError(dev.get(), ALC_INVALID_DEVICE);
  3516. else if(!(dev->Flags&DEVICE_RUNNING))
  3517. {
  3518. if(dev->Backend->start())
  3519. dev->Flags |= DEVICE_RUNNING;
  3520. else
  3521. {
  3522. aluHandleDisconnect(dev.get(), "Device start failure");
  3523. alcSetError(dev.get(), ALC_INVALID_DEVICE);
  3524. }
  3525. }
  3526. }
  3527. END_API_FUNC
  3528. ALC_API void ALC_APIENTRY alcCaptureStop(ALCdevice *device)
  3529. START_API_FUNC
  3530. {
  3531. DeviceRef dev{VerifyDevice(device)};
  3532. if(!dev || dev->Type != Capture)
  3533. alcSetError(dev.get(), ALC_INVALID_DEVICE);
  3534. else
  3535. {
  3536. std::lock_guard<std::mutex> _{dev->StateLock};
  3537. if((dev->Flags&DEVICE_RUNNING))
  3538. dev->Backend->stop();
  3539. dev->Flags &= ~DEVICE_RUNNING;
  3540. }
  3541. }
  3542. END_API_FUNC
  3543. ALC_API void ALC_APIENTRY alcCaptureSamples(ALCdevice *device, ALCvoid *buffer, ALCsizei samples)
  3544. START_API_FUNC
  3545. {
  3546. DeviceRef dev{VerifyDevice(device)};
  3547. if(!dev || dev->Type != Capture)
  3548. {
  3549. alcSetError(dev.get(), ALC_INVALID_DEVICE);
  3550. return;
  3551. }
  3552. ALCenum err{ALC_INVALID_VALUE};
  3553. { std::lock_guard<std::mutex> _{dev->StateLock};
  3554. BackendBase *backend{dev->Backend.get()};
  3555. if(samples >= 0 && backend->availableSamples() >= static_cast<ALCuint>(samples))
  3556. err = backend->captureSamples(buffer, samples);
  3557. }
  3558. if(err != ALC_NO_ERROR)
  3559. alcSetError(dev.get(), err);
  3560. }
  3561. END_API_FUNC
  3562. /************************************************
  3563. * ALC loopback functions
  3564. ************************************************/
  3565. /* alcLoopbackOpenDeviceSOFT
  3566. *
  3567. * Open a loopback device, for manual rendering.
  3568. */
  3569. ALC_API ALCdevice* ALC_APIENTRY alcLoopbackOpenDeviceSOFT(const ALCchar *deviceName)
  3570. START_API_FUNC
  3571. {
  3572. DO_INITCONFIG();
  3573. /* Make sure the device name, if specified, is us. */
  3574. if(deviceName && strcmp(deviceName, alcDefaultName) != 0)
  3575. {
  3576. alcSetError(nullptr, ALC_INVALID_VALUE);
  3577. return nullptr;
  3578. }
  3579. DeviceRef device{new ALCdevice{Loopback}};
  3580. device->SourcesMax = 256;
  3581. device->AuxiliaryEffectSlotMax = 64;
  3582. device->NumAuxSends = DEFAULT_SENDS;
  3583. //Set output format
  3584. device->BufferSize = 0;
  3585. device->UpdateSize = 0;
  3586. device->Frequency = DEFAULT_OUTPUT_RATE;
  3587. device->FmtChans = DevFmtChannelsDefault;
  3588. device->FmtType = DevFmtTypeDefault;
  3589. ConfigValueUInt(nullptr, nullptr, "sources", &device->SourcesMax);
  3590. if(device->SourcesMax == 0) device->SourcesMax = 256;
  3591. ConfigValueUInt(nullptr, nullptr, "slots", &device->AuxiliaryEffectSlotMax);
  3592. if(device->AuxiliaryEffectSlotMax == 0) device->AuxiliaryEffectSlotMax = 64;
  3593. else device->AuxiliaryEffectSlotMax = minu(device->AuxiliaryEffectSlotMax, INT_MAX);
  3594. if(ConfigValueInt(nullptr, nullptr, "sends", &device->NumAuxSends))
  3595. device->NumAuxSends = clampi(
  3596. DEFAULT_SENDS, 0, clampi(device->NumAuxSends, 0, MAX_SENDS)
  3597. );
  3598. device->NumStereoSources = 1;
  3599. device->NumMonoSources = device->SourcesMax - device->NumStereoSources;
  3600. try {
  3601. device->Backend = LoopbackBackendFactory::getFactory().createBackend(device.get(),
  3602. BackendType::Playback);
  3603. // Open the "backend"
  3604. device->Backend->open("Loopback");
  3605. }
  3606. catch(al::backend_exception &e) {
  3607. WARN("Failed to open loopback device: %s\n", e.what());
  3608. alcSetError(nullptr, e.errorCode());
  3609. return nullptr;
  3610. }
  3611. {
  3612. std::lock_guard<std::recursive_mutex> _{ListLock};
  3613. auto iter = std::lower_bound(DeviceList.cbegin(), DeviceList.cend(), device.get());
  3614. DeviceList.insert(iter, device.get());
  3615. ALCdevice_IncRef(device.get());
  3616. }
  3617. TRACE("Created device %p\n", device.get());
  3618. return device.get();
  3619. }
  3620. END_API_FUNC
  3621. /* alcIsRenderFormatSupportedSOFT
  3622. *
  3623. * Determines if the loopback device supports the given format for rendering.
  3624. */
  3625. ALC_API ALCboolean ALC_APIENTRY alcIsRenderFormatSupportedSOFT(ALCdevice *device, ALCsizei freq, ALCenum channels, ALCenum type)
  3626. START_API_FUNC
  3627. {
  3628. DeviceRef dev{VerifyDevice(device)};
  3629. if(!dev || dev->Type != Loopback)
  3630. alcSetError(dev.get(), ALC_INVALID_DEVICE);
  3631. else if(freq <= 0)
  3632. alcSetError(dev.get(), ALC_INVALID_VALUE);
  3633. else
  3634. {
  3635. if(IsValidALCType(type) && IsValidALCChannels(channels) && freq >= MIN_OUTPUT_RATE)
  3636. return ALC_TRUE;
  3637. }
  3638. return ALC_FALSE;
  3639. }
  3640. END_API_FUNC
  3641. /* alcRenderSamplesSOFT
  3642. *
  3643. * Renders some samples into a buffer, using the format last set by the
  3644. * attributes given to alcCreateContext.
  3645. */
  3646. FORCE_ALIGN ALC_API void ALC_APIENTRY alcRenderSamplesSOFT(ALCdevice *device, ALCvoid *buffer, ALCsizei samples)
  3647. START_API_FUNC
  3648. {
  3649. DeviceRef dev{VerifyDevice(device)};
  3650. if(!dev || dev->Type != Loopback)
  3651. alcSetError(dev.get(), ALC_INVALID_DEVICE);
  3652. else if(samples < 0 || (samples > 0 && buffer == nullptr))
  3653. alcSetError(dev.get(), ALC_INVALID_VALUE);
  3654. else
  3655. {
  3656. BackendLockGuard _{*device->Backend};
  3657. aluMixData(dev.get(), buffer, samples);
  3658. }
  3659. }
  3660. END_API_FUNC
  3661. /************************************************
  3662. * ALC DSP pause/resume functions
  3663. ************************************************/
  3664. /* alcDevicePauseSOFT
  3665. *
  3666. * Pause the DSP to stop audio processing.
  3667. */
  3668. ALC_API void ALC_APIENTRY alcDevicePauseSOFT(ALCdevice *device)
  3669. START_API_FUNC
  3670. {
  3671. DeviceRef dev{VerifyDevice(device)};
  3672. if(!dev || dev->Type != Playback)
  3673. alcSetError(dev.get(), ALC_INVALID_DEVICE);
  3674. else
  3675. {
  3676. std::lock_guard<std::mutex> _{dev->StateLock};
  3677. if((dev->Flags&DEVICE_RUNNING))
  3678. dev->Backend->stop();
  3679. dev->Flags &= ~DEVICE_RUNNING;
  3680. dev->Flags |= DEVICE_PAUSED;
  3681. }
  3682. }
  3683. END_API_FUNC
  3684. /* alcDeviceResumeSOFT
  3685. *
  3686. * Resume the DSP to restart audio processing.
  3687. */
  3688. ALC_API void ALC_APIENTRY alcDeviceResumeSOFT(ALCdevice *device)
  3689. START_API_FUNC
  3690. {
  3691. DeviceRef dev{VerifyDevice(device)};
  3692. if(!dev || dev->Type != Playback)
  3693. {
  3694. alcSetError(dev.get(), ALC_INVALID_DEVICE);
  3695. return;
  3696. }
  3697. std::lock_guard<std::mutex> _{dev->StateLock};
  3698. if(!(dev->Flags&DEVICE_PAUSED))
  3699. return;
  3700. dev->Flags &= ~DEVICE_PAUSED;
  3701. if(dev->ContextList.load() == nullptr)
  3702. return;
  3703. if(dev->Backend->start() == ALC_FALSE)
  3704. {
  3705. aluHandleDisconnect(dev.get(), "Device start failure");
  3706. alcSetError(dev.get(), ALC_INVALID_DEVICE);
  3707. return;
  3708. }
  3709. dev->Flags |= DEVICE_RUNNING;
  3710. }
  3711. END_API_FUNC
  3712. /************************************************
  3713. * ALC HRTF functions
  3714. ************************************************/
  3715. /* alcGetStringiSOFT
  3716. *
  3717. * Gets a string parameter at the given index.
  3718. */
  3719. ALC_API const ALCchar* ALC_APIENTRY alcGetStringiSOFT(ALCdevice *device, ALCenum paramName, ALCsizei index)
  3720. START_API_FUNC
  3721. {
  3722. DeviceRef dev{VerifyDevice(device)};
  3723. if(!dev || dev->Type == Capture)
  3724. alcSetError(dev.get(), ALC_INVALID_DEVICE);
  3725. else switch(paramName)
  3726. {
  3727. case ALC_HRTF_SPECIFIER_SOFT:
  3728. if(index >= 0 && static_cast<size_t>(index) < dev->HrtfList.size())
  3729. return dev->HrtfList[index].name.c_str();
  3730. alcSetError(dev.get(), ALC_INVALID_VALUE);
  3731. break;
  3732. default:
  3733. alcSetError(dev.get(), ALC_INVALID_ENUM);
  3734. break;
  3735. }
  3736. return nullptr;
  3737. }
  3738. END_API_FUNC
  3739. /* alcResetDeviceSOFT
  3740. *
  3741. * Resets the given device output, using the specified attribute list.
  3742. */
  3743. ALC_API ALCboolean ALC_APIENTRY alcResetDeviceSOFT(ALCdevice *device, const ALCint *attribs)
  3744. START_API_FUNC
  3745. {
  3746. std::unique_lock<std::recursive_mutex> listlock{ListLock};
  3747. DeviceRef dev{VerifyDevice(device)};
  3748. if(!dev || dev->Type == Capture)
  3749. {
  3750. listlock.unlock();
  3751. alcSetError(dev.get(), ALC_INVALID_DEVICE);
  3752. return ALC_FALSE;
  3753. }
  3754. std::lock_guard<std::mutex> _{dev->StateLock};
  3755. listlock.unlock();
  3756. /* Force the backend to stop mixing first since we're resetting. Also reset
  3757. * the connected state so lost devices can attempt recover.
  3758. */
  3759. if((dev->Flags&DEVICE_RUNNING))
  3760. dev->Backend->stop();
  3761. dev->Flags &= ~DEVICE_RUNNING;
  3762. device->Connected.store(true);
  3763. ALCenum err{UpdateDeviceParams(dev.get(), attribs)};
  3764. if(LIKELY(err == ALC_NO_ERROR)) return ALC_TRUE;
  3765. alcSetError(dev.get(), err);
  3766. if(err == ALC_INVALID_DEVICE)
  3767. aluHandleDisconnect(dev.get(), "Device start failure");
  3768. return ALC_FALSE;
  3769. }
  3770. END_API_FUNC