]> Dogcows Code - chaz/yoink/blobdiff - src/Moof/Sound.cc
tcp socket disconnecting by remote
[chaz/yoink] / src / Moof / Sound.cc
index 27905ba4a1f4893e6f69f981ab0b7e7a2ed5cbf3..ffa270e9e9876768669cd7ca3bdf850d46b5b09c 100644 (file)
@@ -1,42 +1,29 @@
 
-/*******************************************************************************
-
- Copyright (c) 2009, Charles McGarvey
- All rights reserved.
- Redistribution   and   use  in  source  and  binary  forms,  with  or  without
- modification, are permitted provided that the following conditions are met:
-   * Redistributions  of  source  code  must retain the above copyright notice,
-     this list of conditions and the following disclaimer.
-   * Redistributions  in binary form must reproduce the above copyright notice,
-     this  list of conditions and the following disclaimer in the documentation
-     and/or other materials provided with the distribution.
- THIS  SOFTWARE  IS  PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- AND  ANY  EXPRESS  OR  IMPLIED  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- DISCLAIMED.  IN  NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
- FOR  ANY  DIRECT,  INDIRECT,  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- DAMAGES  (INCLUDING,  BUT  NOT  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
- SERVICES;  LOSS  OF  USE,  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
- CAUSED  AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
- OR  TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-*******************************************************************************/
+/*]  Copyright (c) 2009-2010, Charles McGarvey  [**************************
+**]  All rights reserved.
+*
+* vi:ts=4 sw=4 tw=75
+*
+* Distributable under the terms and conditions of the 2-clause BSD license;
+* see the file COPYING for a complete text of the license.
+*
+**************************************************************************/
 
 #include <cstdio>
+#include <deque>
+#include <list>
 #include <string>
-#include <queue>
-#include <vector>
+
+#include <boost/algorithm/string.hpp>
 
 #include <AL/al.h>
+#include <AL/alc.h>
 #include <vorbis/codec.h>
 #include <vorbis/vorbisfile.h>
 
+#include "Error.hh"
+#include "Manager.hh"
 #include "Log.hh"
-#include "Mippleton.hh"
 #include "Sound.hh"
 #include "Timer.hh"
 
@@ -60,38 +47,27 @@ public:
        class Buffer;
        typedef boost::shared_ptr<Buffer> BufferP;
        
-       class Buffer : public Mippleton<Buffer>
+       class Buffer : public Manager<Buffer>
        {
-               OggVorbis_File                  mOggStream;
-               ALenum                                  mFormat;
-               ALsizei                                 mFreq;
-               std::vector<ALuint>             mObjects;
-
        public:
 
-               Buffer(const std::string& name) :
-                       Mippleton<Buffer>(name)
+               Buffer() :
+                       mBuffer(-1)
                {
                        mOggStream.datasource = 0;
-                       openFile();
                }
 
                ~Buffer()
                {
-                       while (!mObjects.empty())
-                       {
-                               alDeleteBuffers(1, &mObjects.back());
-                               mObjects.pop_back();
-                       }
-
                        if (mOggStream.datasource)
                        {
                                ov_clear(&mOggStream);
                        }
+                       if (int(mBuffer) != -1) alDeleteBuffers(1, &mBuffer);
                }
 
 
-               void openFile()
+               void init(const std::string& name)
                {
                        if (mOggStream.datasource)
                        {
@@ -99,28 +75,26 @@ public:
                                mOggStream.datasource = 0;
                        }
 
-                       std::string filePath = Sound::getPath(getName());
-                       int result = ov_fopen((char*)filePath.c_str(), &mOggStream);
+                       std::string path(name);
+                       if (!Sound::getPath(path))
+                       {
+                               Error(Error::RESOURCE_NOT_FOUND, path).raise();
+                       }
 
-                       if (result < 0)
+                       if (ov_fopen((char*)path.c_str(), &mOggStream) < 0)
                        {
-                               logWarning("error while loading sound %s",
-                                               getName().c_str());
-                               throw Exception(Exception::BAD_AUDIO_FORMAT);
+                               Error(Error::UNKNOWN_AUDIO_FORMAT, path).raise();
                        }
 
                        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) init(getName());
                        if (!mOggStream.datasource) return;
 
                        char data[BUFFER_SIZE];
@@ -144,58 +118,23 @@ public:
                        }
                        if (size == 0)
                        {
-                               logWarning("decoded no bytes from %s", getName().c_str());
-                               //throw Exception(Exception::FILE_NOT_FOUND);
+                               logWarning << "decoded no bytes from "
+                                                  << getName() << std::endl;
                                return;
                        }
 
