OpenAL Soft crashes in release mode (debug works fine) - c++

I have created a small sample program in C++ trying to play sounds with OpenAL Soft. The program crashes when compiled in release mode, when compiled in debug mode it works. I'm on OS X using 1.17.2.
I get this error message:
SoundTest(28958,0x70000021d000) malloc: *** error for object 0x7fbdd26062c8: incorrect checksum for freed object - object was probably modified after being freed.
This is the full sample program:
#include <iostream>
#include <AL/alc.h>
#include <AL/al.h>
#include <cmath>
using namespace std;
int main() {
// Reset error state just to be sure
alGetError();
ALCdevice *device = alcOpenDevice(NULL);
if (device == NULL) {
cout << "Error creating device" << endl;
return 1;
}
ALCcontext *context = alcCreateContext(device, NULL);
if (!alcMakeContextCurrent(context)) {
cout << "Failed to make context current" << endl;
return 1;
}
ALuint buffer;
// Set up sound buffer
alGenBuffers((ALuint)1, &buffer);
// Fill buffer with sine-wave
float freq = 440.f;
int seconds = 4;
unsigned sample_rate = 22050;
size_t buf_size = seconds * sample_rate;
short *samples;
samples = new short[buf_size];
for(int i=0; i<buf_size; ++i) {
samples[i] = (short) (32760 * sin((2.f * float(M_PI) * freq) / sample_rate * i ));
}
alBufferData(buffer, AL_FORMAT_MONO16, samples, buf_size, sample_rate);
ALuint source;
// Set up sound source
alGenSources((ALuint)1, &source);
alSourcef(source, AL_PITCH, 1);
alSourcef(source, AL_GAIN, 1);
alSource3f(source, AL_POSITION, 0, 0, 0);
alSource3f(source, AL_VELOCITY, 0, 0, 0);
alSourcei(source, AL_LOOPING, AL_FALSE);
alSourcei(source, AL_BUFFER, buffer);
// Start playing
alSourcePlay(source);
// Wait until the sound stops playing
ALenum state;
do {
alGetSourcei(source, AL_SOURCE_STATE, &state);
} while (state == AL_PLAYING);
// Clean up
alDeleteSources(1, &source);
alcMakeContextCurrent(NULL);
alcDestroyContext(context);
alcCloseDevice(device);
return 0;
}

If anyone else is having the same problem, have a look at this. The issue is resolved now.

Related

C++ writing to Framebuffer, wrong screensize

i try to write to the Linux framebuffer with c++, my problem is, that my program cant write to the whole screen, because the screensize i get is wrong. Although this code worked on an older VM, but i lost it.
#include <fcntl.h>
#include <unistd.h>
#include <linux/fb.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <cerrno>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
int main() {
fb_var_screeninfo vinfo;
fb_fix_screeninfo finfo;
size_t screensize = 0;
long int location = 0;
/* Open the file for reading and writing */
int fbfd = open("/dev/fb0", O_RDWR);
if(fbfd == -1) {
perror("Error: cannot open framebuffer device");
exit(1);
}
printf("The framebuffer device was opened successfully.\n");
/* Get fixed screen information */
if(ioctl(fbfd, FBIOGET_FSCREENINFO, &finfo) == -1) {
perror("Error reading fixed information");
exit(2);
}
/* Get variable screen information */
if(ioctl(fbfd, FBIOGET_VSCREENINFO, &vinfo) == -1) {
perror("Error reading variable information");
exit(3);
}
/* Figure out the size of the screen in bytes */
screensize = vinfo.xres * vinfo.yres * vinfo.bits_per_pixel / 8;
printf("Screen size is %ld\n", screensize);
printf("Vinfo.bpp = %d\n", vinfo.bits_per_pixel);
/* Map the device to memory */
auto fbp = static_cast<unsigned char*>(
mmap(0, screensize, PROT_READ | PROT_WRITE, MAP_SHARED, fbfd, 0));
if(fbp == MAP_FAILED) {
perror("Error: failed to map framebuffer device to memory");
exit(4);
}
printf("The framebuffer device was mapped to memory successfully.\n");
unsigned x = 0;
unsigned y = 0; /* Where we are going to put the pixel */
/* Figure out where in memory to put the pixel */
location = (x + vinfo.xoffset) * (vinfo.bits_per_pixel / 8) +
(y + vinfo.yoffset) * finfo.line_length;
for(uint32_t i = 0; i < vinfo.yres; i++) {
for(uint32_t count = 1; count < vinfo.xres; count++) {
fbp[location++] = 255; /* Some blue */
fbp[location++] = 0; /* A little green */
fbp[location++] = 0; /* A lot of red */
fbp[location++] = 0; /* No transparency */
}
}
munmap(fbp, screensize);
close(fbfd);
return 0;
}
I tried increasing the screensize by multiplying it by 2 and it wrote to the full screen, but then my coordinates are wrong.

