File: sound.cpp

package info (click to toggle)
asc 2.1.0.0-1
  • links: PTS, VCS
  • area: main
  • in suites: lenny
  • size: 59,052 kB
  • ctags: 25,676
  • sloc: cpp: 145,189; sh: 8,705; ansic: 5,564; makefile: 551; perl: 150
file content (515 lines) | stat: -rw-r--r-- 13,235 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
/***************************************************************************
 *                                                                         *
 *   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.                                   *
 *                                                                         *
 ***************************************************************************/


#include <boost/regex.hpp>

#include <cstring>
#include <stdlib.h>


#include <SDL.h>
#include <SDL_mixer.h>
#include <SDL_sound.h>


#include "../global.h"

#include "sound.h"

#include "../basestrm.h"
#include "../music.h"
#include "../sgstream.h"

/** How long should this process sleep while waiting for a sound to play
 */
const int WAIT_SLEEP_MSEC = 50;



class SoundSystem_InternalData {
   public:
      Mix_Music *musicBuf;
      MusicPlayList* currentPlaylist;

      Sound* channel[MIX_CHANNELS];

      ASCString lastMusicMessage;

      SoundSystem_InternalData() : musicBuf(NULL), currentPlaylist(NULL) {
         for ( int i = 0; i < MIX_CHANNELS; ++i )
            channel[i] = NULL;

      };
};

SoundSystem* SoundSystem::instance = NULL;

SoundSystem  :: SoundSystem ( bool muteEffects, bool muteMusic, bool _off )
   : sdl_initialized(false), mix_initialized( false )
{
   internalData = new SoundSystem_InternalData;
   
   musicState = uninitialized;

   this->effectsMuted = muteEffects;
   this->off = _off;

   if ( instance )
      fatalError ( "Only one instance of SoundSystem possible !");

   instance = this;

   if( off )
      return;

   displayLogMessage(0,"Initializing sound device. If this hangs, run ASC without sound (asc -q)\n");
   displayLogMessage(0,"Step 1/3 (SDL_Init)...");

   if ( SDL_Init ( SDL_INIT_AUDIO ) < 0 ) {
      displayLogMessage(0,"failed, disabling sound\n");
      warning("Couldn't initialize SDL audio interface !");
      off = true;
      sdl_initialized = false;
      return;
   }

   displayLogMessage(0,"ok\nStep 2/3 (SDL_Sound Sound_Init)...");
   if (!Sound_Init()) {
      displayLogMessage(0,"failed, disabling sound\n");
      warning("Couldn't initialize SDL_sound !");
      off = true;
      sdl_initialized = false;
      return;
   }
   
   sdl_initialized = true;

   int audio_rate = MIX_DEFAULT_FREQUENCY;
   Uint16 audio_format = MIX_DEFAULT_FORMAT;
   int audio_channels = 2;

   displayLogMessage(0,"ok\nStep 3/3 (SDL_Mixer Mix_OpenAudio)...");
   if ( Mix_OpenAudio ( audio_rate, audio_format, audio_channels, 2048 ) < 0 ) {
      displayLogMessage(0,"failed, disabling sound\n");
      mix_initialized = false;
      warning("Couldn't initialize SDL_mixer !");
      off = true;
      return;
   } else {
      mix_initialized = true;
      if ( muteMusic )
         musicState = init_paused;
      else
         musicState = init_ready;

      Mix_QuerySpec(&audio_rate, &audio_format, &audio_channels);
      displayLogMessage ( 5, "Opened audio at %d Hz %d bit %s\n", audio_rate, (audio_format&0xFF), (audio_channels > 1) ? "stereo" : "mono");
      Mix_HookMusicFinished ( trackFinished );

      Mix_ChannelFinished( channelFinishedCallback );

      displayLogMessage(0,"ok\nSound system successfully initialized!\n");
   }
}


void SoundSystem::setEffectsMute ( bool mute )
{
   if ( off )
      return;

   if ( mute != this->effectsMuted ) {
      if ( mute ) {
         for ( int i = 0; i < MIX_CHANNELS; i++ )
            if ( Mix_Playing(i)  )
                Mix_HaltChannel( i );

      }
      this->effectsMuted = mute;
   }
}


void SoundSystem :: trackFinished( void )
{
   getInstance()->nextTrack();
}

ASCString SoundSystem :: getDiagnosticText()
{

   static ASCString boolean[2] = {"false", "true"};

   ASCString text = "Sound System Status: "; 

   if( off )
      text += "off\n";
   else
      text += "on\n";

   text += "Effects Muted: " + boolean[effectsMuted] + "\n";
   text += "SDL Initialized: " + boolean[sdl_initialized] + "\n";
   text += "Mixer Initialized: " + boolean[mix_initialized] + "\n";
   text += "Music Volume: " + ASCString::toString( musicVolume ) + "\n";
   text += "Effects Volume: " + ASCString::toString( effectVolume ) + "\n";

   text += "\n";
   text += "Last message from mixer was:\n";
   text += internalData->lastMusicMessage + "\n\n";

   if ( internalData->currentPlaylist ) 
      text += internalData->currentPlaylist->getDiagnosticText();
   else
      text += "No play list active!";

   return text;
}