-                       ALuint obj;
-                       alGenBuffers(1, &obj);
-
-                       alBufferData(obj, mFormat, data, size, mFreq);
+                       alGenBuffers(1, &mBuffer);
 
-                       mObjects.push_back(obj);
+                       alBufferData(mBuffer, mFormat, data, size, mFreq);
+                       alSourcei(source, AL_BUFFER, mBuffer);
 
-                       alSourcei(source, AL_BUFFER, obj);
-
-                       // don't need this anymore
+                       // don't need to keep this loaded
                        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)
-                       {
-                               mObjects.push_back(objs[i]);
-                               stream(objs[i]);
-                       }
-
-                       alSourceQueueBuffers(source, nBuffers, objs);
-               }
-
-               enum StreamStatus
-               {
-                       STREAM_OK               = 0,
-                       STREAM_EOF              = 1,
-                       STREAM_WRONG    = 2
-               };
-
-               StreamStatus stream(ALuint buffer)
+               bool stream(ALuint buffer)
                {
-                       std::vector<ALuint>::iterator it =
-                               std::find(mObjects.begin(), mObjects.end(), buffer);
-
-                       // that buffer doesn't belong to us
-                       if (it == mObjects.end()) return STREAM_WRONG;
-
                        char data[BUFFER_SIZE];
                        int size = 0;
 
@@ -216,98 +155,128 @@ public:
                                }
                        }
 
-                       if (size == 0) return STREAM_EOF;
+                       if (size == 0) return false;
 
                        alBufferData(buffer, mFormat, data, size, mFreq);
 
-                       return STREAM_OK;
+                       return true;
                }
 
-               inline void rewind()
+               void rewind()
                {
-                       if (!mOggStream.datasource) openFile();
+                       if (!mOggStream.datasource) init(getName());
                        else ov_raw_seek(&mOggStream, 0);
                }
 
 
-               // delete unused buffers, return true if all buffers deleted
-               inline bool clear()
-               {
-                       // clear any openal errors
-                       alGetError();
+       private:
 
-                       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;
+               OggVorbis_File  mOggStream;
+               ALenum                  mFormat;
+               ALsizei                 mFreq;
+               ALuint                  mBuffer;
+       };
 
-                               mObjects.pop_back();
-                       }
 
-                       return true;
-               }
-       };
+       Impl()
+       {
+               init();
+       }
 
+       Impl(const std::string& name)
+       {
+               init();
+               enqueue(name);
+       }
 
-       Impl(const std::string& name) :
-               mBuffer(Buffer::getInstance(name)),
-               mIsPlaying(false),
-               mIsLooping(false)
+       void init()
        {
-               ALfloat zero[] = {0.0f, 0.0f, 0.0f};
-               
+               retainBackend();
+
+               mIsLoaded = false;
+               mIsPlaying = false;
+               mIsLooping = false;
+
                alGenSources(1, &mSource);
 
+               ALfloat zero[] = {0.0f, 0.0f, 0.0f};
                alSourcef(mSource,  AL_PITCH, 1.0f);
                alSourcef(mSource,  AL_GAIN, 1.0f);
                alSourcefv(mSource, AL_POSITION, zero);
                alSourcefv(mSource, AL_VELOCITY, zero);
+
+               alSourcei(mSource, AL_LOOPING, mIsLooping);
        }
 
        ~Impl()
        {
+               stop();
+
                alDeleteSources(1, &mSource);
+
+               while (!mBuffers.empty())
+               {
+                       alDeleteBuffers(1, &mBuffers.back());
+                       mBuffers.pop_back();
+               }
+
+               releaseBackend();
        }
 
 
        void play()
        {
-               ALenum type;
-               alGetSourcei(mSource, AL_SOURCE_TYPE, &type);
+               if (mQueue.empty()) return;
 
-               if (type != AL_STATIC)
-               {
-                       mBuffer->loadAll(mSource);
-               }
+               if (!mIsLoaded) mQueue.front()->loadAll(mSource);
 
-               alSourcei(mSource, AL_LOOPING, mIsLooping);
                alSourcePlay(mSource);
-               mIsPlaying = true;
+               mIsLoaded = true;
        }
 
 
