X-Git-Url: https://git.dogcows.com/gitweb?p=chaz%2Fyoink;a=blobdiff_plain;f=src%2FMoof%2FSound.cc;h=a04d29b814943de018f678a3425448053f17ab8f;hp=59acfaa9af269886ec0cc34a8286671751f75505;hb=bffc879fc8ee8167bb123310d39fad4e2f426ffd;hpb=4701bf580b75a7d77a460c6f14f9fc31fb109bbb diff --git a/src/Moof/Sound.cc b/src/Moof/Sound.cc index 59acfaa..a04d29b 100644 --- a/src/Moof/Sound.cc +++ b/src/Moof/Sound.cc @@ -26,238 +26,563 @@ *******************************************************************************/ -#include +#include #include +#include +#include -#include -#include #include +#include +#include -#include "Mippleton.hh" +#include "Library.hh" +#include "Log.hh" #include "Sound.hh" +#include "Timer.hh" -#define BUFFER_SIZE (8 * 4096) +#define BUFFER_SIZE (64 * 1024) +//#define BUFFER_SIZE (5*2048) namespace Mf { -struct Sound::Impl +class Sound::Impl { +public: - static ALenum getAudioFormat(const Sound_AudioInfo& audioInfo) + static ALenum getAudioFormat(const vorbis_info* audioInfo) { - if (audioInfo.format == AUDIO_U8 || audioInfo.format == AUDIO_S8) - { - if (audioInfo.channels == 1) return AL_FORMAT_MONO8; - else return AL_FORMAT_STEREO8; - } - else - { - if (audioInfo.channels == 1) return AL_FORMAT_MONO16; - else return AL_FORMAT_STEREO16; - } + if (audioInfo->channels == 1) return AL_FORMAT_MONO16; + else return AL_FORMAT_STEREO16; } - struct Buffer : public Mippleton + + class Buffer; + typedef boost::shared_ptr BufferP; + + class Buffer : public Library { + OggVorbis_File mOggStream; + ALenum mFormat; + ALsizei mFreq; + std::vector mObjects; + + public: + Buffer(const std::string& name) : - Mippleton(name) + Library(name) { - objects[0] = 0; - objects[1] = 0; + mOggStream.datasource = 0; + openFile(); } ~Buffer() { - alDeleteBuffers(2, objects); + while (!mObjects.empty()) + { + alDeleteBuffers(1, &mObjects.back()); + mObjects.pop_back(); + } - if (sound) Sound_FreeSample(sound); + if (mOggStream.datasource) + { + ov_clear(&mOggStream); + } } - void loadFromFile(const std::string& filePath, bool stream) + void openFile() { - if (objects[0] != 0) return; + if (mOggStream.datasource) + { + ov_clear(&mOggStream); + mOggStream.datasource = 0; + } - sound = Sound_NewSampleFromFile(filePath.c_str(), - NULL, BUFFER_SIZE); + std::string filePath = Sound::getPath(getName()); + int result = ov_fopen((char*)filePath.c_str(), &mOggStream); - if (!sound) + if (result < 0) { - std::cerr << "could not load sound from file" << std::endl; - exit(1); + logWarning("error while loading sound %s", + getName().c_str()); + throw Exception(Exception::BAD_AUDIO_FORMAT); } - if (!stream) + vorbis_info* vorbisInfo = ov_info(&mOggStream, -1); + mFormat = getAudioFormat(vorbisInfo); + mFreq = vorbisInfo->rate; + + logDebug(" channels: %d", vorbisInfo->channels); + logDebug(" frequency: %d", vorbisInfo->rate); + } + + + void loadAll(ALuint source) + { + if (!mOggStream.datasource) openFile(); + if (!mOggStream.datasource) return; + + char data[BUFFER_SIZE]; + int size = 0; + + for (;;) { - unsigned decoded = Sound_DecodeAll(sound); - if (decoded == 0) + int section; + int result = ov_read(&mOggStream, data + size, + BUFFER_SIZE - size, 0, 2, 1, §ion); + + if (result > 0) + { + size += result; + } + else + { + if (result < 0) logWarning("vorbis playback error"); + break; + } + } + if (size == 0) { - std::cout << "decoded no bytes" << std::endl; - exit(1); + logWarning("decoded no bytes from %s", getName().c_str()); + //throw Exception(Exception::FILE_NOT_FOUND); + return; } - alGenBuffers(2, objects); - alBufferData(objects[0], getAudioFormat(sound->actual), sound->buffer, - sound->buffer_size, sound->actual.rate); - std::cerr << "buffer size: " << sound->buffer_size << std::endl; - std::cerr << "channels: " << (int)sound->actual.channels << std::endl; - std::cerr << "format: " << sound->actual.format << std::endl; - std::cerr << "frequency: " << sound->actual.rate << std::endl; + ALuint obj; + alGenBuffers(1, &obj); - Sound_FreeSample(sound); - sound = 0; - } - else + alBufferData(obj, mFormat, data, size, mFreq); + + mObjects.push_back(obj); + + alSourcei(source, AL_BUFFER, obj); + + // don't need this anymore + ov_clear(&mOggStream); + mOggStream.datasource = 0; + } + + + void beginStream(ALuint source, int nBuffers = 8) + { + if (!mOggStream.datasource) openFile(); + if (!mOggStream.datasource) return; + + ALuint objs[nBuffers]; + alGenBuffers(nBuffers, objs); + + for (int i = 0; i < nBuffers; ++i) { - std::cerr << "buffer size: " << sound->buffer_size << std::endl; - std::cerr << "channels: " << (int)sound->actual.channels << std::endl; - std::cerr << "format: " << sound->actual.format << std::endl; - std::cerr << "frequency: " << sound->actual.rate << std::endl; - alGenBuffers(2, objects); + mObjects.push_back(objs[i]); + stream(objs[i]); } + + alSourceQueueBuffers(source, nBuffers, objs); } - bool stream(ALuint buffer) + enum StreamStatus + { + STREAM_OK = 0, + STREAM_EOF = 1, + STREAM_WRONG = 2 + }; + + StreamStatus stream(ALuint buffer) { - int bytes = Sound_Decode(sound); + std::vector::iterator it = + std::find(mObjects.begin(), mObjects.end(), buffer); - if (bytes < BUFFER_SIZE) return false; + // that buffer doesn't belong to us + if (it == mObjects.end()) return STREAM_WRONG; + + char data[BUFFER_SIZE]; + int size = 0; + + while (size < BUFFER_SIZE) + { + int section; + int result = ov_read(&mOggStream, data + size, + BUFFER_SIZE - size, 0, 2, 1, §ion); + + if (result > 0) + { + size += result; + } + else + { + if (result < 0) logWarning("vorbis playback error"); + break; + } + } + + if (size == 0) return STREAM_EOF; + + alBufferData(buffer, mFormat, data, size, mFreq); + + return STREAM_OK; + } - alBufferData(buffer, getAudioFormat(sound->actual), sound->buffer, - sound->buffer_size, sound->actual.rate); - return false; + inline void rewind() + { + if (!mOggStream.datasource) openFile(); + else ov_raw_seek(&mOggStream, 0); } - Sound_Sample* sound; - ALuint objects[2]; - //ALfloat location[] = {0.0f, 0.0f, 0.0f}; - //ALfloat location2[] = {0.0f, 0.0f, 0.0f}; - //ALfloat orient[] = {0.0f, 0.0f, -1.0f, 0.0, 1.0, 0.0}; + // delete unused buffers, return true if all buffers deleted + inline bool clear() + { + // clear any openal errors + alGetError(); + + while (!mObjects.empty()) + { + ALuint buffer = mObjects.back(); + alDeleteBuffers(1, &buffer); + + // if an error occured, the buffer was not deleted because it's + // still in use by some source + if (alGetError() != AL_NO_ERROR) return false; + mObjects.pop_back(); + } - //alListenerfv(AL_POSITION, location); - //alListenerfv(AL_VELOCITY, location); - //alListenerfv(AL_VELOCITY, orient); + return true; + } }; - Impl(const std::string& name, bool stream = false) : - buffer_(Buffer::retain(name), Buffer::release) - { - if (!stream) buffer_->loadFromFile(Sound::getPath(name), stream); - else buffer_->loadFromFile(SoundStream::getPath(name), stream); - ALfloat location[] = {0.0f, 0.0f, 0.0f}; + Impl(const std::string& name) : + mBuffer(Buffer::getInstance(name)), + mIsPlaying(false), + mIsLooping(false) + { + ALfloat zero[] = {0.0f, 0.0f, 0.0f}; - alGenSources(1, &source_); + alGenSources(1, &mSource); + + alSourcef(mSource, AL_PITCH, 1.0f); + alSourcef(mSource, AL_GAIN, 1.0f); + alSourcefv(mSource, AL_POSITION, zero); + alSourcefv(mSource, AL_VELOCITY, zero); + } - alSourcef(source_, AL_PITCH, 1.0f); - alSourcef(source_, AL_GAIN, 1.0f); - alSourcefv(source_, AL_POSITION, location); - alSourcefv(source_, AL_VELOCITY, location); - alSourcei(source_, AL_LOOPING, AL_FALSE); + ~Impl() + { + alDeleteSources(1, &mSource); + } + + + void play() + { + ALenum type; + alGetSourcei(mSource, AL_SOURCE_TYPE, &type); - if (!stream) + if (type != AL_STATIC) { - alSourcei(source_, AL_BUFFER, buffer_->objects[0]); + mBuffer->loadAll(mSource); } - else + + alSourcei(mSource, AL_LOOPING, mIsLooping); + alSourcePlay(mSource); + mIsPlaying = true; + } + + + void stream() + { + ALenum type; + alGetSourcei(mSource, AL_SOURCE_TYPE, &type); + + alSourcei(mSource, AL_BUFFER, AL_NONE); + mBuffer->rewind(); + mBuffer->beginStream(mSource); + + alSourcei(mSource, AL_LOOPING, AL_FALSE); + alSourcePlay(mSource); + mIsPlaying = true; + + mStreamTimer.init(boost::bind(&Impl::streamUpdate, this, _1, _2), 1.0, + Timer::REPEAT); + } + + inline void update() + { + ALint finished = 0; + + alGetSourcei(mSource, AL_BUFFERS_PROCESSED, &finished); + + while (finished-- > 0) + { + ALuint buffer; + + alSourceUnqueueBuffers(mSource, 1, &buffer); + + Buffer::StreamStatus status = mBuffer->stream(buffer); + + if (status == Buffer::STREAM_OK) + { + alSourceQueueBuffers(mSource, 1, &buffer); + } + else if (status == Buffer::STREAM_EOF) + { + if (!mQueue.empty()) + { + // begin the next buffer in the queue + mExpired.push_back(mBuffer); + mBuffer = mQueue.front(); + mQueue.pop(); + mBuffer->beginStream(mSource, 1); + } + else if (mIsLooping) + { + // restart from the beginning + mBuffer->rewind(); + mBuffer->stream(buffer); + alSourceQueueBuffers(mSource, 1, &buffer); + } + } + else if (status == Buffer::STREAM_WRONG) + { + clear(); + mBuffer->beginStream(mSource, 1); + } + } + + ALenum state; + alGetSourcei(mSource, AL_SOURCE_STATE, &state); + + // restart playing if we're stopped but supposed to be playing... this + // means we didn't queue enough and the audio skipped + if (mIsPlaying && state != AL_PLAYING) { - buffer_->stream(buffer_->objects[0]); - buffer_->stream(buffer_->objects[1]); + alSourcePlay(mSource); + } + } - alSourceQueueBuffers(source_, 2, buffer_->objects); + inline void clear() + { + // try to remove expired buffers + std::vector::iterator it; + for (it = mExpired.end() - 1; it >= mExpired.begin(); --it) + { + if ((*it)->clear()) mExpired.erase(it); } } - ~Impl() + + void stop() + { + alSourceStop(mSource); + mIsPlaying = false; + } + + inline void pause() { - alDeleteSources(1, &source_); + alSourcePause(mSource); + mIsPlaying = false; + } + + inline void resume() + { + alSourcePlay(mSource); + mIsPlaying = true; } - void update() + inline void setSample(const std::string& name) { - int finished = 0; + bool playing = isPlaying(); + ALenum type; + alGetSourcei(mSource, AL_SOURCE_TYPE, &type); - alGetSourcei(source_, AL_BUFFERS_PROCESSED, &finished); + stop(); - while (finished-- > 0) + //alSourcei(mSource, AL_BUFFER, AL_NONE); + mBuffer = Buffer::getInstance(name); + + if (type == AL_STREAMING) { - ALuint buffer; + if (playing) stream(); + } + else + { + if (playing) play(); + } + } - alSourceUnqueueBuffers(source_, 1, &buffer); - buffer_->stream(buffer); - alSourceQueueBuffers(source_, 1, &buffer); + inline void enqueue(const std::string& name) + { + BufferP buffer = Buffer::getInstance(name); + mQueue.push(buffer); + } + + + inline bool isPlaying() const + { + if (mIsPlaying) return true; + + ALenum state; + alGetSourcei(mSource, AL_SOURCE_STATE, &state); + + return state == AL_PLAYING; + } + + + inline void setLooping(bool looping) + { + mIsLooping = looping; + + ALenum type; + alGetSourcei(mSource, AL_SOURCE_TYPE, &type); + + if (type != AL_STREAMING) + { + alSourcei(mSource, AL_LOOPING, mIsLooping); } } - boost::shared_ptr buffer_; - ALuint source_; - bool playing; -}; + ALuint mSource; + BufferP mBuffer; + + bool mIsPlaying; + bool mIsLooping; + + std::queue mQueue; + std::vector mExpired; + Timer mStreamTimer; + + void streamUpdate(Timer& timer, Scalar t) + { + // don't let the music die! + update(); + // TODO - might be nice to also allow using threads for streaming rather + // than a timer, probably as a compile-time option + } +}; Sound::Sound(const std::string& name) : // pass through - impl_(new Sound::Impl(name)) {} + mImpl(new Sound::Impl(name)) {} void Sound::play() { - //alSourceRewind(impl_->source_); - alSourcePlay(impl_->source_); - impl_->playing = true; + // pass through + mImpl->play(); +} + +void Sound::stream() +{ + // pass through + mImpl->stream(); +} + + +void Sound::stop() +{ + // pass through + mImpl->stop(); } void Sound::pause() { - alSourcePause(impl_->source_); - impl_->playing = false; + // pass through + mImpl->pause(); } -void Sound::togglePlayPause() +void Sound::resume() { - if (impl_->playing) pause(); - else play(); + // pass through + mImpl->resume(); } -void Sound::setGain(Scalar gain) +void Sound::toggle() { - alSourcef(impl_->source_, AL_GAIN, gain); + if (mImpl->mIsPlaying) pause(); + else resume(); } -std::string Sound::getPath(const std::string& name) +void Sound::setSample(const std::string& name) { - std::string path = Resource::getPath("sounds/" + name + ".ogg"); - return path; + // pass through + mImpl->setSample(name); } - -//############################################################################## +void Sound::enqueue(const std::string& name) +{ + // pass through + mImpl->enqueue(name); +} -SoundStream::SoundStream(const std::string& name) +bool Sound::isPlaying() const +{ // pass through - //impl_(name, true) {} + return mImpl->isPlaying(); +} + +void Sound::setPosition(const Vector3& position) { - impl_ = boost::shared_ptr(new Sound::Impl(name, true)); + float p[3] = {position[0], position[1], position[2]}; + alSourcefv(mImpl->mSource, AL_POSITION, p); } +void Sound::setVelocity(const Vector3& velocity) +{ + float v[3] = {velocity[0], velocity[1], velocity[2]}; + alSourcefv(mImpl->mSource, AL_VELOCITY, v); +} -void SoundStream::update(Scalar t, Scalar dt) +void Sound::setGain(Scalar gain) +{ + alSourcef(mImpl->mSource, AL_GAIN, float(gain)); +} + +void Sound::setPitch(Scalar pitch) +{ + alSourcef(mImpl->mSource, AL_PITCH, float(pitch)); +} + +void Sound::setLooping(bool looping) { // pass through - impl_->update(); + mImpl->setLooping(looping); +} + + +void Sound::setListenerPosition(const Vector3& position) +{ + alListener3f(AL_POSITION, float(position[0]), float(position[1]), + float(position[2])); } +void Sound::setListenerVelocity(const Vector3& velocity) +{ + alListener3f(AL_VELOCITY, float(velocity[0]), float(velocity[1]), + float(velocity[2])); +} -std::string SoundStream::getPath(const std::string& name) +void Sound::setListenerOrientation(const Vector3& forward, const Vector3& up) { - std::string path = Resource::getPath("sounds/" + name + ".xm"); + float vec[6]; + vec[0] = float(forward[0]); + vec[1] = float(forward[1]); + vec[2] = float(forward[2]); + vec[3] = float(up[0]); + vec[4] = float(up[1]); + vec[5] = float(up[2]); + alListenerfv(AL_ORIENTATION, vec); +} + + +std::string Sound::getPath(const std::string& name) +{ + std::string path = Resource::getPath("sounds/" + name + ".ogg"); return path; }