Use fmt in relevant examples
[openal-soft.git] / examples / aldirect.cpp
blob9fffc0c6958bc9425b0f0e0e57a693b1801efade
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 <limits>
34 #include <memory>
35 #include <string>
36 #include <string_view>
37 #include <vector>
39 #include "sndfile.h"
41 #include "AL/al.h"
42 #include "AL/alc.h"
43 #include "AL/alext.h"
45 #include "alspan.h"
46 #include "common/alhelpers.h"
47 #include "fmt/core.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 fmt::println(stderr, "Could not open audio in {}: {}", filename,
106 sf_strerror(sndfile.get()));
107 return 0;
109 if(sfinfo.frames < 1)
111 fmt::println(stderr, "Bad sample count in {} ({})", filename, sfinfo.frames);
112 return 0;
115 /* Detect a suitable format to load. Formats like Vorbis and Opus use float
116 * natively, so load as float to avoid clipping when possible. Formats
117 * larger than 16-bit can also use float to preserve a bit more precision.
119 FormatType sample_format{FormatType::Int16};
120 switch((sfinfo.format&SF_FORMAT_SUBMASK))
122 case SF_FORMAT_PCM_24:
123 case SF_FORMAT_PCM_32:
124 case SF_FORMAT_FLOAT:
125 case SF_FORMAT_DOUBLE:
126 case SF_FORMAT_VORBIS:
127 case SF_FORMAT_OPUS:
128 case SF_FORMAT_ALAC_20:
129 case SF_FORMAT_ALAC_24:
130 case SF_FORMAT_ALAC_32:
131 case 0x0080/*SF_FORMAT_MPEG_LAYER_I*/:
132 case 0x0081/*SF_FORMAT_MPEG_LAYER_II*/:
133 case 0x0082/*SF_FORMAT_MPEG_LAYER_III*/:
134 if(alIsExtensionPresentDirect(context, "AL_EXT_FLOAT32"))
135 sample_format = FormatType::Float;
136 break;
137 case SF_FORMAT_IMA_ADPCM:
138 /* ADPCM formats require setting a block alignment as specified in the
139 * file, which needs to be read from the wave 'fmt ' chunk manually
140 * since libsndfile doesn't provide it in a format-agnostic way.
142 if(sfinfo.channels <= 2 && (sfinfo.format&SF_FORMAT_TYPEMASK) == SF_FORMAT_WAV
143 && alIsExtensionPresentDirect(context, "AL_EXT_IMA4")
144 && alIsExtensionPresentDirect(context, "AL_SOFT_block_alignment"))
145 sample_format = FormatType::IMA4;
146 break;
147 case SF_FORMAT_MS_ADPCM:
148 if(sfinfo.channels <= 2 && (sfinfo.format&SF_FORMAT_TYPEMASK) == SF_FORMAT_WAV
149 && alIsExtensionPresentDirect(context, "AL_SOFT_MSADPCM")
150 && alIsExtensionPresentDirect(context, "AL_SOFT_block_alignment"))
151 sample_format = FormatType::MSADPCM;
152 break;
155 ALint byteblockalign{0}, splblockalign{0};
156 if(sample_format == FormatType::IMA4 || sample_format == FormatType::MSADPCM)
158 /* For ADPCM, lookup the wave file's "fmt " chunk, which is a
159 * WAVEFORMATEX-based structure for the audio format.
161 SF_CHUNK_INFO inf{"fmt ", 4, 0, nullptr};
162 SF_CHUNK_ITERATOR *iter{sf_get_chunk_iterator(sndfile.get(), &inf)};
164 /* If there's an issue getting the chunk or block alignment, load as
165 * 16-bit and have libsndfile do the conversion.
167 if(!iter || sf_get_chunk_size(iter, &inf) != SF_ERR_NO_ERROR || inf.datalen < 14)
168 sample_format = FormatType::Int16;
169 else
171 auto fmtbuf = std::vector<ALubyte>(inf.datalen, ALubyte{0});
172 inf.data = fmtbuf.data();
173 if(sf_get_chunk_data(iter, &inf) != SF_ERR_NO_ERROR)
174 sample_format = FormatType::Int16;
175 else
177 /* Read the nBlockAlign field, and convert from bytes- to
178 * samples-per-block (verifying it's valid by converting back
179 * and comparing to the original value).
181 byteblockalign = fmtbuf[12] | (fmtbuf[13]<<8);
182 if(sample_format == FormatType::IMA4)
184 splblockalign = (byteblockalign/sfinfo.channels - 4)/4*8 + 1;
185 if(splblockalign < 1
186 || ((splblockalign-1)/2 + 4)*sfinfo.channels != byteblockalign)
187 sample_format = FormatType::Int16;
189 else if(sample_format == FormatType::MSADPCM)
191 splblockalign = (byteblockalign/sfinfo.channels - 7)*2 + 2;
192 if(splblockalign < 2
193 || ((splblockalign-2)/2 + 7)*sfinfo.channels != byteblockalign)
194 sample_format = FormatType::Int16;
196 else
197 sample_format = FormatType::Int16;
202 if(sample_format == FormatType::Int16)
204 splblockalign = 1;
205 byteblockalign = sfinfo.channels * 2;
207 else if(sample_format == FormatType::Float)
209 splblockalign = 1;
210 byteblockalign = sfinfo.channels * 4;
213 /* Figure out the OpenAL format from the file and desired sample type. */
214 ALenum format{AL_NONE};
215 if(sfinfo.channels == 1)
217 if(sample_format == FormatType::Int16)
218 format = AL_FORMAT_MONO16;
219 else if(sample_format == FormatType::Float)
220 format = AL_FORMAT_MONO_FLOAT32;
221 else if(sample_format == FormatType::IMA4)
222 format = AL_FORMAT_MONO_IMA4;
223 else if(sample_format == FormatType::MSADPCM)
224 format = AL_FORMAT_MONO_MSADPCM_SOFT;
226 else if(sfinfo.channels == 2)
228 if(sample_format == FormatType::Int16)
229 format = AL_FORMAT_STEREO16;
230 else if(sample_format == FormatType::Float)
231 format = AL_FORMAT_STEREO_FLOAT32;
232 else if(sample_format == FormatType::IMA4)
233 format = AL_FORMAT_STEREO_IMA4;
234 else if(sample_format == FormatType::MSADPCM)
235 format = AL_FORMAT_STEREO_MSADPCM_SOFT;
237 else if(sfinfo.channels == 3)
239 if(sf_command(sndfile.get(), SFC_WAVEX_GET_AMBISONIC, nullptr, 0) == SF_AMBISONIC_B_FORMAT)
241 if(sample_format == FormatType::Int16)
242 format = AL_FORMAT_BFORMAT2D_16;
243 else if(sample_format == FormatType::Float)
244 format = AL_FORMAT_BFORMAT2D_FLOAT32;
247 else if(sfinfo.channels == 4)
249 if(sf_command(sndfile.get(), SFC_WAVEX_GET_AMBISONIC, nullptr, 0) == SF_AMBISONIC_B_FORMAT)
251 if(sample_format == FormatType::Int16)
252 format = AL_FORMAT_BFORMAT3D_16;
253 else if(sample_format == FormatType::Float)
254 format = AL_FORMAT_BFORMAT3D_FLOAT32;
257 if(!format)
259 fmt::println(stderr, "Unsupported channel count: {}", sfinfo.channels);
260 return 0;
263 if(sfinfo.frames/splblockalign > sf_count_t{std::numeric_limits<int>::max()}/byteblockalign)
265 fmt::println(stderr, "Too many sample frames in {} ({})", filename, sfinfo.frames);
266 return 0;
269 /* Decode the whole audio file to a buffer. */
270 auto membuf = std::vector<std::byte>(static_cast<size_t>(sfinfo.frames / splblockalign
271 * byteblockalign));
273 sf_count_t num_frames{};
274 if(sample_format == FormatType::Int16)
275 num_frames = sf_readf_short(sndfile.get(), reinterpret_cast<short*>(membuf.data()),
276 sfinfo.frames);
277 else if(sample_format == FormatType::Float)
278 num_frames = sf_readf_float(sndfile.get(), reinterpret_cast<float*>(membuf.data()),
279 sfinfo.frames);
280 else
282 const sf_count_t count{sfinfo.frames / splblockalign * byteblockalign};
283 num_frames = sf_read_raw(sndfile.get(), membuf.data(), count);
284 if(num_frames > 0)
285 num_frames = num_frames / byteblockalign * splblockalign;
287 if(num_frames < 1)
289 fmt::println(stderr, "Failed to read samples in {} ({})", filename, num_frames);
290 return 0;
293 const auto num_bytes = static_cast<ALsizei>(num_frames / splblockalign * byteblockalign);
295 fmt::println("Loading: {} ({}, {}hz)", filename, FormatName(format), sfinfo.samplerate);
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 fmt::println(stderr, "OpenAL Error: {}", alGetStringDirect(context, err));
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 fmt::println(stderr, "Usage: {} [-device <name>] <filename>", args[0]);
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 fmt::println(stderr, "Failed to open \"{}\", trying default", args[1]);
334 args = args.subspan(2);
336 if(!device)
337 device = p_alcOpenDevice(nullptr);
338 if(!device)
340 fmt::println(stderr, "Could not open a device!");
341 return 1;
344 if(!p_alcIsExtensionPresent(device, "ALC_EXT_direct_context"))
346 fmt::println(stderr, "ALC_EXT_direct_context not supported on device");
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 fmt::println(stderr, "Could not create a context!");
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 fmt::print(" \rOffset: {:.02f}", 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});