-       void stream()
+       void playStream()
        {
-               ALenum type;
-               alGetSourcei(mSource, AL_SOURCE_TYPE, &type);
+               if (mQueue.empty()) return;
 
-               alSourcei(mSource, AL_BUFFER, AL_NONE);
-               mBuffer->rewind();
-               mBuffer->beginStream(mSource);
+               if (!mIsPlaying)
+               {
+                       alSourcei(mSource, AL_LOOPING, false);
+                       bufferStream();
+               }
+
+               if (!mStreamTimer.isValid())
+               {
+                       mStreamTimer.init(boost::bind(&Impl::streamUpdate, this, _1, _2),
+                                       1.0, Timer::REPEAT);
+               }
 
-               alSourcei(mSource, AL_LOOPING, AL_FALSE);
                alSourcePlay(mSource);
                mIsPlaying = true;
+       }
+
+       void bufferStream()
+       {
+               ALuint buffer;
+               for (int i = mBuffers.size(); i <= 8; ++i)
+               {
+                       alGenBuffers(1, &buffer);
 
-               mStreamTimer.init(boost::bind(&Impl::streamUpdate, this, _1, _2), 1.0,
-                               Timer::REPEAT);
+                       if (mQueue.front()->stream(buffer))
+                       {
+                               alSourceQueueBuffers(mSource, 1, &buffer);
+                               mBuffers.push_back(buffer);
+                       }
+                       else
+                       {
+                               alDeleteBuffers(1, &buffer);
+                               break;
+                       }
+               }
        }
 