symbol(s) not found for architecture x86_64 openAL

I am compiling the openAL tools on an OS X system and having troubles building the example files.
I am getting the error:
Undefined symbols for architecture x86_64:
"_main", referenced from:
implicit entry/start for main executable
(maybe you meant: _SDL_main)
ld: symbol(s) not found for architecture x86_64
When compiling on an linux machine, I'm getting no errors and the example binaries just work fine. What am I doing wrong?
That is the code of the program I am compiling:
#include <stdio.h>
#include <assert.h>
#include <math.h>
#include "AL/al.h"
#include "AL/alc.h"
#include "AL/alext.h"
#include "common/alhelpers.h"
#include "common/sdl_sound.h"
#ifndef M_PI
#define M_PI (3.14159265358979323846)
#endif
static LPALCGETSTRINGISOFT alcGetStringiSOFT;
static LPALCRESETDEVICESOFT alcResetDeviceSOFT;
/* LoadBuffer loads the named audio file into an OpenAL buffer object, and
* returns the new buffer ID. */
static ALuint LoadSound(const char *filename)
{
ALenum err, format, type, channels;
ALuint rate, buffer;
size_t datalen;
void *data;
FilePtr sound;
/* Open the audio file */
sound = openAudioFile(filename, 1000);
if(!sound)
{
fprintf(stderr, "Could not open audio in %s\n", filename);
closeAudioFile(sound);
return 0;
}
/* Get the sound format, and figure out the OpenAL format */
if(getAudioInfo(sound, &rate, &channels, &type) != 0)
{
fprintf(stderr, "Error getting audio info for %s\n", filename);
closeAudioFile(sound);
return 0;
}
format = GetFormat(channels, type, NULL);
if(format == AL_NONE)
{
fprintf(stderr, "Unsupported format (%s, %s) for %s\n",
ChannelsName(channels), TypeName(type), filename);
closeAudioFile(sound);
return 0;
}
/* Decode the whole audio stream to a buffer. */
data = decodeAudioStream(sound, &datalen);
if(!data)
{
fprintf(stderr, "Failed to read audio from %s\n", filename);
closeAudioFile(sound);
return 0;
}
/* Buffer the audio data into a new buffer object, then free the data and
* close the file. */
buffer = 0;
alGenBuffers(1, &buffer);
alBufferData(buffer, format, data, datalen, rate);
free(data);
closeAudioFile(sound);
/* Check if an error occured, and clean up if so. */
err = alGetError();
if(err != AL_NO_ERROR)
{
fprintf(stderr, "OpenAL Error: %s\n", alGetString(err));
if(buffer && alIsBuffer(buffer))
alDeleteBuffers(1, &buffer);
return 0;
}
return buffer;
}
int main(int argc, char **argv)
{
ALCdevice *device;
ALuint source, buffer;
const char *soundname;
const char *hrtfname;
ALCint hrtf_state;
ALCint num_hrtf;
ALdouble angle;
ALenum state;
/* Print out usage if no file was specified */
if(argc < 2 || (strcmp(argv[1], "-hrtf") == 0 && argc < 4))
{
fprintf(stderr, "Usage: %s [-hrtf <name>] <soundfile>\n", argv[0]);
return 1;
}
/* Initialize OpenAL with the default device, and check for HRTF support. */
if(InitAL() != 0)
return 1;
if(strcmp(argv[1], "-hrtf") == 0)
{
hrtfname = argv[2];
soundname = argv[3];
}
else
{
hrtfname = NULL;
soundname = argv[1];
}
device = alcGetContextsDevice(alcGetCurrentContext());
if(!alcIsExtensionPresent(device, "ALC_SOFT_HRTF"))
{
fprintf(stderr, "Error: ALC_SOFT_HRTF not supported\n");
CloseAL();
return 1;
}
/* Define a macro to help load the function pointers. */
#define LOAD_PROC(d, x) ((x) = alcGetProcAddress((d), #x))
LOAD_PROC(device, alcGetStringiSOFT);
LOAD_PROC(device, alcResetDeviceSOFT);
#undef LOAD_PROC
/* Enumerate available HRTFs, and reset the device using one. */
alcGetIntegerv(device, ALC_NUM_HRTF_SPECIFIERS_SOFT, 1, &num_hrtf);
if(!num_hrtf)
printf("No HRTFs found\n");
else
{
ALCint attr[5];
ALCint index = -1;
ALCint i;
printf("Available HRTFs:\n");
for(i = 0;i < num_hrtf;i++)
{
const ALCchar *name = alcGetStringiSOFT(device, ALC_HRTF_SPECIFIER_SOFT, i);
printf(" %d: %s\n", i, name);
/* Check if this is the HRTF the user requested. */
if(hrtfname && strcmp(name, hrtfname) == 0)
index = i;
}
i = 0;
attr[i++] = ALC_HRTF_SOFT;
attr[i++] = ALC_TRUE;
if(index == -1)
{
if(hrtfname)
printf("HRTF \"%s\" not found\n", hrtfname);
printf("Using default HRTF...\n");
}
else
{
printf("Selecting HRTF %d...\n", index);
attr[i++] = ALC_HRTF_ID_SOFT;
attr[i++] = index;
}
attr[i] = 0;
if(!alcResetDeviceSOFT(device, attr))
printf("Failed to reset device: %s\n", alcGetString(device, alcGetError(device)));
}
/* Check if HRTF is enabled, and show which is being used. */
alcGetIntegerv(device, ALC_HRTF_SOFT, 1, &hrtf_state);
if(!hrtf_state)
printf("HRTF not enabled!\n");
else
{
const ALchar *name = alcGetString(device, ALC_HRTF_SPECIFIER_SOFT);
printf("HRTF enabled, using %s\n", name);
}
fflush(stdout);
/* Load the sound into a buffer. */
buffer = LoadSound(soundname);
if(!buffer)
{
CloseAL();
return 1;
}
/* Create the source to play the sound with. */
source = 0;
alGenSources(1, &source);
alSourcei(source, AL_SOURCE_RELATIVE, AL_TRUE);
alSource3f(source, AL_POSITION, 0.0f, 0.0f, -1.0f);
alSourcei(source, AL_BUFFER, buffer);
assert(alGetError()==AL_NO_ERROR && "Failed to setup sound source");
/* Play the sound until it finishes. */
angle = 0.0;
alSourcePlay(source);
do {
al_nssleep(10000000);
/* Rotate the source around the listener by about 1/4 cycle per second.
* Only affects mono sounds.
*/
angle += 0.01 * M_PI * 0.5;
alSource3f(source, AL_POSITION, (ALfloat)sin(angle), 0.0f, -(ALfloat)cos(angle));
alGetSourcei(source, AL_SOURCE_STATE, &state);
} while(alGetError() == AL_NO_ERROR && state == AL_PLAYING);
/* All done. Delete resources, and close OpenAL. */
alDeleteSources(1, &source);
alDeleteBuffers(1, &buffer);
CloseAL();
return 0;
}
And that is the linker command (automatically produced by cmake):
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/cc -std=c11 -O2 -g -D_DEBUG -Wl,-search_paths_first -Wl,-headerpad_max_install_names CMakeFiles/alhrtf.dir/examples/alhrtf.c.o -o alhrtf libex-common.a /usr/local/lib/libSDL_sound.dylib -framework SDL2 -framework Cocoa -framework SDL2 -framework Cocoa libcommon.a libopenal.1.17.2.dylib libcommon.a -framework AudioToolbox -framework ApplicationServices -framework AudioUnit -framework CoreAudio -lpthread -ldl -lm -pthread -Wl,-rpath,/Library/Frameworks -Wl,-rpath,/Users/tschekar/Downloads/openal-soft/cmake

