Fade out and pause music on death and resume on restart of level, fixes #1064
[supertux.git] / src / audio / sound_manager.cpp
index d0c547e..ace96c1 100644 (file)
@@ -1,12 +1,10 @@
-//  $Id: sound_manager.cpp 2334 2005-04-04 16:26:14Z grumbel $
+//  SuperTux
+//  Copyright (C) 2006 Matthias Braun <matze@braunis.de>
 //
-//  SuperTux -  A Jump'n Run
-//  Copyright (C) 2004 Matthias Braun <matze@braunis.de
-//
-//  This program is free software; you can redistribute it and/or
-//  modify it under the terms of the GNU General Public License
-//  as published by the Free Software Foundation; either version 2
-//  of the License, or (at your option) any later version.
+//  This program is free software: you can redistribute it and/or modify
+//  it under the terms of the GNU General Public License as published by
+//  the Free Software Foundation, either version 3 of the License, or
+//  (at your option) any later version.
 //
 //  This program is distributed in the hope that it will be useful,
 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
 //  GNU General Public License for more details.
 //
 //  You should have received a copy of the GNU General Public License
-//  along with this program; if not, write to the Free Software
-//  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
-#include <config.h>
+//  along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+#include "audio/sound_manager.hpp"
 
-#include <cmath>
-#include <cassert>
-#include <iostream>
+#include <SDL.h>
+#include <assert.h>
 #include <stdexcept>
 #include <sstream>
