fix music problems, is openal faster now?
[supertux.git] / src / audio / sound_manager.cpp
1 #include "sound_manager.hpp"
2
3 #include <stdexcept>
4 #include <iostream>
5 #include <sstream>
6 #include <memory>
7
8 #include "sound_file.hpp"
9 #include "sound_source.hpp"
10 #include "stream_sound_source.hpp"
11
12 SoundManager* sound_manager = 0;
13
14 SoundManager::SoundManager()
15   : device(0), context(0), sound_enabled(false), music_source(0),
16     music_enabled(true)
17 {
18   try {
19     device = alcOpenDevice(0);
20     if(device == 0) {
21       print_openal_version();
22       throw std::runtime_error("Couldn't open audio device.");
23     }
24
25     int attributes[] = { 0 };
26     context = alcCreateContext(device, attributes);
27     check_alc_error("Couldn't create audio context: ");
28     alcMakeContextCurrent(context);
29     check_alc_error("Couldn't select audio context: ");
30
31     check_al_error("Audio error after init: ");
32     sound_enabled = true;
33   } catch(std::exception& e) {
34     device = 0;
35     context = 0;
36     std::cerr << "Couldn't initialize audio device:" << e.what() << "\n";
37     print_openal_version();
38   }
39 }
40
41 SoundManager::~SoundManager()
42 {
43   delete music_source;
44
45   for(SoundSources::iterator i = sources.begin(); i != sources.end(); ++i) {
46     delete *i;
47   }
48
49   for(SoundBuffers::iterator i = buffers.begin(); i != buffers.end(); ++i) {
50     ALuint buffer = i->second;
51     alDeleteBuffers(1, &buffer);
52   }
53
54   if(context != 0) {
55     alcDestroyContext(context);
56   }
57   if(device != 0) {
58     alcCloseDevice(device);
59   }
60 }
61
62 ALuint
63 SoundManager::load_file_into_buffer(const std::string& filename)
64 {
65   // open sound file
66   std::auto_ptr<SoundFile> file (load_sound_file(filename));
67   
68   ALenum format = get_sample_format(file.get());
69   ALuint buffer;
70   alGenBuffers(1, &buffer);
71   check_al_error("Couldn't create audio buffer: ");
72   char* samples = new char[file->size];
73   try {
74     file->read(samples, file->size);
75     alBufferData(buffer, format, samples,
76         static_cast<ALsizei> (file->size),
77         static_cast<ALsizei> (file->rate));
78     check_al_error("Couldn't fill audio buffer: ");
79   } catch(...) {
80     delete[] samples;
81     throw;
82   }
83   delete[] samples;
84
85   return buffer;
86 }
87
88 SoundSource*
89 SoundManager::create_sound_source(const std::string& filename)
90 {
91   if(!sound_enabled)
92     return 0;
93
94   ALuint buffer;
95   
96   // reuse an existing static sound buffer            
97   SoundBuffers::iterator i = buffers.find(filename);
98   if(i != buffers.end()) {
99     buffer = i->second;
100   } else {
101     buffer = load_file_into_buffer(filename);
102     buffers.insert(std::make_pair(filename, buffer));
103   }
104   
105   SoundSource* source = new SoundSource();
106   alSourcei(source->source, AL_BUFFER, buffer);
107   return source;  
108 }
109
110 void
111 SoundManager::play(const std::string& filename, const Vector& pos)
112 {
113   try {
114     SoundSource* source = create_sound_source(filename);
115     if(source == 0)
116       return;
117     if(pos == Vector(-1, -1)) {
118       alSourcef(source->source, AL_ROLLOFF_FACTOR, 0);
119     } else {
120       source->set_position(pos);
121     }
122     source->play();
123     sources.push_back(source);
124   } catch(std::exception& e) {
125     std::cout << "Couldn't play sound " << filename << ": " << e.what() << "\n";
126   }
127 }
128
129 void
130 SoundManager::enable_sound(bool enable)
131 {
132   if(device == 0)
133     return;
134   sound_enabled = enable;
135 }
136
137 void
138 SoundManager::enable_music(bool enable)
139 {
140   if(device == 0)
141     return;
142   music_enabled = enable;
143   if(music_enabled) {
144     play_music(current_music);
145   } else {
146     if(music_source) {
147       delete music_source;
148       music_source = 0;
149     }
150   }
151 }
152
153 void
154 SoundManager::stop_music(bool fade)
155 {
156   if(fade) {
157     if(music_source
158         && music_source->get_fade_state() != StreamSoundSource::FadingOff)
159       music_source->set_fading(StreamSoundSource::FadingOff, .5f);
160   } else {
161     delete music_source;
162     music_source = 0;
163   }
164   current_music = "";
165 }
166
167 void
168 SoundManager::play_music(const std::string& filename, bool fade)
169 {
170   if(filename == current_music)
171     return;
172   current_music = filename;
173   if(!music_enabled)
174     return;
175
176   try {
177     std::auto_ptr<StreamSoundSource> newmusic (new StreamSoundSource());
178     alSourcef(newmusic->source, AL_ROLLOFF_FACTOR, 0);
179     newmusic->set_sound_file(load_sound_file(filename));
180     if(fade)
181       newmusic->set_fading(StreamSoundSource::FadingOn, .5f);
182     newmusic->play();
183
184     delete music_source;
185     music_source = newmusic.release();
186   } catch(std::exception& e) {
187     std::cerr << "Couldn't play music file '" << filename << "': "
188       << e.what() << "\n";
189   }
190 }
191
192 void
193 SoundManager::set_listener_position(const Vector& pos)
194 {
195   static Uint32 lastticks = SDL_GetTicks();
196
197   Uint32 current_ticks = SDL_GetTicks();
198   if(current_ticks - lastticks < 300)
199     return;
200   lastticks = current_ticks;                 
201
202   alListener3f(AL_POSITION, pos.x, pos.y, 0);
203 }
204
205 void
206 SoundManager::set_listener_velocity(const Vector& vel)
207 {
208   alListener3f(AL_VELOCITY, vel.x, vel.y, 0);
209 }
210
211 void
212 SoundManager::update()
213 {
214   static Uint32 lastticks = SDL_GetTicks();
215
216   Uint32 current_ticks = SDL_GetTicks();
217   if(current_ticks - lastticks < 300)
218     return;
219   lastticks = current_ticks;
220
221   // check for finished sound sources
222   for(SoundSources::iterator i = sources.begin(); i != sources.end(); ) {
223     SoundSource* source = *i;
224     if(!source->playing()) {
225       delete source;
226       i = sources.erase(i);
227     } else {
228       ++i;
229     }
230   }
231   // check streaming sounds
232   if(music_source) {
233     music_source->update();
234   }
235   
236   alcProcessContext(context);
237   check_alc_error("Error while processing audio context: ");
238 }
239
240 ALenum
241 SoundManager::get_sample_format(SoundFile* file)
242 {
243   if(file->channels == 2) {
244     if(file->bits_per_sample == 16) {
245       return AL_FORMAT_STEREO16;
246     } else if(file->bits_per_sample == 8) {
247       return AL_FORMAT_STEREO8;
248     } else {
249       throw std::runtime_error("Only 16 and 8 bit samples supported");
250     }
251   } else if(file->channels == 1) {
252     if(file->bits_per_sample == 16) {
253       return AL_FORMAT_MONO16;
254     } else if(file->bits_per_sample == 8) {
255       return AL_FORMAT_MONO8;
256     } else {
257       throw std::runtime_error("Only 16 and 8 bit samples supported");
258     }
259   }
260   
261   throw std::runtime_error("Only 1 and 2 channel samples supported");
262 }
263
264 void
265 SoundManager::print_openal_version()
266 {
267   std::cout << "OpenAL Vendor: " << alGetString(AL_VENDOR) << "\n"
268             << "OpenAL Version: " << alGetString(AL_VERSION) << "\n" 
269             << "OpenAL Renderer: " << alGetString(AL_RENDERER) << "\n"
270             << "OpenAl Extensions: " << alGetString(AL_RENDERER) << "\n";
271 }
272
273 void
274 SoundManager::check_alc_error(const char* message)
275 {
276   int err = alcGetError(device);
277   if(err != ALC_NO_ERROR) {
278     std::stringstream msg;
279     msg << message << alcGetString(device, err);
280     throw std::runtime_error(msg.str());
281   }                
282 }
283
284 void
285 SoundManager::check_al_error(const char* message)
286 {
287   int err = alGetError();
288   if(err != AL_NO_ERROR) {
289     std::stringstream msg;
290     msg << message << alGetString(err);
291     throw std::runtime_error(msg.str());
292   }  
293 }
294