/* * OpenAL Direct Context Example * * Copyright (c) 2024 by Chris Robinson * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /* This file contains an example for playing a sound buffer with the Direct API * extension. */ #include #include #include #include #include #include #include #include #include #include #include "sndfile.h" #include "AL/al.h" #include "AL/alc.h" #include "AL/alext.h" #include "alspan.h" #include "common/alhelpers.h" #include "win_main_utf8.h" namespace { /* On Windows when using Creative's router, we need to override the ALC * functions and access the driver functions directly. This isn't needed when * not using the router, or on other OSs. */ LPALCOPENDEVICE p_alcOpenDevice{alcOpenDevice}; LPALCCLOSEDEVICE p_alcCloseDevice{alcCloseDevice}; LPALCISEXTENSIONPRESENT p_alcIsExtensionPresent{alcIsExtensionPresent}; LPALCCREATECONTEXT p_alcCreateContext{alcCreateContext}; LPALCDESTROYCONTEXT p_alcDestroyContext{alcDestroyContext}; LPALCGETPROCADDRESS p_alcGetProcAddress{alcGetProcAddress}; LPALGETSTRINGDIRECT alGetStringDirect{}; LPALGETERRORDIRECT alGetErrorDirect{}; LPALISEXTENSIONPRESENTDIRECT alIsExtensionPresentDirect{}; LPALGENBUFFERSDIRECT alGenBuffersDirect{}; LPALDELETEBUFFERSDIRECT alDeleteBuffersDirect{}; LPALISBUFFERDIRECT alIsBufferDirect{}; LPALBUFFERIDIRECT alBufferiDirect{}; LPALBUFFERDATADIRECT alBufferDataDirect{}; LPALGENSOURCESDIRECT alGenSourcesDirect{}; LPALDELETESOURCESDIRECT alDeleteSourcesDirect{}; LPALSOURCEIDIRECT alSourceiDirect{}; LPALGETSOURCEIDIRECT alGetSourceiDirect{}; LPALGETSOURCEFDIRECT alGetSourcefDirect{}; LPALSOURCEPLAYDIRECT alSourcePlayDirect{}; struct SndFileDeleter { void operator()(SNDFILE *sndfile) { sf_close(sndfile); } }; using SndFilePtr = std::unique_ptr; enum class FormatType { Int16, Float, IMA4, MSADPCM }; /* LoadBuffer loads the named audio file into an OpenAL buffer object, and * returns the new buffer ID. */ ALuint LoadSound(ALCcontext *context, const std::string_view filename) { /* Open the audio file and check that it's usable. */ SF_INFO sfinfo{}; SndFilePtr sndfile{sf_open(std::string{filename}.c_str(), SFM_READ, &sfinfo)}; if(!sndfile) { std::cerr<< "Could not open audio in "<(inf.datalen, ALubyte{0}); inf.data = fmtbuf.data(); if(sf_get_chunk_data(iter, &inf) != SF_ERR_NO_ERROR) sample_format = FormatType::Int16; else { /* Read the nBlockAlign field, and convert from bytes- to * samples-per-block (verifying it's valid by converting back * and comparing to the original value). */ byteblockalign = fmtbuf[12] | (fmtbuf[13]<<8); if(sample_format == FormatType::IMA4) { splblockalign = (byteblockalign/sfinfo.channels - 4)/4*8 + 1; if(splblockalign < 1 || ((splblockalign-1)/2 + 4)*sfinfo.channels != byteblockalign) sample_format = FormatType::Int16; } else if(sample_format == FormatType::MSADPCM) { splblockalign = (byteblockalign/sfinfo.channels - 7)*2 + 2; if(splblockalign < 2 || ((splblockalign-2)/2 + 7)*sfinfo.channels != byteblockalign) sample_format = FormatType::Int16; } else sample_format = FormatType::Int16; } } } if(sample_format == FormatType::Int16) { splblockalign = 1; byteblockalign = sfinfo.channels * 2; } else if(sample_format == FormatType::Float) { splblockalign = 1; byteblockalign = sfinfo.channels * 4; } /* Figure out the OpenAL format from the file and desired sample type. */ ALenum format{AL_NONE}; if(sfinfo.channels == 1) { if(sample_format == FormatType::Int16) format = AL_FORMAT_MONO16; else if(sample_format == FormatType::Float) format = AL_FORMAT_MONO_FLOAT32; else if(sample_format == FormatType::IMA4) format = AL_FORMAT_MONO_IMA4; else if(sample_format == FormatType::MSADPCM) format = AL_FORMAT_MONO_MSADPCM_SOFT; } else if(sfinfo.channels == 2) { if(sample_format == FormatType::Int16) format = AL_FORMAT_STEREO16; else if(sample_format == FormatType::Float) format = AL_FORMAT_STEREO_FLOAT32; else if(sample_format == FormatType::IMA4) format = AL_FORMAT_STEREO_IMA4; else if(sample_format == FormatType::MSADPCM) format = AL_FORMAT_STEREO_MSADPCM_SOFT; } else if(sfinfo.channels == 3) { if(sf_command(sndfile.get(), SFC_WAVEX_GET_AMBISONIC, nullptr, 0) == SF_AMBISONIC_B_FORMAT) { if(sample_format == FormatType::Int16) format = AL_FORMAT_BFORMAT2D_16; else if(sample_format == FormatType::Float) format = AL_FORMAT_BFORMAT2D_FLOAT32; } } else if(sfinfo.channels == 4) { if(sf_command(sndfile.get(), SFC_WAVEX_GET_AMBISONIC, nullptr, 0) == SF_AMBISONIC_B_FORMAT) { if(sample_format == FormatType::Int16) format = AL_FORMAT_BFORMAT3D_16; else if(sample_format == FormatType::Float) format = AL_FORMAT_BFORMAT3D_FLOAT32; } } if(!format) { std::cerr<< "Unsupported channel count: "< sf_count_t{std::numeric_limits::max()}/byteblockalign) { std::cerr<< "Too many sample frames in "<(static_cast(sfinfo.frames / splblockalign * byteblockalign)); sf_count_t num_frames{}; if(sample_format == FormatType::Int16) num_frames = sf_readf_short(sndfile.get(), reinterpret_cast(membuf.data()), sfinfo.frames); else if(sample_format == FormatType::Float) num_frames = sf_readf_float(sndfile.get(), reinterpret_cast(membuf.data()), sfinfo.frames); else { const sf_count_t count{sfinfo.frames / splblockalign * byteblockalign}; num_frames = sf_read_raw(sndfile.get(), membuf.data(), count); if(num_frames > 0) num_frames = num_frames / byteblockalign * splblockalign; } if(num_frames < 1) { std::cerr<< "Failed to read samples in "<(num_frames / splblockalign * byteblockalign); std::cout<< "Loading: "< 1) alBufferiDirect(context, buffer, AL_UNPACK_BLOCK_ALIGNMENT_SOFT, splblockalign); alBufferDataDirect(context, buffer, format, membuf.data(), num_bytes, sfinfo.samplerate); /* Check if an error occurred, and clean up if so. */ if(ALenum err{alGetErrorDirect(context)}; err != AL_NO_ERROR) { std::cerr<< "OpenAL Error: "< args) { /* Print out usage if no arguments were specified */ if(args.size() < 2) { std::cerr<< "Usage: "<] \n"; return 1; } /* Initialize OpenAL. */ args = args.subspan(1); ALCdevice *device{}; if(args.size() > 1 && args[0] == "-device") { device = p_alcOpenDevice(std::string{args[1]}.c_str()); if(!device) std::cerr<< "Failed to open \""<( p_alcGetProcAddress(device, "alcGetProcAddress2")); p_alcCloseDevice(device); /* Load the driver-specific ALC functions we'll be using. */ #define LOAD_PROC(N) p_##N = reinterpret_cast(p_alcGetProcAddress2(nullptr, #N)) LOAD_PROC(alcOpenDevice); LOAD_PROC(alcCloseDevice); LOAD_PROC(alcIsExtensionPresent); LOAD_PROC(alcGetProcAddress); LOAD_PROC(alcCreateContext); LOAD_PROC(alcDestroyContext); LOAD_PROC(alcGetProcAddress); #undef LOAD_PROC device = p_alcOpenDevice(devname.c_str()); assert(device != nullptr); } /* Load the Direct API functions we're using. */ #define LOAD_PROC(N) N = reinterpret_cast(p_alcGetProcAddress(device, #N)) LOAD_PROC(alGetStringDirect); LOAD_PROC(alGetErrorDirect); LOAD_PROC(alIsExtensionPresentDirect); LOAD_PROC(alGenBuffersDirect); LOAD_PROC(alDeleteBuffersDirect); LOAD_PROC(alIsBufferDirect); LOAD_PROC(alBufferiDirect); LOAD_PROC(alBufferDataDirect); LOAD_PROC(alGenSourcesDirect); LOAD_PROC(alDeleteSourcesDirect); LOAD_PROC(alSourceiDirect); LOAD_PROC(alGetSourceiDirect); LOAD_PROC(alGetSourcefDirect); LOAD_PROC(alSourcePlayDirect); #undef LOAD_PROC /* Create the context. It doesn't need to be set as current to use with the * Direct API functions. */ ALCcontext *context{p_alcCreateContext(device, nullptr)}; if(!context) { p_alcCloseDevice(device); std::cerr<< "Could not create a context!\n"; return 1; } /* Load the sound into a buffer. */ const ALuint buffer{LoadSound(context, args[0])}; if(!buffer) { p_alcDestroyContext(context); p_alcCloseDevice(device); return 1; } /* Create the source to play the sound with. */ ALuint source{0}; alGenSourcesDirect(context, 1, &source); alSourceiDirect(context, source, AL_BUFFER, static_cast(buffer)); assert(alGetErrorDirect(context)==AL_NO_ERROR && "Failed to setup sound source"); /* Play the sound until it finishes. */ alSourcePlayDirect(context, source); ALenum state{}; do { al_nssleep(10000000); alGetSourceiDirect(context, source, AL_SOURCE_STATE, &state); /* Get the source offset. */ ALfloat offset{}; alGetSourcefDirect(context, source, AL_SEC_OFFSET, &offset); printf("\rOffset: %f ", offset); fflush(stdout); } while(alGetErrorDirect(context) == AL_NO_ERROR && state == AL_PLAYING); printf("\n"); /* All done. Delete resources, and close down OpenAL. */ alDeleteSourcesDirect(context, 1, &source); alDeleteBuffersDirect(context, 1, &buffer); p_alcDestroyContext(context); p_alcCloseDevice(device); return 0; } } // namespace int main(int argc, char **argv) { assert(argc >= 0); auto args = std::vector(static_cast(argc)); std::copy_n(argv, args.size(), args.begin()); return main(al::span{args}); }