AccessViolationException when using C++ DLL from C#

I have a C++ DLL for use from C#. I have a function which takes a string passed to it, and I have those set on the C++ function parameters as const char * like so:
int __stdcall extract_all_frames(const char* szDestination, float scaleFactor)
The main body of this function is copied directly from a working FFmpeg example function so I'm almost certain the problem isn't there. I feel like the problem is in this modification I made to it:
//Open file
char szFilename[32];
sprintf_s(szFilename, sizeof(szFilename), "frame%d.ppm\0", iFrame);
// JOIN szFILENAME AND szDESTINATION
std::string buffer(szDestination, sizeof(szDestination));
buffer.append("\\");
buffer.append(szDestination);
Which is supposed to be a concatenated path and directory. I then pass buffer.c_str() into fopen_s(), which takes const char * not std::string. Whenever calling this function from C#, I get the following exception:
A first chance exception of type 'System.AccessViolationException' occurred in XRF FFmpeg Invoke Test.exe
Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
This is the complete code:
#include "stdafx.h"
#pragma comment (lib, "avcodec.lib")
#pragma comment (lib, "avformat.lib")
#pragma comment (lib, "avutil.lib")
#pragma comment (lib, "swscale.lib")
extern "C"
{
#include <libavcodec\avcodec.h>
#include <libavformat\avformat.h>
#include <libavutil\avutil.h>
#include <libswscale\swscale.h>
}
#include <string>
#include "Xrf.FFmpeg.hpp"
void save_frame(AVFrame* pFrame, int iFrame, const char* szDestination)
{
//Open file
char szFilename[32];
sprintf_s(szFilename, sizeof(szFilename), "frame%d.ppm\0", iFrame);
// JOIN szFILENAME AND szDESTINATION
std::string buffer(szDestination, sizeof(szDestination));
buffer.append("\\");
buffer.append(szDestination);
FILE* pFile;
errno_t openError = fopen_s(&pFile, buffer.c_str(), "wb");
if (pFile == NULL)
{
return;
}
//Write header
int width = pFrame->width;
int height = pFrame->height;
fprintf(pFile, "P6\n%d %d\n255\n", width, height);
//Write pixel data
for (int y = 0; y < height; y++)
{
fwrite(pFrame->data[0] + y * pFrame->linesize[0], 1, width * 3, pFile);
}
// Close file
fclose(pFile);
}
int __stdcall extract_all_frames(const char* szPath, const char* szDestination, float scaleFactor)
{
// Check if scaleFactor is valid
if ((scaleFactor != 0.f) &&
(scaleFactor > 3.f))
{
fprintf(stderr, "Xrf: Scale factor '%f' out of bounds!\nMust be greater than 0, and less then or equal to 3.0.\n", scaleFactor);
return -1;
}
// Register all formats and codecs
av_register_all();
AVFormatContext* pFormatCtx;
if (avformat_open_input(&pFormatCtx, szPath, nullptr, nullptr) != 0)
{
fprintf(stderr, "libavformat: Couldn't open file '%s'!\n", szPath);
return -1;
}
// Retrieve stream information
if (avformat_find_stream_info(pFormatCtx, nullptr) < 0)
{
fprintf(stderr, "libavformat: Unable to find stream information!\n");
return -1;
}
// Dump information about file onto standard error
av_dump_format(pFormatCtx, 0, szPath, 0);
// Find the first video stream
size_t i;
int videoStream = -1;
for (i = 0; i < pFormatCtx->nb_streams; i++)
{
if (pFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO)
{
videoStream = i;
break;
}
}
if (videoStream == -1)
{
fprintf(stderr, "libavformat: No video stream found!\n");
return -1;
}
// Get a pointer to the codec context for the video stream
AVCodecContext* pCodecCtx = pFormatCtx->streams[videoStream]->codec;
// Scale the frame
int scaleHeight = static_cast<int>(floor(pCodecCtx->height * scaleFactor));
int scaleWidth = static_cast<int>(floor(pCodecCtx->width * scaleFactor));
//Check if frame sizes are valid (not 0, because that's dumb)
if (scaleHeight == 0 || scaleWidth == 0)
{
fprintf(stderr, "Xrf: Scale factor caused a zero value in either width or height!\n");
return -1;
}
// Find the decoder for the video stream
AVCodec* pCodec = avcodec_find_decoder(pCodecCtx->codec_id);
if (pCodec == NULL)
{
fprintf(stderr, "libavcodec: Unsupported codec!\n");
return -1; // Codec not found
}
// Open codec
AVDictionary* optionsDict = nullptr;
if (avcodec_open2(pCodecCtx, pCodec, &optionsDict) < 0)
{
fprintf(stderr, "libavcodec: Couldn't open codec '%s'!\n", pCodec->long_name);
return -1;
}
// Allocate video frame
AVFrame* pFrame = av_frame_alloc();
// Allocate an AVFrame structure
AVFrame* pFrameRGB = av_frame_alloc();
if (pFrameRGB == NULL)
{
fprintf(stderr, "libavformat: Unable to allocate a YUV->RGB resampling AVFrame!\n");
return -1;
}
// Determine required buffer size and allocate buffer
int numBytes = avpicture_get_size(PIX_FMT_RGB24, scaleWidth, scaleHeight);
uint8_t* buffer = static_cast <uint8_t *> (av_malloc(numBytes * sizeof(uint8_t)));
struct SwsContext* sws_ctx = sws_getContext(pCodecCtx->width,
pCodecCtx->height,
pCodecCtx->pix_fmt,
scaleWidth,
scaleHeight,
PIX_FMT_RGB24,
SWS_BILINEAR,
nullptr, nullptr, nullptr);
// Assign appropriate parts of buffer to image planes in pFrameRGB
// Note that pFrameRGB is an AVFrame, but AVFrame is a superset
// of AVPicture
avpicture_fill(reinterpret_cast <AVPicture *> (pFrameRGB),
buffer,
PIX_FMT_RGB24,
scaleWidth,
scaleHeight);
// Read frames and save first five frames to disk
AVPacket packet;
int frameFinished;
while (av_read_frame(pFormatCtx, &packet) >= 0)
{
// Is this a packet from the video stream?
if (packet.stream_index == videoStream)
{
// Decode video frame
avcodec_decode_video2(pCodecCtx, pFrame, &frameFinished, &packet);
// Did we get a video frame?
if (frameFinished)
{
// Convert the image from its native format to RGB
sws_scale(sws_ctx,
static_cast <uint8_t const * const *> (pFrame->data),
pFrame->linesize,
0,
pCodecCtx->height,
pFrameRGB->data,
pFrameRGB->linesize);
// Save the frame to disk
if (++i <= 5)
{
save_frame(pFrameRGB, i, szDestination);
}
}
}
// Free the packet that was allocated by av_read_frame
av_free_packet(&packet);
}
av_free(buffer); // Free the RGB image
av_free(pFrameRGB);
av_free(pFrame); // Free the YUV frame
avcodec_close(pCodecCtx); // Close the codec
avformat_close_input(&pFormatCtx); // Close the video file
return 0;
}
I don't know if the error is in my modification (most likely, I'm extremely new to C++), or the other code, as the exception only throws on the invocation line in C#, not the actual C++ line causing the problem.
This is wrong:
std::string buffer(szDestination, sizeof(szDestination));
szDestination is a pointer, thus sizeof(szDestination) will return the pointer size, in bytes, not the number of characters.
If szDestination is a null terminated string, use strlen or similar function to determine the number of characters. If it isn't null terminated, then you need to pass the number of bytes to copy as a parameter.
The better thing to do is when your DLL function is called:
int __stdcall extract_all_frames(const char* szPath, const char* szDestination, float scaleFactor)
take those pointers and immediately assign them to std::string. Then drop all usage of char* or const char* from there. There is no need for your helper functions to deal with "dumb" character pointers.
Example:
int __stdcall extract_all_frames(const char* szPath, const char* szDestination, float scaleFactor)
{
std::string sPath = szPath;
std::string sDestination = sDestination;
// From here, use sPath and sDestination
//...
}
// redefinition of save_frame
//...
void save_frame(AVFrame* pFrame, int iFrame, const std::string& szDestination)
{
//Open file
std::string buffer = "frame" + to_string(iFrame) + ".ppm\0";
buffer.append("\\");
buffer.append(szDestination);
//...
}

