Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/presentation2/src/orxonox/sound/SoundManager.cc @ 6409

Last change on this file since 6409 was 6409, checked in by rgrieder, 15 years ago

Better sound source management: Sources are created on demand with a minimum of minSources_ (default: 16) and deleted again when more than 50% more sources are available than used.

  • Property svn:eol-style set to native
File size: 22.5 KB
Line 
1/*
2 *   ORXONOX - the hottest 3D action shooter ever to exist
3 *                    > www.orxonox.net <
4 *
5 *
6 *   License notice:
7 *
8 *   This program is free software; you can redistribute it and/or
9 *   modify it under the terms of the GNU General Public License
10 *   as published by the Free Software Foundation; either version 2
11 *   of the License, or (at your option) any later version.
12 *
13 *   This program is distributed in the hope that it will be useful,
14 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
15 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 *   GNU General Public License for more details.
17 *
18 *   You should have received a copy of the GNU General Public License
19 *   along with this program; if not, write to the Free Software
20 *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
21 *
22 *   Author:
23 *       Erwin 'vaiursch' Herrsche
24 *       Kevin Young
25 *       Reto Grieder
26 *   Co-authors:
27 *      ...
28 *
29 */
30
31#include "SoundManager.h"
32
33#include <AL/alut.h>
34#include <utility>
35
36#include "util/Exception.h"
37#include "util/Math.h"
38#include "util/ScopeGuard.h"
39#include "util/Clock.h"
40#include "core/ConfigValueIncludes.h"
41#include "core/CoreIncludes.h"
42#include "core/GameMode.h"
43#include "core/ScopedSingletonManager.h"
44#include "core/Resource.h"
45#include "SoundBuffer.h"
46#include "BaseSound.h"
47#include "AmbientSound.h"
48#include "WorldSound.h"
49
50namespace orxonox
51{
52    ManageScopedSingleton(SoundManager, ScopeID::Graphics, true);
53
54    std::string SoundManager::getALErrorString(ALenum code)
55    {
56        switch (code)
57        {
58        case AL_NO_ERROR:          return "No error";
59        case AL_INVALID_NAME:      return "Invalid AL parameter name";
60        case AL_INVALID_ENUM:      return "Invalid AL enum";
61        case AL_INVALID_VALUE:     return "Invalid AL value";
62        case AL_INVALID_OPERATION: return "Invalid AL operation";
63        case AL_OUT_OF_MEMORY:     return "AL reports out of memory";
64        default:                   return "Unknown AL error";
65        }
66    }
67
68    SoundManager::SoundManager()
69        : effectsPoolSize_(0)
70    {
71        RegisterRootObject(SoundManager);
72
73        // See whether we even want to load
74        bool bDisableSound_ = false;
75        SetConfigValue(bDisableSound_, false);
76        if (bDisableSound_)
77            ThrowException(InitialisationAborted, "Sound: Not loading at all");
78
79        if (!alutInitWithoutContext(NULL, NULL))
80            ThrowException(InitialisationFailed, "Sound Error: ALUT initialisation failed: " << alutGetErrorString(alutGetError()));
81        Loki::ScopeGuard alutExitGuard = Loki::MakeGuard(&alutExit);
82
83/*
84        // Get list of available sound devices and display them
85        const char* devices = alcGetString(NULL, ALC_DEVICE_SPECIFIER);
86        char* device = new char[strlen(devices)+1];
87        strcpy(device, devices);
88        std::string renderDevice;
89        SetConfigValue(renderDevice, std::string(device)).description("Sound device used for rendering");
90        COUT(4) << "Sound: Available devices: ";
91        while (true)
92        {
93            this->deviceNames_.push_back(devices);
94            COUT(4) << '"' << devices << "\", ";
95            devices += strlen(devices) + 1;
96            if (*devices == '\0')
97                break;
98        }
99        COUT(4) << std::endl;
100
101        // Open the selected device
102        COUT(3) << "Sound: Opening device \"" << renderDevice << '\' << std::endl;
103        this->device_ = alcOpenDevice(renderDevice.c_str());
104*/
105        this->device_ = alcOpenDevice(NULL);
106        if (this->device_ == NULL)
107        {
108            COUT(1) << "Sound: Could not open sound device. Have you installed OpenAL?" << std::endl;
109#ifdef ORXONOX_PLATFORM_WINDOWS
110            COUT(1) << "Sound: Just getting the DLL with the dependencies is not enough for Windows (esp. Windows 7)!" << std::endl;
111#endif
112            ThrowException(InitialisationFailed, "Sound Error: Could not open sound device.");
113        }
114        Loki::ScopeGuard closeDeviceGuard = Loki::MakeGuard(&alcCloseDevice, this->device_);
115
116        // Create sound context and make it the currently used one
117        this->context_ = alcCreateContext(this->device_, NULL);
118        if (this->context_ == NULL)
119            ThrowException(InitialisationFailed, "Sound Error: Could not create ALC context");
120        Loki::ScopeGuard desroyContextGuard = Loki::MakeGuard(&alcDestroyContext, this->context_);
121        if (!alcMakeContextCurrent(this->context_))
122            ThrowException(InitialisationFailed, "Sound Error: Could not use ALC context");
123
124        GameMode::setPlaysSound(true);
125        Loki::ScopeGuard resetPlaysSoundGuard = Loki::MakeGuard(&GameMode::setPlaysSound, false);
126
127        // Get some information about the sound
128        if (const char* version = alGetString(AL_VERSION))
129            COUT(4) << "Sound: --- OpenAL Version: " << version << std::endl;
130        if (const char* vendor = alGetString(AL_VENDOR))
131            COUT(4) << "Sound: --- OpenAL Vendor : " << vendor << std::endl;
132        if (const char* types = alutGetMIMETypes(ALUT_LOADER_BUFFER))
133            COUT(4) << "Sound: --- Supported MIME Types: " << types << std::endl;
134        else
135            COUT(2) << "Sound Warning: MIME Type retrieval failed: " << alutGetErrorString(alutGetError()) << std::endl;
136
137        this->mute_[SoundType::All]     = 1.0f;
138        this->mute_[SoundType::Music]   = 1.0f;
139        this->mute_[SoundType::Effects] = 1.0f;
140
141        this->setConfigValues();
142
143        // Try to get at least one source
144        ALuint source;
145        alGenSources(1, &source);
146        if (!alGetError() && alIsSource(source))
147            this->availableSoundSources_.push_back(source);
148        else
149            ThrowException(InitialisationFailed, "Sound Error: Could not create even a single source");
150        // Create a few initial sources
151        this->createSoundSources(this->minSources_ - 1);
152
153        // Disarm guards
154        alutExitGuard.Dismiss();
155        closeDeviceGuard.Dismiss();
156        desroyContextGuard.Dismiss();
157        resetPlaysSoundGuard.Dismiss();
158
159        COUT(4) << "Sound: Initialisation complete" << std::endl;
160    }
161
162    SoundManager::~SoundManager()
163    {
164        GameMode::setPlaysSound(false);
165
166        // Relieve context to destroy it
167        if (!alcMakeContextCurrent(NULL))
168            COUT(1) << "Sound Error: Could not unset ALC context" << std::endl;
169        alcDestroyContext(this->context_);
170        if (ALCenum error = alcGetError(this->device_))
171        {
172            if (error == AL_INVALID_OPERATION)
173                COUT(1) << "Sound Error: Could not destroy ALC context because it is the current one" << std::endl;
174            else
175                COUT(1) << "Sound Error: Could not destroy ALC context because it is invalid" << std::endl;
176        }
177#ifdef AL_VERSION_1_1
178        if (!alcCloseDevice(this->device_))
179            COUT(1) << "Sound Error: Could not destroy ALC device. This might be because there are still buffers in use!" << std::endl;
180#else
181        alcCloseDevice(this->device_);
182#endif
183        if (!alutExit())
184            COUT(1) << "Sound Error: Closing ALUT failed: " << alutGetErrorString(alutGetError()) << std::endl;
185    }
186
187    void SoundManager::setConfigValues()
188    {
189        SetConfigValue(crossFadeStep_, 0.2f)
190            .description("Determines how fast sounds should fade, per second.")
191            .callback(this, &SoundManager::checkFadeStepValidity);
192
193        SetConfigValueAlias(volume_[SoundType::All], "soundVolume_", 1.0f)
194            .description("Defines the overall volume.")
195            .callback(this, &SoundManager::checkSoundVolumeValidity);
196        SetConfigValueAlias(volume_[SoundType::Music], "ambientVolume_", 1.0f)
197            .description("Defines the ambient volume.")
198            .callback(this, &SoundManager::checkAmbientVolumeValidity);
199        SetConfigValueAlias(volume_[SoundType::Effects], "effectsVolume_", 1.0f)
200            .description("Defines the effects volume.")
201            .callback(this, &SoundManager::checkEffectsVolumeValidity);
202
203        SetConfigValue(minSources_, 16)
204            .description("Minimum number of sources being generated (if possible)");
205        SetConfigValue(maxSources_, 1024)
206            .description("Maximum number of sources to be made available");
207    }
208
209    void SoundManager::preUpdate(const Clock& time)
210    {
211        this->processCrossFading(time.getDeltaTime());
212
213        // Check whether a sound object has stopped playing
214        for (unsigned int i = 0; i < this->usedSoundSources_.size(); ++i)
215        {
216            ALint state;
217            alGetSourcei(this->usedSoundSources_[i].first, AL_SOURCE_STATE, &state);
218            if (state == AL_STOPPED)
219            {
220                this->usedSoundSources_[i].second->stop();
221                --i;
222            }
223        }
224    }
225
226    void SoundManager::checkFadeStepValidity()
227    {
228        if (crossFadeStep_ <= 0.0 || crossFadeStep_ >= 1.0 )
229        {
230            COUT(2) << "Sound warning: fade step out of range, ignoring change." << std::endl;
231            ResetConfigValue(crossFadeStep_);
232        }
233    }
234
235    void SoundManager::checkVolumeValidity(SoundType::Value type)
236    {
237        float clampedVolume = clamp(this->volume_[type], 0.0f, 1.0f);
238        if (clampedVolume != this->volume_[type])
239            COUT(2) << "Sound warning: Volume setting (" << type << ") out of range, clamping." << std::endl;
240        this->updateVolume(type);
241    }
242
243    void SoundManager::setVolume(float vol, SoundType::Value type)
244    {
245        if (type < 0 || type > SoundType::Effects)
246            return;
247        this->volume_[type] = vol;
248        this->checkVolumeValidity(type);
249    }
250
251    float SoundManager::getVolume(SoundType::Value type)
252    {
253        if (type < 0 || type > SoundType::Effects)
254            return 0.0f;
255        return this->volume_[type];
256    }
257
258    float SoundManager::getRealVolume(SoundType::Value type)
259    {
260        if (type != SoundType::Music && type != SoundType::Effects)
261            return 0.0f;
262        return this->volume_[SoundType::All] * this->mute_[SoundType::All] * this->volume_[type] * this->mute_[type];
263    }
264
265    void SoundManager::updateVolume(SoundType::Value type)
266    {
267        switch(type)
268        {
269        case SoundType::All:
270            for (ObjectList<BaseSound>::iterator it = ObjectList<BaseSound>::begin(); it != ObjectList<BaseSound>::end(); ++it)
271                (*it)->updateVolume();
272            break;
273        case SoundType::Music:
274            for (ObjectList<AmbientSound>::iterator it = ObjectList<AmbientSound>::begin(); it != ObjectList<AmbientSound>::end(); ++it)
275                (*it)->updateVolume();
276            break;
277        case SoundType::Effects:
278            for (ObjectList<WorldSound>::iterator it = ObjectList<WorldSound>::begin(); it != ObjectList<WorldSound>::end(); ++it)
279                (*it)->updateVolume();
280            break;
281        default:
282            assert(false);
283        }
284    }
285
286    void SoundManager::toggleMute(SoundType::Value type)
287    {
288        if (type < 0 || type > SoundType::Effects)
289            return;
290        this->mute_[type] = (this->mute_[type] == 0) ? 1.0f : 0.0f;
291        this->updateVolume(type);
292    }
293
294    bool SoundManager::getMute(SoundType::Value type)
295    {
296        if (type < 0 || type > SoundType::Effects)
297            return true;
298        return (this->mute_[type] == 0);
299    }
300
301    void SoundManager::setListenerPosition(const Vector3& position)
302    {
303        alListener3f(AL_POSITION, position.x, position.y, position.z);
304        ALenum error = alGetError();
305        if (error == AL_INVALID_VALUE)
306            COUT(2) << "Sound: OpenAL: Invalid listener position" << std::endl;
307    }
308
309    void SoundManager::setListenerOrientation(const Quaternion& orientation)
310    {
311        // update listener orientation
312        const Vector3& direction = -orientation.zAxis();
313        const Vector3& up = orientation.yAxis();
314
315        ALfloat orient[6] = { direction.x, direction.y, direction.z, up.x, up.y, up.z };
316
317        alListenerfv(AL_ORIENTATION, orient);
318        ALenum error = alGetError();
319        if (error == AL_INVALID_VALUE)
320            COUT(2) << "Sound: OpenAL: Invalid listener orientation" << std::endl;
321    }
322
323    void SoundManager::registerAmbientSound(AmbientSound* newAmbient)
324    {
325        if (newAmbient != NULL)
326        {
327            for (AmbientList::const_iterator it = this->ambientSounds_.begin(); it != this->ambientSounds_.end(); ++it)
328            {
329                if (it->first == newAmbient)
330                {
331                    COUT(2) << "Sound warning: Will not play an AmbientSound twice." << std::endl;
332                    return;
333                }
334            }
335
336            if (!this->ambientSounds_.empty())
337            {
338                this->fadeOut(ambientSounds_.front().first);
339            }
340            this->ambientSounds_.push_front(std::make_pair(newAmbient, false));
341            newAmbient->doPlay();
342            this->fadeIn(newAmbient);
343        }
344    }
345
346    void SoundManager::unregisterAmbientSound(AmbientSound* oldAmbient)
347    {
348        if (oldAmbient == NULL || ambientSounds_.empty())
349            return;
350
351        if (this->ambientSounds_.front().first == oldAmbient)
352        {
353            this->fadeOut(oldAmbient);
354            this->ambientSounds_.pop_front();
355            if (!this->ambientSounds_.empty())
356            {
357                if (!this->ambientSounds_.front().second) // Not paused before
358                {
359                    this->ambientSounds_.front().first->doPlay();
360                }
361                this->fadeIn(this->ambientSounds_.front().first);
362            }
363        }
364        else
365        {
366            for (AmbientList::iterator it = this->ambientSounds_.begin(); it != this->ambientSounds_.end(); ++it)
367            {
368                if (it->first == oldAmbient)
369                {
370                    this->fadeOut(oldAmbient);
371                    this->ambientSounds_.erase(it);
372                    break;
373                }
374            }
375        }
376    }
377
378    void SoundManager::pauseAmbientSound(AmbientSound* ambient)
379    {
380        if (ambient != NULL)
381        {
382            for (AmbientList::iterator it = this->ambientSounds_.begin(); it != this->ambientSounds_.end(); ++it)
383            {
384                if (it->first == ambient)
385                {
386                    it->second = true;
387                    this->fadeOut(it->first);
388                    return;
389                }
390            }
391        }
392    }
393
394    void SoundManager::fadeIn(const SmartPtr<AmbientSound>& sound)
395    {
396        // If we're already fading out --> remove that
397        for (std::list<SmartPtr<AmbientSound> >::iterator it = this->fadeOutList_.begin(); it != this->fadeOutList_.end(); it++)
398        {
399            if (*it == sound)
400            {
401                this->fadeOutList_.erase(it);
402                break;
403            }
404        }
405        // No duplicate entries
406        if (std::find(this->fadeInList_.begin(), this->fadeInList_.end(), sound) == this->fadeInList_.end())
407            this->fadeInList_.push_back(sound);
408    }
409
410    void SoundManager::fadeOut(const SmartPtr<AmbientSound>& sound)
411    {
412        // If we're already fading in --> remove that
413        for (std::list<SmartPtr<AmbientSound> >::iterator it = this->fadeInList_.begin(); it != this->fadeInList_.end(); it++)
414        {
415            if (*it == sound)
416            {
417                this->fadeInList_.erase(it);
418                break;
419            }
420        }
421        // No duplicate entries
422        if (std::find(this->fadeOutList_.begin(), this->fadeOutList_.end(), sound) == this->fadeOutList_.end())
423            this->fadeOutList_.push_back(sound);
424    }
425
426    void SoundManager::processCrossFading(float dt)
427    {
428
429        // Hacky solution to the fade delay while loading a level.
430        if(dt > 0.2)
431        {
432            return;
433        }
434
435        // FADE IN
436        for (std::list<SmartPtr<AmbientSound> >::iterator it= this->fadeInList_.begin(); it != this->fadeInList_.end(); )
437        {
438            if ((*it)->getVolume() + this->crossFadeStep_*dt > 1.0f)
439            {
440                (*it)->setVolume(1.0f);
441                this->fadeInList_.erase(it++);
442            }
443            else
444            {
445                (*it)->setVolume((*it)->getVolume() + this->crossFadeStep_*dt);
446                ++it;
447            }
448        }
449
450        // FADE OUT
451        for (std::list<SmartPtr<AmbientSound> >::iterator it = this->fadeOutList_.begin(); it != this->fadeOutList_.end(); )
452        {
453            if ((*it)->getVolume() - this->crossFadeStep_*dt < 0.0f)
454            {
455                (*it)->setVolume(0.0f);
456
457                // If sound is in the ambient list --> pause
458                for (AmbientList::const_iterator it2 = this->ambientSounds_.begin(); it2 != this->ambientSounds_.end(); ++it2)
459                {
460                    if (it2->first == *it)
461                    {
462                        (*it)->doPause();
463                        break;
464                    }
465                }
466                // If not pause (by loop above for instance) --> stop
467                if (!(*it)->isPaused())
468                    (*it)->doStop();
469
470                this->fadeOutList_.erase(it++);
471            }
472            else
473            {
474                (*it)->setVolume((*it)->getVolume() - this->crossFadeStep_*dt);
475                ++it;
476            }
477        }
478    }
479
480    shared_ptr<SoundBuffer> SoundManager::getSoundBuffer(const std::string& filename)
481    {
482        shared_ptr<SoundBuffer> buffer;
483        // Check active or pooled buffers
484        SoundBufferMap::const_iterator it = this->soundBuffers_.find(filename);
485        if (it != this->soundBuffers_.end())
486        {
487            buffer = it->second;
488
489            // Remove from effects pool if not active used before
490            if (buffer->poolIterator_ != this->effectsPool_.end())
491            {
492                this->effectsPoolSize_ -= buffer->getSize();
493                this->effectsPool_.erase(buffer->poolIterator_);
494                buffer->poolIterator_ = this->effectsPool_.end();
495            }
496        }
497        else
498        {
499            try
500            {
501                buffer.reset(new SoundBuffer(filename, this->effectsPool_.end()));
502            }
503            catch (...)
504            {
505                COUT(1) << Exception::handleMessage() << std::endl;
506                return buffer;
507            }
508            this->soundBuffers_[filename] = buffer;
509        }
510        return buffer;
511    }
512
513    void SoundManager::releaseSoundBuffer(const shared_ptr<SoundBuffer>& buffer, bool bPoolBuffer)
514    {
515        // Check if others are still using the buffer
516        if (buffer.use_count() != 2)
517            return;
518        SoundBufferMap::iterator it = this->soundBuffers_.find(buffer->getFilename());
519        if (it != this->soundBuffers_.end())
520        {
521            if (bPoolBuffer)
522            {
523                // Pool already too large?
524                while (this->effectsPoolSize_ + it->second->getSize() > this->maxEffectsPoolSize_s && !this->effectsPool_.empty())
525                {
526                    shared_ptr<SoundBuffer> bufferDel = this->effectsPool_.back();
527                    this->effectsPoolSize_ -= bufferDel->getSize();
528                    bufferDel->poolIterator_ = this->effectsPool_.end();
529                    this->effectsPool_.pop_back();
530                    // Remove from buffer map too
531                    SoundBufferMap::iterator itDel = this->soundBuffers_.find(bufferDel->getFilename());
532                    if (itDel != this->soundBuffers_.end())
533                        this->soundBuffers_.erase(itDel);
534                }
535                // Put buffer into the pool
536                this->effectsPoolSize_ += it->second->getSize();
537                this->effectsPool_.push_front(it->second);
538                it->second->poolIterator_ = this->effectsPool_.begin();
539            }
540            else
541                this->soundBuffers_.erase(it);
542        }
543    }
544
545    ALuint SoundManager::getSoundSource(BaseSound* object)
546    {
547        if (!this->availableSoundSources_.empty())
548        {
549            ALuint source = this->availableSoundSources_.back();
550            this->availableSoundSources_.pop_back();
551            this->usedSoundSources_.push_back(std::make_pair(source, object));
552            return source;
553        }
554        else
555        {
556            if (this->usedSoundSources_.size() < this->maxSources_)
557            {
558                ALuint source;
559                alGenSources(1, &source);
560                // Try to create new sources (50% more, but at least one)
561                if (alIsSource(source) && !alGetError())
562                {
563                    this->usedSoundSources_.push_back(std::make_pair(source, object));
564                    return source;
565                }
566            }
567            // Return no source ID
568            ALuint source = 123456789;
569            while (alIsSource(++source));
570            return source;
571        }
572    }
573
574    void SoundManager::releaseSoundSource(ALuint source)
575    {
576#ifndef NDEBUG
577        for (std::vector<ALuint>::const_iterator it = this->availableSoundSources_.begin(); it != this->availableSoundSources_.end(); ++it)
578            assert((*it) != source);
579#endif
580        this->availableSoundSources_.push_back(source);
581        for (std::vector<std::pair<ALuint, BaseSound*> >::iterator it = this->usedSoundSources_.begin();
582            it != this->usedSoundSources_.end(); ++it)
583        {
584            if (it->first == source)
585            {
586                this->usedSoundSources_.erase(it);
587                break;
588            }
589        }
590        int used = std::max(this->usedSoundSources_.size(), this->minSources_);
591        // Subtract those we added in the statement above trough std::max
592        int available = (int)this->availableSoundSources_.size() - (used - (int)this->usedSoundSources_.size());
593        // Delete sources again to free resources if appropriate (more than 50% more available than used)
594        int toDelete = available - used / 2;
595        while (toDelete-- > 0)
596        {
597            alDeleteSources(1, &this->availableSoundSources_.back());
598            if (alGetError())
599                COUT(1) << "Sound Error: Failed to delete a source --> lost forever" << std::endl;
600            this->availableSoundSources_.pop_back();
601        }
602    }
603
604    unsigned int SoundManager::createSoundSources(unsigned int n)
605    {
606        unsigned int count = this->availableSoundSources_.size() + this->usedSoundSources_.size();
607        while (count < this->maxSources_ && count <= n)
608        {
609            ALuint source;
610            alGenSources(1, &source);
611            if (alIsSource(source) && !alGetError())
612                this->availableSoundSources_.push_back(source);
613            else
614                break;
615            ++count;
616        }
617        return count - this->availableSoundSources_.size() - this->usedSoundSources_.size();
618    }
619}
Note: See TracBrowser for help on using the repository browser.