-       inline void update()
+
+       void update()
        {
                ALint finished = 0;
 
@@ -315,111 +284,105 @@ public:
 
                while (finished-- > 0)
                {
-                       ALuint buffer;
-
-                       alSourceUnqueueBuffers(mSource, 1, &buffer);
+                       ALuint bufferObj;
+                       alSourceUnqueueBuffers(mSource, 1, &bufferObj);
 
-                       Buffer::StreamStatus status = mBuffer->stream(buffer);
+                       BufferP buffer = mQueue.front();
+                       bool streamed = buffer->stream(bufferObj);
 
-                       if (status == Buffer::STREAM_OK)
+                       if (streamed)
                        {
-                               alSourceQueueBuffers(mSource, 1, &buffer);
+                               alSourceQueueBuffers(mSource, 1, &bufferObj);
                        }
-                       else if (status == Buffer::STREAM_EOF)
+                       else
                        {
+                               // the buffer couldn't be streamed, so get rid of it
+                               mQueue.pop_front();
+
                                if (!mQueue.empty())
                                {
                                        // begin the next buffer in the queue
-                                       mExpired.push_back(mBuffer);
-                                       mBuffer = mQueue.front();
-                                       mQueue.pop();
-                                       mBuffer->beginStream(mSource, 1);
+                                       mQueue.front()->rewind();
+                                       mQueue.front()->stream(bufferObj);
+                                       alSourceQueueBuffers(mSource, 1, &bufferObj);
+                                       logInfo("loading new buffer");
+
+                                       // queue up any unused buffers
+                                       bufferStream();
                                }
                                else if (mIsLooping)
                                {
-                                       // restart from the beginning
-                                       mBuffer->rewind();
-                                       mBuffer->stream(buffer);
-                                       alSourceQueueBuffers(mSource, 1, &buffer);
+                                       // reload the same buffer
+                                       mQueue.push_back(buffer);
+                                       buffer->rewind();
+                                       buffer->stream(bufferObj);
+                                       alSourceQueueBuffers(mSource, 1, &bufferObj);
+                                       logInfo("looping same buffer");
+                               }
+                               else
+                               {
+                                       // nothing more to play, stopping...
+                                       mIsPlaying = false;
+                                       std::remove(mBuffers.begin(), mBuffers.end(),
+                                                               bufferObj);
                                }
-                       }
-                       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
+               // 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)
                {
                        alSourcePlay(mSource);
                }
        }
 
-       inline void clear()
-       {
-               // try to remove expired buffers
-               std::vector<BufferP>::iterator it;
-               for (it = mExpired.end() - 1; it >= mExpired.begin(); --it)
-               {
-                       if ((*it)->clear()) mExpired.erase(it);
-               }
-       }
-
 
        void stop()
        {
                alSourceStop(mSource);
                mIsPlaying = false;
+
+               mStreamTimer.invalidate();
        }
 
-       inline void pause()
+       void pause()
        {
                alSourcePause(mSource);
                mIsPlaying = false;
-       }
 
-       inline void resume()
-       {
-               alSourcePlay(mSource);
-               mIsPlaying = true;
+               mStreamTimer.invalidate();
        }
 
 
-       inline void setSample(const std::string& name)
+       void setSample(const std::string& name)
        {
-               bool playing = isPlaying();
-               ALenum type;
-               alGetSourcei(mSource, AL_SOURCE_TYPE, &type);
-
                stop();
+               alSourcei(mSource, AL_BUFFER, AL_NONE);
 
-               //alSourcei(mSource, AL_BUFFER, AL_NONE);
-               mBuffer = Buffer::getInstance(name);
+               mQueue.clear();
+               mIsLoaded = false;
 
-               if (type == AL_STREAMING)
-               {
-                       if (playing) stream();
-               }
-               else
+               enqueue(name);
+
+               while (!mBuffers.empty())
                {
-                       if (playing) play();
+                       alDeleteBuffers(1, &mBuffers.back());
+                       mBuffers.pop_back();
                }
        }
 
-       inline void enqueue(const std::string& name)
+       void enqueue(const std::string& name)
        {
                BufferP buffer = Buffer::getInstance(name);
-               mQueue.push(buffer);
+               mQueue.push_back(buffer);
        }
 
 
-       inline bool isPlaying() const
+       bool isPlaying() const
        {
                if (mIsPlaying) return true;
 
@@ -430,7 +393,7 @@ public:
        }
 
 
-       inline void setLooping(bool looping)
+       void setLooping(bool looping)
        {
                mIsLooping = looping;
 
@@ -444,44 +407,92 @@ public:
        }
 
 
+       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
+       }
+
+       static void retainBackend()
+       {
+               if (gRetainCount++ == 0)
+               {
+                       gAlDevice = alcOpenDevice(0);
+                       gAlContext = alcCreateContext(gAlDevice, 0);
+                       if (!gAlDevice || !gAlContext)
+                       {
+                               const char* error = alcGetString(gAlDevice,
+                                               alcGetError(gAlDevice));
+                               logError << "audio subsystem initialization failure: "
+                                                << error << std::endl;
+                       }
+                       else
+                       {
+                               alcMakeContextCurrent(gAlContext);
+                               logInfo << "opened sound device `"
+                                               << alcGetString(gAlDevice,
+                                                                               ALC_DEFAULT_DEVICE_SPECIFIER)
+                                               << "'" << std::endl;
+                       }
+               }
+       }
+
+       static void releaseBackend()
+       {
+               if (--gRetainCount == 0)
+               {
+                       alcMakeContextCurrent(0);
+                       alcDestroyContext(gAlContext);
+                       alcCloseDevice(gAlDevice);
+               }
+       }
+
+
        ALuint                                  mSource;
-       BufferP                                 mBuffer;
+       std::list<ALuint>               mBuffers;
 
+       bool                                    mIsLoaded;
        bool                                    mIsPlaying;
        bool                                    mIsLooping;
 
-       std::queue<BufferP>             mQueue;
-       std::vector<BufferP>    mExpired;
+       std::deque<BufferP>             mQueue;
 
        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
-       }
+       static unsigned                 gRetainCount;
+       static ALCdevice*               gAlDevice;
+       static ALCcontext*              gAlContext;
 };
 