C++ : AL/altypes.h No such file or directory

I am trying to get started with OpenAL.
I am trying to compile this program which I got from here using:
g++ main.cpp -lOpenAL
At the moment the error "AL/altypes.h" No such file or directory. Appears. Does anyone know how I can fix this? I have installed libopenal-dev. (I am on Ubuntu 13.04 I think?)
#include <iostream>
#include <cstdlib>
#include <AL/altypes.h>
#include <AL/al.h>
#include <AL/alu.h>
#include <AL/alut.h>
#define NUM_BUFFERS 1
#define NUM_SOURCES 1
#define NUM_ENVIRONMENTS 1
ALfloat listenerPos[] = {0.0, 0.0, 4.0};
ALfloat listenerVel[] = {0.0, 0.0, 0.0};
ALfloat listenerOri[] = {0.0, 0.0, 1.0, 0.0, 1.0, 0.0};
ALfloat source0Pos[] = {0.0, 0.0, 0.0};
ALfloat source0Vel[] = {0.0, 0.0, 0.0};
ALuint buffer[NUM_BUFFERS];
ALuint source[NUM_SOURCES];
ALuint environment[NUM_ENVIRONMENTS];
ALsizei size, freq;
ALenum format;
ALvoid* data;
void init(void)
{
alListenerfv(AL_POSITION,listenerPos);
alListenerfv(AL_VELOCITY,listenerVel);
alListenerfv(AL_ORIENTATION,listenerOri);
alGetError(); // clear any error messages
// Generate buffers, or else no sound will happen!
alGenBuffers(NUM_BUFFERS, buffer);
if(alGetError() != AL_NO_ERROR)
{
std::cout << "- Error creating buffers !!" << std::endl;
exit(1);
}
else
{
std::cout << "init() - No errors yet." << std::endl;
}
alutLoadWAVFile((Albyte *) "c.wav", &format, &data, size,&freq, &al_bool);
alBufferData(buffer[0],format,data,size,freq);
alutUnloadWAV(format,data,size,freq);
alGetError(); /* clear error */
alGenSources(NUM_SOURCES, source);
if(alGetError() != AL_NO_ERROR)
{
std::cout << "- Error creating sources !!" << std::endl;
exit(2);
}
else
{
std::cout << "init - no errors after alGenSources" << std::endl;
}
alSourcef(source[0], AL_PITCH, 1.0f);
alSourcef(source[0], AL_GAIN, 1.0f);
alSourcefv(source[0], AL_POSITION, source0Pos);
alSourcefv(source[0], AL_VELOCITY, source0Vel);
alSourcei(source[0], AL_BUFFER,buffer[0]);
alSourcei(source[0], AL_LOOPING, AL_TRUE);
}
int main()
{
//initialise openAL
alutInit(&argc, argv) ;
init();
return 0;
}
As an aside, this program won't actually do what I want at the moment.
I want to declare an array of double/int, populate it with data and play that data. Does anyone know how I can do that?
There is a package libalut-dev which contains utilities, however take a look at libsndfile for audio file I/O. Its always a holy grail to roll your own WAV / PCM parser which teaches you a lot and its not too difficult. WRT your aside ...the following openal code synthesizes data into an openal buffer then renders it as audio. Another page of code beyond below will get you a streaming audio player which is nice to have handy. compile it using
gcc -o gen_tone_08 gen_tone_08.c -lopenal -lm
Let us know how you get on
#include <stdio.h>
#include <stdlib.h> // gives malloc
#include <math.h>
#ifdef __APPLE__
#include <OpenAL/al.h>
#include <OpenAL/alc.h>
#elif __linux
#include <AL/al.h>
#include <AL/alc.h>
#endif
ALCdevice * openal_output_device;
ALCcontext * openal_output_context;
ALuint internal_buffer;
ALuint streaming_source[1];
int al_check_error(const char * given_label) {
ALenum al_error;
al_error = alGetError();
if(AL_NO_ERROR != al_error) {
printf("ERROR - %s (%s)\n", alGetString(al_error), given_label);
return al_error;
}
return 0;
}
void MM_init_al() {
const char * defname = alcGetString(NULL, ALC_DEFAULT_DEVICE_SPECIFIER);
openal_output_device = alcOpenDevice(defname);
openal_output_context = alcCreateContext(openal_output_device, NULL);
alcMakeContextCurrent(openal_output_context);
// setup buffer and source
alGenBuffers(1, & internal_buffer);
al_check_error("failed call to alGenBuffers");
}
void MM_exit_al() {
ALenum errorCode = 0;
// Stop the sources
alSourceStopv(1, & streaming_source[0]); // streaming_source
int ii;
for (ii = 0; ii < 1; ++ii) {
alSourcei(streaming_source[ii], AL_BUFFER, 0);
}
// Clean-up
alDeleteSources(1, &streaming_source[0]);
alDeleteBuffers(16, &streaming_source[0]);
errorCode = alGetError();
alcMakeContextCurrent(NULL);
errorCode = alGetError();
alcDestroyContext(openal_output_context);
alcCloseDevice(openal_output_device);
}
void MM_render_one_buffer() {
/* Fill buffer with Sine-Wave */
// float freq = 440.f;
float freq = 100.f;
float incr_freq = 0.1f;
int seconds = 4;
// unsigned sample_rate = 22050;
unsigned sample_rate = 44100;
double my_pi = 3.14159;
size_t buf_size = seconds * sample_rate;
short * samples = malloc(sizeof(short) * buf_size);
printf("\nhere is freq %f\n", freq);
int i=0;
for(; i<buf_size; ++i) {
samples[i] = 32760 * sin( (2.f * my_pi * freq)/sample_rate * i );
freq += incr_freq;
// incr_freq += incr_freq;
// freq *= factor_freq;
if (100.0 > freq || freq > 5000.0) {
incr_freq *= -1.0f;
}
}
/* upload buffer to OpenAL */
alBufferData( internal_buffer, AL_FORMAT_MONO16, samples, buf_size, sample_rate);
al_check_error("populating alBufferData");
free(samples);
/* Set-up sound source and play buffer */
// ALuint src = 0;
// alGenSources(1, &src);
// alSourcei(src, AL_BUFFER, internal_buffer);
alGenSources(1, & streaming_source[0]);
alSourcei(streaming_source[0], AL_BUFFER, internal_buffer);
// alSourcePlay(src);
alSourcePlay(streaming_source[0]);
// ---------------------
ALenum current_playing_state;
alGetSourcei(streaming_source[0], AL_SOURCE_STATE, & current_playing_state);
al_check_error("alGetSourcei AL_SOURCE_STATE");
while (AL_PLAYING == current_playing_state) {
printf("still playing ... so sleep\n");
sleep(1); // should use a thread sleep NOT sleep() for a more responsive finish
alGetSourcei(streaming_source[0], AL_SOURCE_STATE, & current_playing_state);
al_check_error("alGetSourcei AL_SOURCE_STATE");
}
printf("end of playing\n");
/* Dealloc OpenAL */
MM_exit_al();
} // MM_render_one_buffer
int main() {
MM_init_al();
MM_render_one_buffer();
}