void SoundSystem :: nextTrack( void )
{
   if ( off || musicState==paused || musicState==init_paused)
      return;

   if ( internalData->musicBuf ) {
      Mix_FreeMusic( internalData->musicBuf );
      internalData->musicBuf = NULL;
   }

   if ( internalData->currentPlaylist ) {
      ASCString filename = internalData->currentPlaylist->getNextTrack();
      
      if ( !filename.empty() ) {
        musicState = playing;
        internalData->musicBuf = Mix_LoadMUS( filename.c_str() );

        if ( !internalData->musicBuf ) {
           internalData->lastMusicMessage = "Could not load music file " + filename + " ; SDL reports error " + SDL_GetError();
           displayLogMessage ( 1, internalData->lastMusicMessage + "\n" );
           SDL_ClearError();
        } else {
           int chan = Mix_PlayMusic ( internalData->musicBuf, 1 );
           Mix_VolumeMusic ( musicVolume );
           displayLogMessage ( 4, "Playing music on channel %d \n", chan );
        }
     }
  } else
     displayLogMessage ( 1, "No play list available \n" );
}

void SoundSystem :: playMusic ( MusicPlayList* playlist )
{
   internalData->currentPlaylist = playlist;
   nextTrack();
}


void SoundSystem :: pauseMusic()
{
   if ( off )
      return;

   if ( musicState == playing ) {
      Mix_PauseMusic ();
      musicState = paused;
   }
}

void SoundSystem :: resumeMusic()
{
   if ( off )
      return;

   if ( musicState == init_ready || musicState == init_paused ) {
      if (musicState == init_paused)
         musicState = init_ready;
      nextTrack();
      return;
   }

   if ( musicState == paused ) {
      Mix_ResumeMusic ();
      musicState = playing;
   }
}

void SoundSystem :: resumePauseMusic()
{
   if ( musicState == playing )
      pauseMusic();
   else
      resumeMusic();
}

void SoundSystem :: setMusicVolume( int volume )
{
   musicVolume = volume * 128 / 100;

   if ( off )
      return;

   Mix_VolumeMusic ( musicVolume );
}

void SoundSystem :: setEffectVolume( int volume )
{
   effectVolume = volume * 128 / 100;

   if ( off )
      return;

   Mix_Volume ( -1, effectVolume );
}


SoundSystem::~SoundSystem()
{
   if ( !off ) {
      Mix_HaltMusic();

      if ( internalData->musicBuf ) {
         Mix_FreeMusic( internalData->musicBuf );
         internalData-> musicBuf = NULL;
      }
   }

   if( mix_initialized )
      Mix_CloseAudio();

   if( sdl_initialized )
      SDL_CloseAudio();

   delete internalData;

   instance = NULL;
}



void SoundSystem::channelFinishedCallback( int channelnum )
{
   if ( getInstance()->internalData->channel[channelnum] )
      getInstance()->internalData->channel[channelnum]->finishedSignal( channelnum );
}



pair<Sound_Sample*, Mix_Chunk*> loadWave ( const ASCString& name )
{
   Mix_Chunk* chunk  = NULL;
   Sound_Sample* sample  = NULL;
   
   if ( !exist ( name )) {
      errorMessage ( " can't open sound file: " + name );
      return make_pair(sample,chunk);
   }

   tnfilestream stream ( name, tnstream::reading );

   ASCString ext;
   boost::smatch what;
   static boost::regex extension( ".*\\.([^\\.]+)");
   if( boost::regex_match( name, what, extension))
      ext.assign( what[1].first, what[1].second );


   int frequency;
   Uint16 format;
   int channels;
   Mix_QuerySpec(&frequency, &format, &channels);
   Sound_AudioInfo ai;
   ai.format = format;
   ai.channels = channels;
   ai.rate = frequency;
   
   try {
      sample = Sound_NewSample ( SDL_RWFromStream ( &stream ), ext.c_str(), &ai, 1<<16);
      if ( sample )
         displayLogMessage ( 10, " SoundSystem::loadWave - sound " + name + " loaded successfully\n");
      else {
         displayLogMessage (0, ASCString(" SoundSystem::loadWave" ) + name + " failed. Message: " + Sound_GetError() + "\n");
         return make_pair(sample,chunk);
      }
   }
   catch ( tfileerror err ) {
      warning(" Error loading sound file " + name );
      sample = NULL;
      return make_pair(sample,chunk);
   }

   Uint32 size = Sound_DecodeAll ( sample );
   if ( sample->buffer_size <= 0 ) 
      warning( "decoding of file " + name + " failed");

   chunk = new Mix_Chunk;
   chunk->allocated = size;
   chunk->abuf = (Uint8*) sample->buffer;
   chunk->alen = size;
   chunk->volume = MIX_MAX_VOLUME;
   
   return make_pair(sample,chunk);
}


