Make a couple lambdas static
[openal-soft.git] / examples / aldirect.cpp
blobd7964addaeb7f5c3816f10ac859e8382d7491070
1 /*
2 * OpenAL Direct Context Example
4 * Copyright (c) 2024 by Chris Robinson <chris.kcat@gmail.com>
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:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
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.
25 /* This file contains an example for playing a sound buffer with the Direct API
26 * extension.
29 #include <algorithm>
30 #include <cassert>
31 #include <cstddef>
32 #include <cstdio>
33 #include <iostream>
34 #include <limits>
35 #include <memory>
36 #include <string>
37 #include <string_view>
38 #include <vector>
40 #include "sndfile.h"
42 #include "AL/al.h"
43 #include "AL/alc.h"
44 #include "AL/alext.h"
46 #include "alspan.h"
47 #include "common/alhelpers.h"
49 #include "win_main_utf8.h"
51 namespace {
53 /* On Windows when using Creative's router, we need to override the ALC
54 * functions and access the driver functions directly. This isn't needed when
55 * not using the router, or on other OSs.
57 LPALCOPENDEVICE p_alcOpenDevice{alcOpenDevice};
58 LPALCCLOSEDEVICE p_alcCloseDevice{alcCloseDevice};
59 LPALCISEXTENSIONPRESENT p_alcIsExtensionPresent{alcIsExtensionPresent};
60 LPALCCREATECONTEXT p_alcCreateContext{alcCreateContext};
61 LPALCDESTROYCONTEXT p_alcDestroyContext{alcDestroyContext};
62 LPALCGETPROCADDRESS p_alcGetProcAddress{alcGetProcAddress};
65 LPALGETSTRINGDIRECT alGetStringDirect{};
66 LPALGETERRORDIRECT alGetErrorDirect{};
67 LPALISEXTENSIONPRESENTDIRECT alIsExtensionPresentDirect{};
69 LPALGENBUFFERSDIRECT alGenBuffersDirect{};
70 LPALDELETEBUFFERSDIRECT alDeleteBuffersDirect{};
71 LPALISBUFFERDIRECT alIsBufferDirect{};
72 LPALBUFFERIDIRECT alBufferiDirect{};
73 LPALBUFFERDATADIRECT alBufferDataDirect{};
75 LPALGENSOURCESDIRECT alGenSourcesDirect{};
76 LPALDELETESOURCESDIRECT alDeleteSourcesDirect{};
77 LPALSOURCEIDIRECT alSourceiDirect{};
78 LPALGETSOURCEIDIRECT alGetSourceiDirect{};
79 LPALGETSOURCEFDIRECT alGetSourcefDirect{};
80 LPALSOURCEPLAYDIRECT alSourcePlayDirect{};
83 struct SndFileDeleter {
84 void operator()(SNDFILE *sndfile) { sf_close(sndfile); }
86 using SndFilePtr = std::unique_ptr<SNDFILE,SndFileDeleter>;
88 enum class FormatType {
89 Int16,
90 Float,
91 IMA4,
92 MSADPCM
95 /* LoadBuffer loads the named audio file into an OpenAL buffer object, and
96 * returns the new buffer ID.
98 ALuint LoadSound(ALCcontext *context, const std::string_view filename)
100 /* Open the audio file and check that it's usable. */
101 SF_INFO sfinfo{};
102 SndFilePtr sndfile{sf_open(std::string{filename}.c_str(), SFM_READ, &sfinfo)};
103 if(!sndfile)
105 std::cerr<< "Could not open audio in "<<filename<<": "<<sf_strerror(sndfile.get())<<"\n";
106 return 0;
108 if(sfinfo.frames < 1)
110 std::cerr<< "Bad sample count in "<<filename<<" ("<<sfinfo.frames<<")\n";
111 return 0;
114 /* Detect a suitable format to load. Formats like Vorbis and Opus use float
115 * natively, so load as float to avoid clipping when possible. Formats
116 * larger than 16-bit can also use float to preserve a bit more precision.
118 FormatType sample_format{FormatType::Int16};
119 switch((sfinfo.format&SF_FORMAT_SUBMASK))
121 case SF_FORMAT_PCM_24:
122 case SF_FORMAT_PCM_32:
123 case SF_FORMAT_FLOAT:
124 case SF_FORMAT_DOUBLE:
125 case SF_FORMAT_VORBIS:
126 case SF_FORMAT_OPUS:
127 case SF_FORMAT_ALAC_20:
128 case SF_FORMAT_ALAC_24:
129 case SF_FORMAT_ALAC_32:
130 case 0x0080/*SF_FORMAT_MPEG_LAYER_I*/:
131 case 0x0081/*SF_FORMAT_MPEG_LAYER_II*/:
132 case 0x0082/*SF_FORMAT_MPEG_LAYER_III*/:
133 if(alIsExtensionPresentDirect(context, "AL_EXT_FLOAT32"))
134 sample_format = FormatType::Float;
135 break;
136 case SF_FORMAT_IMA_ADPCM:
137 /* ADPCM formats require setting a block alignment as specified in the
138 * file, which needs to be read from the wave 'fmt ' chunk manually
139 * since libsndfile doesn't provide it in a format-agnostic way.
141 if(sfinfo.channels <= 2 && (sfinfo.format&SF_FORMAT_TYPEMASK) == SF_FORMAT_WAV
142 && alIsExtensionPresentDirect(context, "AL_EXT_IMA4")
143 && alIsExtensionPresentDirect(context, "AL_SOFT_block_alignment"))
144 sample_format = FormatType::IMA4;
145 break;
146 case SF_FORMAT_MS_ADPCM:
147 if(sfinfo.channels <= 2 && (sfinfo.format&SF_FORMAT_TYPEMASK) == SF_FORMAT_WAV
148 && alIsExtensionPresentDirect(context, "AL_SOFT_MSADPCM")
149 && alIsExtensionPresentDirect(context, "AL_SOFT_block_alignment"))
150 sample_format = FormatType::MSADPCM;
151 break;
154 ALint byteblockalign{0}, splblockalign{0};
155 if(sample_format == FormatType::IMA4 || sample_format == FormatType::MSADPCM)
157 /* For ADPCM, lookup the wave file's "fmt " chunk, which is a
158 * WAVEFORMATEX-based structure for the audio format.
160 SF_CHUNK_INFO inf{"fmt ", 4, 0, nullptr};
161 SF_CHUNK_ITERATOR *iter{sf_get_chunk_iterator(sndfile.get(), &inf)};
163 /* If there's an issue getting the chunk or block alignment, load as
164 * 16-bit and have libsndfile do the conversion.
166 if(!iter || sf_get_chunk_size(iter, &inf) != SF_ERR_NO_ERROR || inf.datalen < 14)
167 sample_format = FormatType::Int16;
168 else
170 auto fmtbuf = std::vector<ALubyte>(inf.datalen, ALubyte{0});
171 inf.data = fmtbuf.data();
172 if(sf_get_chunk_data(iter, &inf) != SF_ERR_NO_ERROR)
173 sample_format = FormatType::Int16;
174 else
176 /* Read the nBlockAlign field, and convert from bytes- to
177 * samples-per-block (verifying it's valid by converting back
178 * and comparing to the original value).
180 byteblockalign = fmtbuf[12] | (fmtbuf[13]<<8);
181 if(sample_format == FormatType::IMA4)
183 splblockalign = (byteblockalign/sfinfo.channels - 4)/4*8 + 1;
184 if(splblockalign < 1
185 || ((splblockalign-1)/2 + 4)*sfinfo.channels != byteblockalign)
186 sample_format = FormatType::Int16;
188 else if(sample_format == FormatType::MSADPCM)
190 splblockalign = (byteblockalign/sfinfo.channels - 7)*2 + 2;
191 if(splblockalign < 2
192 || ((splblockalign-2)/2 + 7)*sfinfo.channels != byteblockalign)
193 sample_format = FormatType::Int16;
195 else
196 sample_format = FormatType::Int16;
201 if(sample_format == FormatType::Int16)
203 splblockalign = 1;
204 byteblockalign = sfinfo.channels * 2;
206 else if(sample_format == FormatType::Float)
208 splblockalign = 1;
209 byteblockalign = sfinfo.channels * 4;
212 /* Figure out the OpenAL format from the file and desired sample type. */
213 ALenum format{AL_NONE};
214 if(sfinfo.channels == 1)
216 if(sample_format == FormatType::Int16)
217 format = AL_FORMAT_MONO16;
218 else if(sample_format == FormatType::Float)
219 format = AL_FORMAT_MONO_FLOAT32;
220 else if(sample_format == FormatType::IMA4)
221 format = AL_FORMAT_MONO_IMA4;
222 else if(sample_format == FormatType::MSADPCM)
223 format = AL_FORMAT_MONO_MSADPCM_SOFT;
225 else if(sfinfo.channels == 2)
227 if(sample_format == FormatType::Int16)
228 format = AL_FORMAT_STEREO16;
229 else if(sample_format == FormatType::Float)
230 format = AL_FORMAT_STEREO_FLOAT32;
231 else if(sample_format == FormatType::IMA4)
232 format = AL_FORMAT_STEREO_IMA4;
233 else if(sample_format == FormatType::MSADPCM)
234 format = AL_FORMAT_STEREO_MSADPCM_SOFT;
236 else if(sfinfo.channels == 3)
238 if(sf_command(sndfile.get(), SFC_WAVEX_GET_AMBISONIC, nullptr, 0) == SF_AMBISONIC_B_FORMAT)
240 if(sample_format == FormatType::Int16)
241 format = AL_FORMAT_BFORMAT2D_16;
242 else if(sample_format == FormatType::Float)
243 format = AL_FORMAT_BFORMAT2D_FLOAT32;
246 else if(sfinfo.channels == 4)
248 if(sf_command(sndfile.get(), SFC_WAVEX_GET_AMBISONIC, nullptr, 0) == SF_AMBISONIC_B_FORMAT)
250 if(sample_format == FormatType::Int16)
251 format = AL_FORMAT_BFORMAT3D_16;
252 else if(sample_format == FormatType::Float)
253 format = AL_FORMAT_BFORMAT3D_FLOAT32;
256 if(!format)
258 std::cerr<< "Unsupported channel count: "<<sfinfo.channels<<"\n";
259 return 0;
262 if(sfinfo.frames/splblockalign > sf_count_t{std::numeric_limits<int>::max()}/byteblockalign)
264 std::cerr<< "Too many sample frames in "<<filename<<" ("<<sfinfo.frames<<")\n";
265 return 0;
268 /* Decode the whole audio file to a buffer. */
269 auto membuf = std::vector<std::byte>(static_cast<size_t>(sfinfo.frames / splblockalign
270 * byteblockalign));
272 sf_count_t num_frames{};
273 if(sample_format == FormatType::Int16)
274 num_frames = sf_readf_short(sndfile.get(), reinterpret_cast<short*>(membuf.data()),
275 sfinfo.frames);
276 else if(sample_format == FormatType::Float)
277 num_frames = sf_readf_float(sndfile.get(), reinterpret_cast<float*>(membuf.data()),
278 sfinfo.frames);
279 else
281 const sf_count_t count{sfinfo.frames / splblockalign * byteblockalign};
282 num_frames = sf_read_raw(sndfile.get(), membuf.data(), count);
283 if(num_frames > 0)
284 num_frames = num_frames / byteblockalign * splblockalign;
286 if(num_frames < 1)
288 std::cerr<< "Failed to read samples in "<<filename<<" ("<<num_frames<<")\n";
289 return 0;
292 const auto num_bytes = static_cast<ALsizei>(num_frames / splblockalign * byteblockalign);
294 std::cout<< "Loading: "<<filename<<" ("<<FormatName(format)<<", "<<sfinfo.samplerate<<"hz)\n"
295 <<std::flush;
297 ALuint buffer{};
298 alGenBuffersDirect(context, 1, &buffer);
299 if(splblockalign > 1)
300 alBufferiDirect(context, buffer, AL_UNPACK_BLOCK_ALIGNMENT_SOFT, splblockalign);
301 alBufferDataDirect(context, buffer, format, membuf.data(), num_bytes, sfinfo.samplerate);
303 /* Check if an error occurred, and clean up if so. */
304 if(ALenum err{alGetErrorDirect(context)}; err != AL_NO_ERROR)
306 std::cerr<< "OpenAL Error: "<<alGetStringDirect(context, err)<<"\n";
307 if(buffer && alIsBufferDirect(context, buffer))
308 alDeleteBuffersDirect(context, 1, &buffer);
309 return 0;
312 return buffer;
316 int main(al::span<std::string_view> args)
318 /* Print out usage if no arguments were specified */
319 if(args.size() < 2)
321 std::cerr<< "Usage: "<<args[0]<<" [-device <name>] <filename>\n";
322 return 1;
325 /* Initialize OpenAL. */
326 args = args.subspan(1);
328 ALCdevice *device{};
329 if(args.size() > 1 && args[0] == "-device")
331 device = p_alcOpenDevice(std::string{args[1]}.c_str());
332 if(!device)
333 std::cerr<< "Failed to open \""<<args[1]<<"\", trying default\n";
334 args = args.subspan(2);
336 if(!device)
337 device = p_alcOpenDevice(nullptr);
338 if(!device)
340 std::cerr<< "Could not open a device!\n";
341 return 1;
344 if(!p_alcIsExtensionPresent(device, "ALC_EXT_direct_context"))
346 std::cerr<< "ALC_EXT_direct_context not supported on device\n";
347 p_alcCloseDevice(device);
348 return 1;
351 /* On Windows with Creative's router, the device needs to be bootstrapped
352 * to use it through the driver directly. Otherwise the Direct functions
353 * aren't able to recognize the router's ALCcontexts. To handle this, we
354 * use the router's alcOpenDevice, alcGetProcAddress, and alcCloseDevice
355 * functions to open the device with the router, get the device driver's
356 * alcGetProcAddress2 function, and close the device with the router. Then
357 * call alcGetProcAddress2 with the null device handle to get the driver's
358 * functions. Afterward, we can open the device back up using the driver
359 * functions directly and continue on.
361 * Note that this will allow using other devices from the same driver just
362 * fine, but switching to a device on another driver will require using the
363 * original functions from the router (and require re-bootstrapping to use
364 * that driver's functions, if applicable). If controlling multiple devices
365 * with Direct functions from separate drivers simultaneously is desired, a
366 * good strategy may be to associate the driver's ALC and Direct functions
367 * with the ALCdevice and ALCcontext handles created from them.
369 * This is all unnecessary when not using Creative's router, including on
370 * non-Windows OSs or when using OpenAL Soft's router, where the original
371 * ALC functions can be used as normal.
374 const std::string devname{alcGetString(device, ALC_ALL_DEVICES_SPECIFIER)};
375 auto p_alcGetProcAddress2 = reinterpret_cast<LPALCGETPROCADDRESS2>(
376 p_alcGetProcAddress(device, "alcGetProcAddress2"));
377 p_alcCloseDevice(device);
379 /* Load the driver-specific ALC functions we'll be using. */
380 #define LOAD_PROC(N) p_##N = reinterpret_cast<decltype(p_##N)>(p_alcGetProcAddress2(nullptr, #N))
381 LOAD_PROC(alcOpenDevice);
382 LOAD_PROC(alcCloseDevice);
383 LOAD_PROC(alcIsExtensionPresent);
384 LOAD_PROC(alcGetProcAddress);
385 LOAD_PROC(alcCreateContext);
386 LOAD_PROC(alcDestroyContext);
387 LOAD_PROC(alcGetProcAddress);
388 #undef LOAD_PROC
389 device = p_alcOpenDevice(devname.c_str());
390 assert(device != nullptr);
393 /* Load the Direct API functions we're using. */
394 #define LOAD_PROC(N) N = reinterpret_cast<decltype(N)>(p_alcGetProcAddress(device, #N))
395 LOAD_PROC(alGetStringDirect);
396 LOAD_PROC(alGetErrorDirect);
397 LOAD_PROC(alIsExtensionPresentDirect);
399 LOAD_PROC(alGenBuffersDirect);
400 LOAD_PROC(alDeleteBuffersDirect);
401 LOAD_PROC(alIsBufferDirect);
402 LOAD_PROC(alBufferiDirect);
403 LOAD_PROC(alBufferDataDirect);
405 LOAD_PROC(alGenSourcesDirect);
406 LOAD_PROC(alDeleteSourcesDirect);
407 LOAD_PROC(alSourceiDirect);
408 LOAD_PROC(alGetSourceiDirect);
409 LOAD_PROC(alGetSourcefDirect);
410 LOAD_PROC(alSourcePlayDirect);
411 #undef LOAD_PROC
413 /* Create the context. It doesn't need to be set as current to use with the
414 * Direct API functions.
416 ALCcontext *context{p_alcCreateContext(device, nullptr)};
417 if(!context)
419 p_alcCloseDevice(device);
420 std::cerr<< "Could not create a context!\n";
421 return 1;
424 /* Load the sound into a buffer. */
425 const ALuint buffer{LoadSound(context, args[0])};
426 if(!buffer)
428 p_alcDestroyContext(context);
429 p_alcCloseDevice(device);
430 return 1;
433 /* Create the source to play the sound with. */
434 ALuint source{0};
435 alGenSourcesDirect(context, 1, &source);
436 alSourceiDirect(context, source, AL_BUFFER, static_cast<ALint>(buffer));
437 assert(alGetErrorDirect(context)==AL_NO_ERROR && "Failed to setup sound source");
439 /* Play the sound until it finishes. */
440 alSourcePlayDirect(context, source);
441 ALenum state{};
442 do {
443 al_nssleep(10000000);
444 alGetSourceiDirect(context, source, AL_SOURCE_STATE, &state);
446 /* Get the source offset. */
447 ALfloat offset{};
448 alGetSourcefDirect(context, source, AL_SEC_OFFSET, &offset);
449 printf("\rOffset: %f ", offset);
450 fflush(stdout);
451 } while(alGetErrorDirect(context) == AL_NO_ERROR && state == AL_PLAYING);
452 printf("\n");
454 /* All done. Delete resources, and close down OpenAL. */
455 alDeleteSourcesDirect(context, 1, &source);
456 alDeleteBuffersDirect(context, 1, &buffer);
458 p_alcDestroyContext(context);
459 p_alcCloseDevice(device);
461 return 0;
464 } // namespace
466 int main(int argc, char **argv)
468 assert(argc >= 0);
469 auto args = std::vector<std::string_view>(static_cast<unsigned int>(argc));
470 std::copy_n(argv, args.size(), args.begin());
471 return main(al::span{args});