OpenAL: locating freealut or fixing this code

I am writing a new framework for a game engine, but I'm stuck with one issue, OpenAL.
I'm usually using freealut for this, but i cant find it anywhere, the only site that hosted it is offline, and i don't have any copies of it. I even had to dissect some other guys' project to find openal32.lib. Either my google fu has grown weak, or the vast Internet really doesn't have any copies of it.
I found some example coding showing how to work openAL without the freealut framework, but i cant get it to load in multiple files, so i either have to find out why its not working, or somehow locate freealut, i found some sources for it in github, but at this moment, building freealut from source is out of the question.
I am using visual express c++ 2010 as the ide.
I modified the code I found, into this:
Basically its three commands to load, play and delete the sound files.
It works fine for one sound file, but when I try to load in more, it stops working.
#include "AudioLib.h"
#include <iostream>
#include <cstdlib>
#include <Windows.h>
#include <map>
#include <vector>
#include <AL\al.h>
#include <AL\alc.h>
using namespace std;
typedef map <const char *, ALuint > MapType;
MapType soundsbuffer;
MapType soundssource;
int endWithError(char* msg, int error=0)
{
//Display error message in console
cout << msg << "\n";
//system("PAUSE");
return error;
}
vector<const char *> soundslist;
ALCdevice *device;
ALCcontext *context;
int loadSound(const char * input) {
FILE *fp;
unsigned char* buf;
ALuint source;
ALuint buffer;
fp = NULL;
fp = fopen(input,"rb");
char type[4];
DWORD size,chunkSize;
short formatType,channels;
DWORD sampleRate, avgBytesPerSec;
short bytesPerSample, bitsPerSample;
DWORD dataSize;
//Check that the WAVE file is OK
fread(type,sizeof(char),4,fp); //Reads the first bytes in the file
if(type[0]!='R' || type[1]!='I' || type[2]!='F' || type[3]!='F') //Should be "RIFF"
return endWithError ("No RIFF"); //Not RIFF
fread(&size, sizeof(DWORD),1,fp); //Continue to read the file
fread(type, sizeof(char),4,fp); //Continue to read the file
if (type[0]!='W' || type[1]!='A' || type[2]!='V' || type[3]!='E') //This part should be "WAVE"
return endWithError("not WAVE"); //Not WAVE
fread(type,sizeof(char),4,fp); //Continue to read the file
if (type[0]!='f' || type[1]!='m' || type[2]!='t' || type[3]!=' ') //This part should be "fmt "
return endWithError("not fmt "); //Not fmt
//Now we know that the file is a acceptable WAVE file
//Info about the WAVE data is now read and stored
fread(&chunkSize,sizeof(DWORD),1,fp);
fread(&formatType,sizeof(short),1,fp);
fread(&channels,sizeof(short),1,fp);
fread(&sampleRate,sizeof(DWORD),1,fp);
fread(&avgBytesPerSec,sizeof(DWORD),1,fp);
fread(&bytesPerSample,sizeof(short),1,fp);
fread(&bitsPerSample,sizeof(short),1,fp);
fread(type,sizeof(char),4,fp);
if (type[0]!='d' || type[1]!='a' || type[2]!='t' || type[3]!='a') //This part should be "data"
return endWithError("Missing DATA"); //not data
fread(&dataSize,sizeof(DWORD),1,fp); //The size of the sound data is read
//Display the info about the WAVE file
cout << "Chunk Size: " << chunkSize << "\n";
cout << "Format Type: " << formatType << "\n";
cout << "Channels: " << channels << "\n";
cout << "Sample Rate: " << sampleRate << "\n";
cout << "Average Bytes Per Second: " << avgBytesPerSec << "\n";
cout << "Bytes Per Sample: " << bytesPerSample << "\n";
cout << "Bits Per Sample: " << bitsPerSample << "\n";
cout << "Data Size: " << dataSize << "\n";
buf= new unsigned char[dataSize]; //Allocate memory for the sound data
cout << fread(buf,sizeof(BYTE),dataSize,fp) << " bytes loaded\n"; //Read the sound data and display the
//number of bytes loaded.
//Should be the same as the Data Size if OK
//Now OpenAL needs to be initialized
//And an OpenAL Context
device = alcOpenDevice(NULL); //Open the device
if(!device) return endWithError("no sound device"); //Error during device oening
context = alcCreateContext(device, NULL); //Give the device a context
alcMakeContextCurrent(context); //Make the context the current
if(!context) return endWithError("no sound context"); //Error during context handeling
//Stores the sound data
ALuint frequency=sampleRate;; //The Sample Rate of the WAVE file
ALenum format=0; //The audio format (bits per sample, number of channels)
alGenBuffers(1, &buffer); //Generate one OpenAL Buffer and link to "buffer"
alGenSources(1, &source); //Generate one OpenAL Source and link to "source"
if(alGetError() != AL_NO_ERROR) return endWithError("Error GenSource"); //Error during buffer/source generation
//Figure out the format of the WAVE file
if(bitsPerSample == 8)
{
if(channels == 1)
format = AL_FORMAT_MONO8;
else if(channels == 2)
format = AL_FORMAT_STEREO8;
}
else if(bitsPerSample == 16)
{
if(channels == 1)
format = AL_FORMAT_MONO16;
else if(channels == 2)
format = AL_FORMAT_STEREO16;
}
if(!format) return endWithError("Wrong BitPerSample"); //Not valid format
alBufferData(buffer, format, buf, dataSize, frequency); //Store the sound data in the OpenAL Buffer
soundsbuffer[input] = buffer;
soundssource[input] = source;
soundslist.push_back(input);
if(alGetError() != AL_NO_ERROR) {
return endWithError("Error loading ALBuffer"); //Error during buffer loading
}
fclose(fp);
delete[] buf;
}
int playSound(const char * input) {
//Sound setting variables
ALfloat SourcePos[] = { 0.0, 0.0, 0.0 }; //Position of the source sound
ALfloat SourceVel[] = { 0.0, 0.0, 0.0 }; //Velocity of the source sound
ALfloat ListenerPos[] = { 0.0, 0.0, 0.0 }; //Position of the listener
ALfloat ListenerVel[] = { 0.0, 0.0, 0.0 }; //Velocity of the listener
ALfloat ListenerOri[] = { 0.0, 0.0, -1.0, 0.0, 1.0, 0.0 }; //Orientation of the listener
//First direction vector, then vector pointing up)
//Listener
alListenerfv(AL_POSITION, ListenerPos); //Set position of the listener
alListenerfv(AL_VELOCITY, ListenerVel); //Set velocity of the listener
alListenerfv(AL_ORIENTATION, ListenerOri); //Set orientation of the listener
ALuint source = soundssource[input];
ALuint buffer = soundsbuffer[input];
//Source
alSourcei (source, AL_BUFFER, buffer); //Link the buffer to the source
alSourcef (source, AL_PITCH, 1.0f ); //Set the pitch of the source
alSourcef (source, AL_GAIN, 1.0f ); //Set the gain of the source
alSourcefv(source, AL_POSITION, SourcePos); //Set the position of the source
alSourcefv(source, AL_VELOCITY, SourceVel); //Set the velocity of the source
alSourcei (source, AL_LOOPING, AL_FALSE ); //Set if source is looping sound
//PLAY
alSourcePlay(source); //Play the sound buffer linked to the source
if(alGetError() != AL_NO_ERROR) return endWithError("Error playing sound"); //Error when playing sound
//system("PAUSE"); //Pause to let the sound play
}
void deleteSound() {
//Clean-up
//Close the WAVE file
//Delete the sound data buffer
for(int i = 0; i < soundslist.size(); i++) {
const char * out = soundslist[i];
alDeleteSources(1, &soundssource[out]); //Delete the OpenAL Source
alDeleteBuffers(1, &soundsbuffer[out]);
}
//Delete the OpenAL Buffer
soundslist.clear();
alcMakeContextCurrent(NULL); //Make no context current
alcDestroyContext(context); //Destroy the OpenAL Context
alcCloseDevice(device);
}
So what I'm asking for:
I need either the freealut files, or some help with the code.
Any solutions?
Ok, the openal site seems to be partially back online.
For anyone who needs the link: http://connect.creativelabs.com/openal/Downloads/Forms/AllItems.aspx?RootFolder=http%3a%2f%2fconnect%2ecreativelabs%2ecom%2fopenal%2fDownloads%2fALUT&FolderCTID=0x01200073059C4C04B4D14B80686126F6C1A2E8