class Sound_InternalData {
   public:
     //! the actual wave data
      Mix_Chunk *mainwave;
      Mix_Chunk *startwave;
      Sound_Sample *mainsample;
      Sound_Sample *startsample;
      Sound_InternalData() : mainwave(NULL), startwave(NULL), mainsample(NULL), startsample(NULL) {};
};

Sound::Sound( const ASCString& filename, int _fadeIn ) : name ( filename ), fadeIn ( _fadeIn ), waitingForMainWave(false)
{
   internalData = new Sound_InternalData;
   
   if ( !SoundSystem::instance )
      fatalError ( "Sound::Sound failed, because there is no SoundSystem initialized");

   pair<Sound_Sample*, Mix_Chunk*> res = loadWave( filename );
   internalData->mainsample = res.first;
   internalData->mainwave = res.second;
}

Sound::Sound( const ASCString& startSoundFilename, const ASCString& continuousSoundFilename, int _fadeIn ) : name ( startSoundFilename ), fadeIn ( _fadeIn ), waitingForMainWave(false)
{
   internalData = new Sound_InternalData;
   
   if ( !SoundSystem::instance )
      fatalError ( "Sound::Sound failed, because there is no SoundSystem initialized");

   pair<Sound_Sample*, Mix_Chunk*> res = loadWave( startSoundFilename );
   internalData->startsample = res.first;
   internalData->startwave = res.second;
   
   res = loadWave( continuousSoundFilename );
   internalData->mainsample = res.first;
   internalData->mainwave = res.second;
}




int Sound::startPlaying( bool loop )
{
   int channel;

   int loopcontrol;
   if ( loop ) 
      loopcontrol = -1;
   else
      loopcontrol = 0;

   Mix_Chunk* wave  = internalData->startwave;
   if ( !wave ) 
      wave = internalData->mainwave;
   else
      loopcontrol = 0;

   if ( fadeIn )
      channel = Mix_FadeInChannel ( -1, wave, loopcontrol, fadeIn );
   else {
      channel = Mix_PlayChannel ( -1, wave, loopcontrol );
      Mix_Volume ( channel, SoundSystem::instance->getEffectVolume() );
   }
   if ( internalData->startwave ) {
      waitingForMainWave = true;
   }

   return channel;
}

void Sound::finishedSignal( int channelnum )
{
   if ( waitingForMainWave ) {
      Mix_PlayChannel ( channelnum, internalData->mainwave, -1 );
      Mix_Volume ( channelnum, SoundSystem::instance->getEffectVolume() );
      waitingForMainWave = false;
   }
}

void Sound::play(void)
{
   if( SoundSystem::instance->areEffectsMuted() || !internalData->mainwave)
      return;

   int channel = startPlaying( false );
   SoundSystem::instance->internalData->channel[ channel ] = this;
}

void Sound::playLoop()
{
   if( SoundSystem::instance->areEffectsMuted() || !internalData->mainwave)
      return;

   int channel = startPlaying( true );
   SoundSystem::instance->internalData->channel[ channel ] = this;
}

void Sound::stop()
{
   for ( int i = 0; i < MIX_CHANNELS; i++ )
      if ( SoundSystem::instance->internalData->channel[ i ] == this  && Mix_Playing(i)  )
          Mix_HaltChannel( i );
}


void Sound::playWait(void)
{
   if( SoundSystem::instance->areEffectsMuted() || !internalData->mainwave)
      return;

   if ( internalData->startwave ) {
      int channel = Mix_PlayChannel ( -1, internalData->startwave, 0 );
      SoundSystem::instance->internalData->channel[ channel ] = this;
      do {
         SDL_Delay(WAIT_SLEEP_MSEC);
      } while( SoundSystem::instance->internalData->channel[ channel ] == this  && Mix_Playing(channel)  );
   }

   int channel = Mix_PlayChannel ( -1, internalData->mainwave, 0 );
   SoundSystem::instance->internalData->channel[ channel ] = this;

   do {
      SDL_Delay(WAIT_SLEEP_MSEC);
   } while( SoundSystem::instance->internalData->channel[ channel ] == this  && Mix_Playing(channel)  );
}

void Sound :: fadeOut ( int ms )
{
   for ( int i = 0; i < MIX_CHANNELS; i++ )
      if ( SoundSystem::instance->internalData->channel[ i ] == this  && Mix_Playing(i)  )
          Mix_FadeOutChannel( i, ms );
}



Sound::~Sound(void)
{
   stop();

   if ( internalData->mainwave )
      delete internalData->mainwave ;

   if ( internalData->startwave )
      delete internalData->startwave;

   if ( internalData->mainsample )
      Sound_FreeSample ( internalData->mainsample );

   if ( internalData->startsample )
      Sound_FreeSample ( internalData->startsample );

   delete internalData;
}