-
-#include "audio/sound_manager.h"
-
-#include "audio/musicref.h"
-#include "moving_object.h"
-#include "resources.h"
-
-SoundManager::SoundManager()
-  : current_music(0), m_music_enabled(true) , m_sound_enabled(true),
-    audio_device(false)
+#include <memory>
+
+#include "audio/dummy_sound_source.hpp"
+#include "audio/sound_file.hpp"
+#include "audio/stream_sound_source.hpp"
+#include "util/log.hpp"
+
+SoundManager::SoundManager() :
+  device(0),
+  context(0),
+  sound_enabled(false),
+  buffers(),
+  sources(),
+  update_list(),
+  music_source(),
+  music_enabled(false),
+  current_music()
 {
+  try {
+    device = alcOpenDevice(0);
+    if (device == NULL) {
+      throw std::runtime_error("Couldn't open audio device.");
+    }
+
+    int attributes[] = { 0 };
+    context = alcCreateContext(device, attributes);
+    check_alc_error("Couldn't create audio context: ");
+    alcMakeContextCurrent(context);
+    check_alc_error("Couldn't select audio context: ");
+
+    check_al_error("Audio error after init: ");
+    sound_enabled = true;
+    music_enabled = true;
+  } catch(std::exception& e) {
+    if(context != NULL) {
+      alcDestroyContext(context);
+      context = NULL;
+    }
+    if(device != NULL) {
+      alcCloseDevice(device);
+      device = NULL;
+    }
+    log_warning << "Couldn't initialize audio device: " << e.what() << std::endl;
+    print_openal_version();
+  }
 }
 
 SoundManager::~SoundManager()
 {
-  for(Sounds::iterator i = sounds.begin(); i != sounds.end(); ++i) {
-    Mix_FreeChunk(i->second);
+  music_source.reset();
+  sources.clear();
+
+  for(SoundBuffers::iterator i = buffers.begin(); i != buffers.end(); ++i) {
+    ALuint buffer = i->second;
+    alDeleteBuffers(1, &buffer);
+  }
+
+  if(context != NULL) {
+    alcDestroyContext(context);
+    context = NULL;
+  }
+  if(device != NULL) {
+    alcCloseDevice(device);
+    device = NULL;
   }
-  sounds.clear();
 }
 
-int
-SoundManager::play_sound(const std::string& name,int loops)
+ALuint
+SoundManager::load_file_into_buffer(SoundFile& file)
 {
-  if(!audio_device || !m_sound_enabled)
-    return -1;
-  
-  Mix_Chunk* chunk = preload_sound(name);
-  if(chunk == 0) {
-    std::cerr << "Sound '" << name << "' not found.\n";
-    return -1;
-  }
-  return Mix_PlayChannel(-1, chunk, loops);  
+  ALenum format = get_sample_format(file);
+  ALuint buffer;
+  alGenBuffers(1, &buffer);
+  check_al_error("Couldn't create audio buffer: ");
+  std::unique_ptr<char[]> samples(new char[file.size]);
+  file.read(samples.get(), file.size);
+  alBufferData(buffer, format, samples.get(),
+               static_cast<ALsizei>(file.size),
+               static_cast<ALsizei>(file.rate));
+  check_al_error("Couldn't fill audio buffer: ");
+
+  return buffer;
 }
 
+std::unique_ptr<OpenALSoundSource>
+SoundManager::intern_create_sound_source(const std::string& filename)
+{
+  assert(sound_enabled);
 
-void
-SoundManager::play_sound(const std::string& sound, const MovingObject* object,
-    const Vector& pos)
+  std::unique_ptr<OpenALSoundSource> source(new OpenALSoundSource);
+
+  ALuint buffer;
+
+  // reuse an existing static sound buffer
+  SoundBuffers::iterator i = buffers.find(filename);
+  if(i != buffers.end()) {
+    buffer = i->second;
+  } else {
+    // Load sound file
+    std::unique_ptr<SoundFile> file(load_sound_file(filename));
+
+    if(file->size < 100000) {
+      buffer = load_file_into_buffer(*file);
+      buffers.insert(std::make_pair(filename, buffer));
+    } else {
+      std::unique_ptr<StreamSoundSource> source_(new StreamSoundSource);
+      source_->set_sound_file(std::move(file));
+      return std::move(source_);
+    }
+
+    log_debug << "Uncached sound \"" << filename << "\" requested to be played" << std::endl;
+  }
+
+  alSourcei(source->source, AL_BUFFER, buffer);
+  return std::move(source);
+}
+
+std::unique_ptr<SoundSource>
+SoundManager::create_sound_source(const std::string& filename)
 {
-  // TODO keep track of the object later and move the sound along with the
-  // object.
-  play_sound(sound, object->get_pos(), pos);
+  if(!sound_enabled)
+    return create_dummy_sound_source();
+
+  try {
+    return intern_create_sound_source(filename);
+  } catch(std::exception &e) {
+    log_warning << "Couldn't create audio source: " << e.what() << std::endl;
+    return create_dummy_sound_source();
+  }
 }
 
 void
-SoundManager::play_sound(const std::string& sound, const Vector& pos,
-    const Vector& pos2)
+SoundManager::preload(const std::string& filename)
 {
-  if(!audio_device || !m_sound_enabled)
+  if(!sound_enabled)
     return;
 
-  Mix_Chunk* chunk = preload_sound(sound);
-  if(chunk == 0) {
-    std::cerr << "Sound '" << sound << "' not found.\n";
-    return;                                              
+  SoundBuffers::iterator i = buffers.find(filename);
+  // already loaded?
+  if(i != buffers.end())
+    return;
+  try {
+    std::unique_ptr<SoundFile> file (load_sound_file(filename));
+    // only keep small files
+    if(file->size >= 100000)
+      return;
+
+    ALuint buffer = load_file_into_buffer(*file);
+    buffers.insert(std::make_pair(filename, buffer));
+  } catch(std::exception& e) {
+    log_warning << "Error while preloading sound file: " << e.what() << std::endl;
   }
+}
 
-  // TODO make sure this formula is good
-  float distance 
-    = pos2.x- pos.x;
-  int loud = int(255.0/float(1600) * fabsf(distance));
-  if(loud > 255)
+void
+SoundManager::play(const std::string& filename, const Vector& pos)
+{
+  if(!sound_enabled)
     return;
 
-  int chan = Mix_PlayChannel(-1, chunk, 0);
-  if(chan < 0)
-    return;                                  
-  Mix_SetDistance(chan, loud);
-
-  // very bad way to do this...
-  if(distance > 100)
-    Mix_SetPanning(chan, 230, 24);
-  else if(distance < -100)
-    Mix_SetPanning(chan, 24, 230);
+  try {
+    std::unique_ptr<OpenALSoundSource> source(intern_create_sound_source(filename));
+
+    if(pos.x < 0 || pos.y < 0) {
+      source->set_relative(true);
+    } else {
+      source->set_position(pos);
+    }
+    source->play();
+    sources.push_back(std::move(source));
+  } catch(std::exception& e) {
+    log_warning << "Couldn't play sound " << filename << ": " << e.what() << std::endl;
+  }
 }
 
-/*
-
-ok, i was stupid. We won't need this now.
-
-// Register a sound effect function - basti_
-
-void 
-SoundManager::register_effect(int channel,Mix_EffectFunc_t f,
-                             Mix_EffectDone_t d,void * arg) {
+void
+SoundManager::manage_source(std::unique_ptr<SoundSource> source)
+{
+  assert(source);
+  if (dynamic_cast<OpenALSoundSource*>(source.get()))
+  {
+    std::unique_ptr<OpenALSoundSource> openal_source(dynamic_cast<OpenALSoundSource*>(source.release()));
+    sources.push_back(std::move(openal_source));
+  }
+}
 
-  if(!audio_device || !m_sound_enabled)
-    return;
-  Mix_RegisterEffect(channel,f,d,arg);
+void
+SoundManager::register_for_update(StreamSoundSource* sss)
+{
+  if (sss)
+  {
+    update_list.push_back(sss);
+  }
 }
 
-// Adjust the Volume of a channel "on line". Needs sizeof(float) static data.
+void
+SoundManager::remove_from_update(StreamSoundSource* sss)
+{
+  if (sss)
+  {
+    StreamSoundSources::iterator i = update_list.begin();
+    while( i != update_list.end() ){
+      if( *i == sss ){
+        i = update_list.erase(i);
+      } else {
+        ++i;
+      }
+    }
+  }
+}
 
-void 
-SoundManager::volume_adjust(int chan, void *stream, int len, void *udata) {
+void
+SoundManager::enable_sound(bool enable)
+{
+  if(device == NULL)
+    return;
 
-  typedef signed short int atype;
+  sound_enabled = enable;
+}
 
-  ((float *)udata)[1]=((float *)udata)[1]*0.95+
-    (((float *)udata)[0]-
-     ((float *)udata)[1])*0.05; // decay towards [0] - declick
-  float vol=((float*)udata)[1];
+void
+SoundManager::enable_music(bool enable)
+{
+  if(device == NULL)
+    return;
 
-  for (int i=0;i<len/2;i++)
-    ((atype *)stream)[i]=
-      ((atype)(((atype *)stream)[i]*vol)); 
-  // FIXME: This should be audio-type dependant - how to do this correctly?
-  
-  chan=0; // -Werror sucks
+  music_enabled = enable;
+  if(music_enabled) {
+    play_music(current_music);
+  } else {
+    if(music_source) {
+      music_source.reset();
+    }
+  }
 }
-*/
 
+void
+SoundManager::stop_music(float fadetime)
+{
+  if(fadetime > 0) {
+    if(music_source
+       && music_source->get_fade_state() != StreamSoundSource::FadingOff)
+      music_source->set_fading(StreamSoundSource::FadingOff, fadetime);
+  } else {
+    music_source.reset();
+  }
+  current_music = "";
+}
 
-MusicRef
-SoundManager::load_music(const std::string& file)
+void
+SoundManager::play_music(const std::string& filename, bool fade)
 {
-  if(!audio_device)
-    return MusicRef(0);
+  if(filename == current_music && music_source != NULL)
+    return;
+  current_music = filename;
+  if(!music_enabled)
+    return;
 
-  if(!exists_music(file)) {
-    std::stringstream msg;
-    msg << "Couldn't load musicfile '" << file << "': " << SDL_GetError();
-    throw std::runtime_error(msg.str());
+  if(filename == "") {
+    music_source.reset();
+    return;
   }
 
-  std::map<std::string, MusicResource>::iterator i = musics.find(file);
-  assert(i != musics.end());
-  return MusicRef(& (i->second));
+  try {
+    std::unique_ptr<StreamSoundSource> newmusic (new StreamSoundSource());
+    newmusic->set_sound_file(load_sound_file(filename));
+    newmusic->set_looping(true);
+    newmusic->set_relative(true);
+    if(fade)
+      newmusic->set_fading(StreamSoundSource::FadingOn, .5f);
+    newmusic->play();
+
+    music_source = std::move(newmusic);
+  } catch(std::exception& e) {
+    log_warning << "Couldn't play music file '" << filename << "': " << e.what() << std::endl;
+    // When this happens, previous music continued playing, stop it, just in case.
+    stop_music(0);
+  }
 }
 
-bool
-SoundManager::exists_music(const std::string& file)
+void
+SoundManager::pause_music(float fadetime)
 {
-  if(!audio_device)
-    return true;
-  
-  // song already loaded?
-  std::map<std::string, MusicResource>::iterator i = musics.find(file);
-  if(i != musics.end()) {
-    return true;                                      
+  if(fadetime > 0) {
+    if(music_source
+       && music_source->get_fade_state() != StreamSoundSource::FadingPause)
+      music_source->set_fading(StreamSoundSource::FadingPause, fadetime);
+  } else {
+    music_source->pause();
   }
-  
-  Mix_Music* song = Mix_LoadMUS(file.c_str());
-  if(song == 0)
-    return false;
-
-  // insert into music list
-  std::pair<std::map<std::string, MusicResource>::iterator, bool> result = 
-    musics.insert(
-        std::make_pair<std::string, MusicResource> (file, MusicResource()));
-  MusicResource& resource = result.first->second;
-  resource.manager = this;
-  resource.music = song;
-
-  return true;
 }
 
 void
-SoundManager::free_music(MusicResource* )
+SoundManager::resume_music(float fadetime)
 {
-  // TODO free music, currently we can't do this since SDL_mixer seems to have
-  // some bugs if you load/free alot of mod files.  
+  if(fadetime > 0) {
+    if(music_source
+       && music_source->get_fade_state() != StreamSoundSource::FadingResume)
+      music_source->set_fading(StreamSoundSource::FadingResume, fadetime);
+  } else {
+    music_source->resume();
+  }
 }
 
 void
-SoundManager::play_music(const MusicRef& musicref, int loops)
+SoundManager::set_listener_position(const Vector& pos)
 {
-  if(!audio_device)
-    return;
+  static Uint32 lastticks = SDL_GetTicks();
 
-  if(musicref.music == 0 || current_music == musicref.music)
+  Uint32 current_ticks = SDL_GetTicks();
+  if(current_ticks - lastticks < 300)
     return;
+  lastticks = current_ticks;
 
-  if(current_music)
-    current_music->refcount--;
-  
-  current_music = musicref.music;
-  current_music->refcount++;
-  
-  if(m_music_enabled)
-    Mix_PlayMusic(current_music->music, loops);
+  alListener3f(AL_POSITION, pos.x, pos.y, 0);
 }
 
 void
-SoundManager::halt_music()
+SoundManager::set_listener_velocity(const Vector& vel)
 {
-  if(!audio_device)
-    return;
-  
-  Mix_HaltMusic();
-  
-  if(current_music) {
-    current_music->refcount--;
-    if(current_music->refcount == 0)
-      free_music(current_music);
-    current_music = 0;
-  }
+  alListener3f(AL_VELOCITY, vel.x, vel.y, 0);
 }
 
 void
-SoundManager::enable_music(bool enable)
+SoundManager::update()
 {
-  if(!audio_device)
-    return;
+  static Uint32 lasttime = SDL_GetTicks();
+  Uint32 now = SDL_GetTicks();
 
-  if(enable == m_music_enabled)
+  if(now - lasttime < 300)
     return;
-  
-  m_music_enabled = enable;
-  if(m_music_enabled == false) {
-    Mix_HaltMusic();
-  } else {
-    if(current_music)
-      Mix_PlayMusic(current_music->music, -1);
+  lasttime = now;
+
+  // update and check for finished sound sources
+  for(SoundSources::iterator i = sources.begin(); i != sources.end(); ) {
+    auto& source = *i;
+
+    source->update();
+
+    if(!source->playing()) {
+      i = sources.erase(i);
+    } else {
+      ++i;
+    }
+  }
+  // check streaming sounds
+  if(music_source) {
+    music_source->update();
+  }
+
+  if (context)
+  {
+    alcProcessContext(context);
+    check_alc_error("Error while processing audio context: ");
+  }
+
+  //run update() for stream_sound_source
+  StreamSoundSources::iterator s = update_list.begin();
+  while( s != update_list.end() ){
+    (*s)->update();
+    ++s;
   }
 }
 
-void
-SoundManager::enable_sound(bool enable)
+ALenum
+SoundManager::get_sample_format(const SoundFile& file)
 {
-  if(!audio_device)
-    return;
-  
-  m_sound_enabled = enable;
+  if(file.channels == 2) {
+    if(file.bits_per_sample == 16) {
+      return AL_FORMAT_STEREO16;
+    } else if(file.bits_per_sample == 8) {
+      return AL_FORMAT_STEREO8;
+    } else {
+      throw std::runtime_error("Only 16 and 8 bit samples supported");
+    }
+  } else if(file.channels == 1) {
+    if(file.bits_per_sample == 16) {
+      return AL_FORMAT_MONO16;
+    } else if(file.bits_per_sample == 8) {
+      return AL_FORMAT_MONO8;
+    } else {
+      throw std::runtime_error("Only 16 and 8 bit samples supported");
+    }
+  }
+
+  throw std::runtime_error("Only 1 and 2 channel samples supported");
 }
 
-SoundManager::MusicResource::~MusicResource()
+void
+SoundManager::print_openal_version()
 {
-  // don't free music buggy SDL_Mixer crashs for some mod files
-  // Mix_FreeMusic(music);
+  log_info << "OpenAL Vendor: " << alGetString(AL_VENDOR) << std::endl;
+  log_info << "OpenAL Version: " << alGetString(AL_VERSION) << std::endl;
+  log_info << "OpenAL Renderer: " << alGetString(AL_RENDERER) << std::endl;
+  log_info << "OpenAl Extensions: " << alGetString(AL_EXTENSIONS) << std::endl;
 }
 
-Mix_Chunk* SoundManager::preload_sound(const std::string& name)
+void
+SoundManager::check_alc_error(const char* message)
 {
-  if(!audio_device)
-    return 0;
-
-  Sounds::iterator i = sounds.find(name);
-  if(i != sounds.end()) {
-    return i->second;
+  int err = alcGetError(device);
+  if(err != ALC_NO_ERROR) {
+    std::stringstream msg;
+    msg << message << alcGetString(device, err);
+    throw std::runtime_error(msg.str());
   }
+}
 
-  std::string filename = "sounds/";
-  filename += name;
-  filename += ".wav";
-  filename = get_resource_filename(filename);
-  
-  Mix_Chunk* chunk = Mix_LoadWAV(filename.c_str());
-  if(chunk != 0) {
-    sounds.insert(std::make_pair(name, chunk));
+void
+SoundManager::check_al_error(const char* message)
+{
+  int err = alGetError();
+  if(err != AL_NO_ERROR) {
+    std::stringstream msg;
+    msg << message << alGetString(err);
+    throw std::runtime_error(msg.str());
   }
-
-  return chunk;
 }
 
+/* EOF */