+unsigned       Sound::Impl::gRetainCount = 0;
+ALCdevice*     Sound::Impl::gAlDevice = 0;
+ALCcontext*    Sound::Impl::gAlContext = 0;
+
+
+Sound::Sound() :
+       // pass through
+       mImpl(new Sound::Impl) {}
+
 Sound::Sound(const std::string& name) :
        // pass through
        mImpl(new Sound::Impl(name)) {}
 
 
-void Sound::play()
+void Sound::setSample(const std::string& name)
 {
        // pass through
-       mImpl->play();
+       mImpl->setSample(name);
 }
 
-void Sound::stream()
+
+void Sound::play()
 {
        // pass through
-       mImpl->stream();
+       mImpl->play();
 }
 
-
 void Sound::stop()
 {
        // pass through
@@ -494,48 +505,30 @@ void Sound::pause()
        mImpl->pause();
 }
 
-void Sound::resume()
-{
-       // pass through
-       mImpl->resume();
-}
 
 void Sound::toggle()
 {
-       if (mImpl->mIsPlaying) pause();
-       else resume();
-}
-
-
-void Sound::setSample(const std::string& name)
-{
-       // pass through
-       mImpl->setSample(name);
+       if (isPlaying()) pause();
+       else play();
 }
 
-void Sound::enqueue(const std::string& name)
-{
-       // pass through
-       mImpl->enqueue(name);
-}
-
-
 bool Sound::isPlaying() const
 {
        // pass through
        return mImpl->isPlaying();
 }
 
+
 void Sound::setPosition(const Vector3& position)
 {
-       float p[3] = {position[0], position[1], position[2]};
-       alSourcefv(mImpl->mSource, AL_POSITION, p);
+       float vec[3] = {position[0], position[1], position[2]};
+       alSourcefv(mImpl->mSource, AL_POSITION, vec);
 }
 
 void Sound::setVelocity(const Vector3& velocity)
 {
-       float v[3] = {velocity[0], velocity[1], velocity[2]};
-       alSourcefv(mImpl->mSource, AL_VELOCITY, v);
+       float vec[3] = {velocity[0], velocity[1], velocity[2]};
+       alSourcefv(mImpl->mSource, AL_VELOCITY, vec);
 }
 
 void Sound::setGain(Scalar gain)
@@ -557,17 +550,18 @@ void Sound::setLooping(bool looping)
 
 void Sound::setListenerPosition(const Vector3& position)
 {
-       alListener3f(AL_POSITION, float(position[0]), float(position[1]),
-                       float(position[2]));
+       float vec[] = {position[0], position[1], position[2]};
+       alListenerfv(AL_POSITION, vec);
 }
 
 void Sound::setListenerVelocity(const Vector3& velocity)
 {
-       alListener3f(AL_VELOCITY, float(velocity[0]), float(velocity[1]),
-                       float(velocity[2]));
+       float vec[] = {velocity[0], velocity[1], velocity[2]};
+       alListenerfv(AL_VELOCITY, vec);
 }
 
-void Sound::setListenerOrientation(const Vector3& forward, const Vector3& up)
+void Sound::setListenerOrientation(const Vector3& forward,
+                                                                  const Vector3& up)
 {
        float vec[6];
        vec[0] = float(forward[0]);
@@ -580,14 +574,28 @@ void Sound::setListenerOrientation(const Vector3& forward, const Vector3& up)
 }
 
 
-std::string Sound::getPath(const std::string& name)
+bool Sound::getPath(std::string& name)
 {
-       std::string path = Resource::getPath("sounds/" + name + ".ogg");
-       return path;
+       return Resource::getPath(name, "sounds/", "ogg");
 }
 
 
-} // namespace Mf
+//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
 
-/** vim: set ts=4 sw=4 tw=80: *************************************************/
+void SoundStream::enqueue(const std::string& name)
+{
+       // pass through
+       mImpl->enqueue(name);
+}
+
+
+void SoundStream::play()
+{
+       // pass through
+       mImpl->playStream();
+}
+
+
+} // namespace Mf
 
This page took 0.041636 seconds and 4 git commands to generate.