aldirect.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  1. /*
  2. * OpenAL Direct Context Example
  3. *
  4. * Copyright (c) 2024 by Chris Robinson <[email protected]>
  5. *
  6. * Permission is hereby granted, free of charge, to any person obtaining a copy
  7. * of this software and associated documentation files (the "Software"), to deal
  8. * in the Software without restriction, including without limitation the rights
  9. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. * copies of the Software, and to permit persons to whom the Software is
  11. * furnished to do so, subject to the following conditions:
  12. *
  13. * The above copyright notice and this permission notice shall be included in
  14. * all copies or substantial portions of the Software.
  15. *
  16. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. * THE SOFTWARE.
  23. */
  24. /* This file contains an example for playing a sound buffer with the Direct API
  25. * extension.
  26. */
  27. #include <algorithm>
  28. #include <cassert>
  29. #include <cstddef>
  30. #include <cstdio>
  31. #include <iostream>
  32. #include <limits>
  33. #include <memory>
  34. #include <string>
  35. #include <string_view>
  36. #include <vector>
  37. #include "sndfile.h"
  38. #include "AL/al.h"
  39. #include "AL/alc.h"
  40. #include "AL/alext.h"
  41. #include "alspan.h"
  42. #include "common/alhelpers.h"
  43. #include "win_main_utf8.h"
  44. namespace {
  45. /* On Windows when using Creative's router, we need to override the ALC
  46. * functions and access the driver functions directly. This isn't needed when
  47. * not using the router, or on other OSs.
  48. */
  49. LPALCOPENDEVICE p_alcOpenDevice{alcOpenDevice};
  50. LPALCCLOSEDEVICE p_alcCloseDevice{alcCloseDevice};
  51. LPALCISEXTENSIONPRESENT p_alcIsExtensionPresent{alcIsExtensionPresent};
  52. LPALCCREATECONTEXT p_alcCreateContext{alcCreateContext};
  53. LPALCDESTROYCONTEXT p_alcDestroyContext{alcDestroyContext};
  54. LPALCGETPROCADDRESS p_alcGetProcAddress{alcGetProcAddress};
  55. LPALGETSTRINGDIRECT alGetStringDirect{};
  56. LPALGETERRORDIRECT alGetErrorDirect{};
  57. LPALISEXTENSIONPRESENTDIRECT alIsExtensionPresentDirect{};
  58. LPALGENBUFFERSDIRECT alGenBuffersDirect{};
  59. LPALDELETEBUFFERSDIRECT alDeleteBuffersDirect{};
  60. LPALISBUFFERDIRECT alIsBufferDirect{};
  61. LPALBUFFERIDIRECT alBufferiDirect{};
  62. LPALBUFFERDATADIRECT alBufferDataDirect{};
  63. LPALGENSOURCESDIRECT alGenSourcesDirect{};
  64. LPALDELETESOURCESDIRECT alDeleteSourcesDirect{};
  65. LPALSOURCEIDIRECT alSourceiDirect{};
  66. LPALGETSOURCEIDIRECT alGetSourceiDirect{};
  67. LPALGETSOURCEFDIRECT alGetSourcefDirect{};
  68. LPALSOURCEPLAYDIRECT alSourcePlayDirect{};
  69. struct SndFileDeleter {
  70. void operator()(SNDFILE *sndfile) { sf_close(sndfile); }
  71. };
  72. using SndFilePtr = std::unique_ptr<SNDFILE,SndFileDeleter>;
  73. enum class FormatType {
  74. Int16,
  75. Float,
  76. IMA4,
  77. MSADPCM
  78. };
  79. /* LoadBuffer loads the named audio file into an OpenAL buffer object, and
  80. * returns the new buffer ID.
  81. */
  82. ALuint LoadSound(ALCcontext *context, const std::string_view filename)
  83. {
  84. /* Open the audio file and check that it's usable. */
  85. SF_INFO sfinfo{};
  86. SndFilePtr sndfile{sf_open(std::string{filename}.c_str(), SFM_READ, &sfinfo)};
  87. if(!sndfile)
  88. {
  89. std::cerr<< "Could not open audio in "<<filename<<": "<<sf_strerror(sndfile.get())<<"\n";
  90. return 0;
  91. }
  92. if(sfinfo.frames < 1)
  93. {
  94. std::cerr<< "Bad sample count in "<<filename<<" ("<<sfinfo.frames<<")\n";
  95. return 0;
  96. }
  97. /* Detect a suitable format to load. Formats like Vorbis and Opus use float
  98. * natively, so load as float to avoid clipping when possible. Formats
  99. * larger than 16-bit can also use float to preserve a bit more precision.
  100. */
  101. FormatType sample_format{FormatType::Int16};
  102. switch((sfinfo.format&SF_FORMAT_SUBMASK))
  103. {
  104. case SF_FORMAT_PCM_24:
  105. case SF_FORMAT_PCM_32:
  106. case SF_FORMAT_FLOAT:
  107. case SF_FORMAT_DOUBLE:
  108. case SF_FORMAT_VORBIS:
  109. case SF_FORMAT_OPUS:
  110. case SF_FORMAT_ALAC_20:
  111. case SF_FORMAT_ALAC_24:
  112. case SF_FORMAT_ALAC_32:
  113. case 0x0080/*SF_FORMAT_MPEG_LAYER_I*/:
  114. case 0x0081/*SF_FORMAT_MPEG_LAYER_II*/:
  115. case 0x0082/*SF_FORMAT_MPEG_LAYER_III*/:
  116. if(alIsExtensionPresentDirect(context, "AL_EXT_FLOAT32"))
  117. sample_format = FormatType::Float;
  118. break;
  119. case SF_FORMAT_IMA_ADPCM:
  120. /* ADPCM formats require setting a block alignment as specified in the
  121. * file, which needs to be read from the wave 'fmt ' chunk manually
  122. * since libsndfile doesn't provide it in a format-agnostic way.
  123. */
  124. if(sfinfo.channels <= 2 && (sfinfo.format&SF_FORMAT_TYPEMASK) == SF_FORMAT_WAV
  125. && alIsExtensionPresentDirect(context, "AL_EXT_IMA4")
  126. && alIsExtensionPresentDirect(context, "AL_SOFT_block_alignment"))
  127. sample_format = FormatType::IMA4;
  128. break;
  129. case SF_FORMAT_MS_ADPCM:
  130. if(sfinfo.channels <= 2 && (sfinfo.format&SF_FORMAT_TYPEMASK) == SF_FORMAT_WAV
  131. && alIsExtensionPresentDirect(context, "AL_SOFT_MSADPCM")
  132. && alIsExtensionPresentDirect(context, "AL_SOFT_block_alignment"))
  133. sample_format = FormatType::MSADPCM;
  134. break;
  135. }
  136. ALint byteblockalign{0}, splblockalign{0};
  137. if(sample_format == FormatType::IMA4 || sample_format == FormatType::MSADPCM)
  138. {
  139. /* For ADPCM, lookup the wave file's "fmt " chunk, which is a
  140. * WAVEFORMATEX-based structure for the audio format.
  141. */
  142. SF_CHUNK_INFO inf{"fmt ", 4, 0, nullptr};
  143. SF_CHUNK_ITERATOR *iter{sf_get_chunk_iterator(sndfile.get(), &inf)};
  144. /* If there's an issue getting the chunk or block alignment, load as
  145. * 16-bit and have libsndfile do the conversion.
  146. */
  147. if(!iter || sf_get_chunk_size(iter, &inf) != SF_ERR_NO_ERROR || inf.datalen < 14)
  148. sample_format = FormatType::Int16;
  149. else
  150. {
  151. auto fmtbuf = std::vector<ALubyte>(inf.datalen, ALubyte{0});
  152. inf.data = fmtbuf.data();
  153. if(sf_get_chunk_data(iter, &inf) != SF_ERR_NO_ERROR)
  154. sample_format = FormatType::Int16;
  155. else
  156. {
  157. /* Read the nBlockAlign field, and convert from bytes- to
  158. * samples-per-block (verifying it's valid by converting back
  159. * and comparing to the original value).
  160. */
  161. byteblockalign = fmtbuf[12] | (fmtbuf[13]<<8);
  162. if(sample_format == FormatType::IMA4)
  163. {
  164. splblockalign = (byteblockalign/sfinfo.channels - 4)/4*8 + 1;
  165. if(splblockalign < 1
  166. || ((splblockalign-1)/2 + 4)*sfinfo.channels != byteblockalign)
  167. sample_format = FormatType::Int16;
  168. }
  169. else if(sample_format == FormatType::MSADPCM)
  170. {
  171. splblockalign = (byteblockalign/sfinfo.channels - 7)*2 + 2;
  172. if(splblockalign < 2
  173. || ((splblockalign-2)/2 + 7)*sfinfo.channels != byteblockalign)
  174. sample_format = FormatType::Int16;
  175. }
  176. else
  177. sample_format = FormatType::Int16;
  178. }
  179. }
  180. }
  181. if(sample_format == FormatType::Int16)
  182. {
  183. splblockalign = 1;
  184. byteblockalign = sfinfo.channels * 2;
  185. }
  186. else if(sample_format == FormatType::Float)
  187. {
  188. splblockalign = 1;
  189. byteblockalign = sfinfo.channels * 4;
  190. }
  191. /* Figure out the OpenAL format from the file and desired sample type. */
  192. ALenum format{AL_NONE};
  193. if(sfinfo.channels == 1)
  194. {
  195. if(sample_format == FormatType::Int16)
  196. format = AL_FORMAT_MONO16;
  197. else if(sample_format == FormatType::Float)
  198. format = AL_FORMAT_MONO_FLOAT32;
  199. else if(sample_format == FormatType::IMA4)
  200. format = AL_FORMAT_MONO_IMA4;
  201. else if(sample_format == FormatType::MSADPCM)
  202. format = AL_FORMAT_MONO_MSADPCM_SOFT;
  203. }
  204. else if(sfinfo.channels == 2)
  205. {
  206. if(sample_format == FormatType::Int16)
  207. format = AL_FORMAT_STEREO16;
  208. else if(sample_format == FormatType::Float)
  209. format = AL_FORMAT_STEREO_FLOAT32;
  210. else if(sample_format == FormatType::IMA4)
  211. format = AL_FORMAT_STEREO_IMA4;
  212. else if(sample_format == FormatType::MSADPCM)
  213. format = AL_FORMAT_STEREO_MSADPCM_SOFT;
  214. }
  215. else if(sfinfo.channels == 3)
  216. {
  217. if(sf_command(sndfile.get(), SFC_WAVEX_GET_AMBISONIC, nullptr, 0) == SF_AMBISONIC_B_FORMAT)
  218. {
  219. if(sample_format == FormatType::Int16)
  220. format = AL_FORMAT_BFORMAT2D_16;
  221. else if(sample_format == FormatType::Float)
  222. format = AL_FORMAT_BFORMAT2D_FLOAT32;
  223. }
  224. }
  225. else if(sfinfo.channels == 4)
  226. {
  227. if(sf_command(sndfile.get(), SFC_WAVEX_GET_AMBISONIC, nullptr, 0) == SF_AMBISONIC_B_FORMAT)
  228. {
  229. if(sample_format == FormatType::Int16)
  230. format = AL_FORMAT_BFORMAT3D_16;
  231. else if(sample_format == FormatType::Float)
  232. format = AL_FORMAT_BFORMAT3D_FLOAT32;
  233. }
  234. }
  235. if(!format)
  236. {
  237. std::cerr<< "Unsupported channel count: "<<sfinfo.channels<<"\n";
  238. return 0;
  239. }
  240. if(sfinfo.frames/splblockalign > sf_count_t{std::numeric_limits<int>::max()}/byteblockalign)
  241. {
  242. std::cerr<< "Too many sample frames in "<<filename<<" ("<<sfinfo.frames<<")\n";
  243. return 0;
  244. }
  245. /* Decode the whole audio file to a buffer. */
  246. auto membuf = std::vector<std::byte>(static_cast<size_t>(sfinfo.frames / splblockalign
  247. * byteblockalign));
  248. sf_count_t num_frames{};
  249. if(sample_format == FormatType::Int16)
  250. num_frames = sf_readf_short(sndfile.get(), reinterpret_cast<short*>(membuf.data()),
  251. sfinfo.frames);
  252. else if(sample_format == FormatType::Float)
  253. num_frames = sf_readf_float(sndfile.get(), reinterpret_cast<float*>(membuf.data()),
  254. sfinfo.frames);
  255. else
  256. {
  257. const sf_count_t count{sfinfo.frames / splblockalign * byteblockalign};
  258. num_frames = sf_read_raw(sndfile.get(), membuf.data(), count);
  259. if(num_frames > 0)
  260. num_frames = num_frames / byteblockalign * splblockalign;
  261. }
  262. if(num_frames < 1)
  263. {
  264. std::cerr<< "Failed to read samples in "<<filename<<" ("<<num_frames<<")\n";
  265. return 0;
  266. }
  267. const auto num_bytes = static_cast<ALsizei>(num_frames / splblockalign * byteblockalign);
  268. std::cout<< "Loading: "<<filename<<" ("<<FormatName(format)<<", "<<sfinfo.samplerate<<"hz)\n"
  269. <<std::flush;
  270. ALuint buffer{};
  271. alGenBuffersDirect(context, 1, &buffer);
  272. if(splblockalign > 1)
  273. alBufferiDirect(context, buffer, AL_UNPACK_BLOCK_ALIGNMENT_SOFT, splblockalign);
  274. alBufferDataDirect(context, buffer, format, membuf.data(), num_bytes, sfinfo.samplerate);
  275. /* Check if an error occurred, and clean up if so. */
  276. if(ALenum err{alGetErrorDirect(context)}; err != AL_NO_ERROR)
  277. {
  278. std::cerr<< "OpenAL Error: "<<alGetStringDirect(context, err)<<"\n";
  279. if(buffer && alIsBufferDirect(context, buffer))
  280. alDeleteBuffersDirect(context, 1, &buffer);
  281. return 0;
  282. }
  283. return buffer;
  284. }
  285. int main(al::span<std::string_view> args)
  286. {
  287. /* Print out usage if no arguments were specified */
  288. if(args.size() < 2)
  289. {
  290. std::cerr<< "Usage: "<<args[0]<<" [-device <name>] <filename>\n";
  291. return 1;
  292. }
  293. /* Initialize OpenAL. */
  294. args = args.subspan(1);
  295. ALCdevice *device{};
  296. if(args.size() > 1 && args[0] == "-device")
  297. {
  298. device = p_alcOpenDevice(std::string{args[1]}.c_str());
  299. if(!device)
  300. std::cerr<< "Failed to open \""<<args[1]<<"\", trying default\n";
  301. args = args.subspan(2);
  302. }
  303. if(!device)
  304. device = p_alcOpenDevice(nullptr);
  305. if(!device)
  306. {
  307. std::cerr<< "Could not open a device!\n";
  308. return 1;
  309. }
  310. if(!p_alcIsExtensionPresent(device, "ALC_EXT_direct_context"))
  311. {
  312. std::cerr<< "ALC_EXT_direct_context not supported on device\n";
  313. p_alcCloseDevice(device);
  314. return 1;
  315. }
  316. /* On Windows with Creative's router, the device needs to be bootstrapped
  317. * to use it through the driver directly. Otherwise the Direct functions
  318. * aren't able to recognize the router's ALCcontexts. To handle this, we
  319. * use the router's alcOpenDevice, alcGetProcAddress, and alcCloseDevice
  320. * functions to open the device with the router, get the device driver's
  321. * alcGetProcAddress2 function, and close the device with the router. Then
  322. * call alcGetProcAddress2 with the null device handle to get the driver's
  323. * functions. Afterward, we can open the device back up using the driver
  324. * functions directly and continue on.
  325. *
  326. * Note that this will allow using other devices from the same driver just
  327. * fine, but switching to a device on another driver will require using the
  328. * original functions from the router (and require re-bootstrapping to use
  329. * that driver's functions, if applicable). If controlling multiple devices
  330. * with Direct functions from separate drivers simultaneously is desired, a
  331. * good strategy may be to associate the driver's ALC and Direct functions
  332. * with the ALCdevice and ALCcontext handles created from them.
  333. *
  334. * This is all unnecessary when not using Creative's router, including on
  335. * non-Windows OSs or when using OpenAL Soft's router, where the original
  336. * ALC functions can be used as normal.
  337. */
  338. {
  339. const std::string devname{alcGetString(device, ALC_ALL_DEVICES_SPECIFIER)};
  340. auto p_alcGetProcAddress2 = reinterpret_cast<LPALCGETPROCADDRESS2>(
  341. p_alcGetProcAddress(device, "alcGetProcAddress2"));
  342. p_alcCloseDevice(device);
  343. /* Load the driver-specific ALC functions we'll be using. */
  344. #define LOAD_PROC(N) p_##N = reinterpret_cast<decltype(p_##N)>(p_alcGetProcAddress2(nullptr, #N))
  345. LOAD_PROC(alcOpenDevice);
  346. LOAD_PROC(alcCloseDevice);
  347. LOAD_PROC(alcIsExtensionPresent);
  348. LOAD_PROC(alcGetProcAddress);
  349. LOAD_PROC(alcCreateContext);
  350. LOAD_PROC(alcDestroyContext);
  351. LOAD_PROC(alcGetProcAddress);
  352. #undef LOAD_PROC
  353. device = p_alcOpenDevice(devname.c_str());
  354. assert(device != nullptr);
  355. }
  356. /* Load the Direct API functions we're using. */
  357. #define LOAD_PROC(N) N = reinterpret_cast<decltype(N)>(p_alcGetProcAddress(device, #N))
  358. LOAD_PROC(alGetStringDirect);
  359. LOAD_PROC(alGetErrorDirect);
  360. LOAD_PROC(alIsExtensionPresentDirect);
  361. LOAD_PROC(alGenBuffersDirect);
  362. LOAD_PROC(alDeleteBuffersDirect);
  363. LOAD_PROC(alIsBufferDirect);
  364. LOAD_PROC(alBufferiDirect);
  365. LOAD_PROC(alBufferDataDirect);
  366. LOAD_PROC(alGenSourcesDirect);
  367. LOAD_PROC(alDeleteSourcesDirect);
  368. LOAD_PROC(alSourceiDirect);
  369. LOAD_PROC(alGetSourceiDirect);
  370. LOAD_PROC(alGetSourcefDirect);
  371. LOAD_PROC(alSourcePlayDirect);
  372. #undef LOAD_PROC
  373. /* Create the context. It doesn't need to be set as current to use with the
  374. * Direct API functions.
  375. */
  376. ALCcontext *context{p_alcCreateContext(device, nullptr)};
  377. if(!context)
  378. {
  379. p_alcCloseDevice(device);
  380. std::cerr<< "Could not create a context!\n";
  381. return 1;
  382. }
  383. /* Load the sound into a buffer. */
  384. const ALuint buffer{LoadSound(context, args[0])};
  385. if(!buffer)
  386. {
  387. p_alcDestroyContext(context);
  388. p_alcCloseDevice(device);
  389. return 1;
  390. }
  391. /* Create the source to play the sound with. */
  392. ALuint source{0};
  393. alGenSourcesDirect(context, 1, &source);
  394. alSourceiDirect(context, source, AL_BUFFER, static_cast<ALint>(buffer));
  395. assert(alGetErrorDirect(context)==AL_NO_ERROR && "Failed to setup sound source");
  396. /* Play the sound until it finishes. */
  397. alSourcePlayDirect(context, source);
  398. ALenum state{};
  399. do {
  400. al_nssleep(10000000);
  401. alGetSourceiDirect(context, source, AL_SOURCE_STATE, &state);
  402. /* Get the source offset. */
  403. ALfloat offset{};
  404. alGetSourcefDirect(context, source, AL_SEC_OFFSET, &offset);
  405. printf("\rOffset: %f ", offset);
  406. fflush(stdout);
  407. } while(alGetErrorDirect(context) == AL_NO_ERROR && state == AL_PLAYING);
  408. printf("\n");
  409. /* All done. Delete resources, and close down OpenAL. */
  410. alDeleteSourcesDirect(context, 1, &source);
  411. alDeleteBuffersDirect(context, 1, &buffer);
  412. p_alcDestroyContext(context);
  413. p_alcCloseDevice(device);
  414. return 0;
  415. }
  416. } // namespace
  417. int main(int argc, char **argv)
  418. {
  419. assert(argc >= 0);
  420. auto args = std::vector<std::string_view>(static_cast<unsigned int>(argc));
  421. std::copy_n(argv, args.size(), args.begin());
  422. return main(al::span{args});
  423. }