Debian Codegraph @

src/io/sound.cpp

raw symbols SCIP
1
2 /**
3 *
4 * @file sound.cpp
5 *
6 * Part of the OpenJazz project
7 *
8 * @par History:
9 * - 23rd August 2005: Created sound.c
10 * - 3rd February 2009: Renamed sound.c to sound.cpp
11 *
12 * @par Licence:
13 * Copyright (c) 2005-2017 AJ Thomson
14 * Copyright (c) 2015-2026 Carsten Teibes
15 *
16 * OpenJazz is distributed under the terms of
17 * the GNU General Public License, version 2.0
18 *
19 * @par Description:
20 * Deals with the loading, playing and freeing of music and sound effects.
21 *
22 */
23
24
25 #include "file.h"
26 #include "sound.h"
27 #include "util.h"
28 #include "io/log.h"
29 #include "platforms/platforms.h"
30 #if OJ_SDL3
31 #include <SDL3/SDL_audio.h>
32 #else
33 #include <SDL_audio.h>
34 #endif
35 #include <psmplug.h>
36 #include <cassert>
37
38 // default configuration
39
40 #ifndef SOUND_FREQ
41 #define SOUND_FREQ 44100
42 #endif
43 #ifndef SOUND_SAMPLES
44 #define SOUND_SAMPLES 2048
45 #endif
46 #if MUSIC_SETTINGS == 0
47 // low
48 #define MUSIC_RESAMPLEMODE MODPLUG_RESAMPLE_LINEAR
49 #define MUSIC_FLAGS 0
50 #elif MUSIC_SETTINGS == 1
51 // mid
52 #define MUSIC_RESAMPLEMODE MODPLUG_RESAMPLE_LINEAR
53 #define MUSIC_FLAGS MODPLUG_ENABLE_MEGABASS
54 #else
55 // high
56 #define MUSIC_RESAMPLEMODE MODPLUG_RESAMPLE_FIR
57 #define MUSIC_FLAGS MODPLUG_ENABLE_NOISE_REDUCTION | MODPLUG_ENABLE_REVERB | MODPLUG_ENABLE_MEGABASS | MODPLUG_ENABLE_SURROUND
58 #endif
59
60 // Datatype
61
62 /// Raw sound effect data
63 typedef struct {
64 unsigned char *data;
65 char *name;
66 int length;
67 } RawSound;
68
69 /// Resampled sound effect data
70 typedef struct {
71 unsigned char *data;
72 int length;
73 int position;
74 } Sound;
75
76 namespace {
77
78 // Variables
79 RawSound *rawSounds = nullptr;
80 int nRawSounds = 0;
81 Sound sounds[SE::MAX] = {};
82 bool soundsLoaded = false;
83 ModPlugFile *musicFile = nullptr;
84 SDL_AudioSpec audioSpec = {};
85 bool musicPaused = false;
86 int musicVolume = MAX_VOLUME >> 1; // 50%
87 int soundVolume = MAX_VOLUME >> 2; // 25%
88 char *currentMusic = nullptr;
89 MusicTempo musicTempo = MusicTempo::NORMAL;
90
91 #if OJ_SDL3
92 SDL_AudioStream *audioStream = nullptr;
93 #elif OJ_SDL2
94 SDL_AudioDeviceID audioDevice = 0;
95 #endif
96
97 // Helpers
98
99 void LockAudio() {
100 #if OJ_SDL3
101 // not needed
102 //SDL_LockAudioStream();
103 #elif OJ_SDL2
104 SDL_LockAudioDevice(audioDevice);
105 #else
106 SDL_LockAudio();
107 #endif
108 }
109 void UnlockAudio() {
110 #if OJ_SDL3
111 // not needed
112 //SDL_UnlockAudioStream();
113 #elif OJ_SDL2
114 SDL_UnlockAudioDevice(audioDevice);
115 #else
116 SDL_UnlockAudio();
117 #endif
118 }
119 #if !OJ_SDL3 && !OJ_SDL2
120 int SDL_AUDIO_BITSIZE(int format) {
121 if (format == AUDIO_U8 || audioSpec.format == AUDIO_S8)
122 return 8;
123 else if (format == AUDIO_S16MSB || audioSpec.format == AUDIO_S16LSB ||
124 format == AUDIO_U16MSB || audioSpec.format == AUDIO_U16LSB)
125 return 16;
126
127 LOG_ERROR("Unsupported Audio format.");
128 return 0;
129 }
130 #endif
131
132 /**
133 * Callback used to provide data to the audio subsystem.
134 *
135 * @param userdata N/A
136 * @param stream Output stream
137 * @param len Length of data to be placed in the output stream
138 */
139 void audioCallback (void * /*userdata*/, unsigned char * stream, int len) {
140 // Clear audio buffer
141 memset(stream, '\0', len * sizeof(unsigned char));
142
143 if (musicFile && !musicPaused) {
144 // Read the next portion of music into the stream
145 ModPlug_Read(musicFile, stream, len);
146 }
147
148 if (!soundsLoaded) return;
149
150 for (int i = SE::NONE; i < SE::MAX; i++) {
151 if (!sounds[i].data || sounds[i].position < 0) continue;
152
153 int rest = sounds[i].length - sounds[i].position;
154 int length = 0;
155 int position = sounds[i].position;
156
157 if (len < rest) {
158 // Play as much of the clip as possible
159 length = len;
160 sounds[i].position += len;
161 } else {
162 // Play the remainder of the clip
163 length = rest;
164 sounds[i].position = -1;
165 }
166
167 // Add the next portion of the sound clip to the audio stream
168 #if OJ_SDL3
169 SDL_MixAudio(stream, sounds[i].data + position, audioSpec.format, length,
170 soundVolume / (float)MAX_VOLUME);
171 #elif OJ_SDL2
172 SDL_MixAudioFormat(stream, sounds[i].data + position, audioSpec.format,
173 length, soundVolume * SDL_MIX_MAXVOLUME / MAX_VOLUME);
174 #else
175 SDL_MixAudio(stream, sounds[i].data + position, length,
176 soundVolume * SDL_MIX_MAXVOLUME / MAX_VOLUME);
177 #endif
178 }
179 }
180
181 #if OJ_SDL3
182 void wrapperAudioCallback(void *userdata, SDL_AudioStream *stream, int additional_amount, int /* total_amount */) {
183 if (additional_amount > 0) {
184 Uint8 *data = SDL_stack_alloc(Uint8, additional_amount);
185 if (data) {
186 // call old function
187 audioCallback(userdata, data, additional_amount);
188 SDL_PutAudioStreamData(stream, data, additional_amount);
189 SDL_stack_free(data);
190 }
191 }
192 }
193 #endif
194 }
195
196 /**
197 * Initialise audio.
198 */
199 void openAudio () {
200 bool audioOk = false;
201
202 // Set up SDL audio
203 #if OJ_SDL3
204 audioSpec = { SDL_AUDIO_S16, 2, SOUND_FREQ };
205 audioStream = SDL_OpenAudioDeviceStream(SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK,
206 &audioSpec, wrapperAudioCallback, nullptr);
207 audioOk = (audioStream != nullptr);
208 #else
209 SDL_AudioSpec asDesired = {};
210 asDesired.freq = SOUND_FREQ;
211 asDesired.format = AUDIO_S16SYS;
212 asDesired.channels = 2;
213 asDesired.samples = SOUND_SAMPLES;
214 asDesired.callback = audioCallback;
215 asDesired.userdata = nullptr;
216
217 #if OJ_SDL2
218 audioDevice = SDL_OpenAudioDevice(nullptr, 0, &asDesired, &audioSpec,
219 SDL_AUDIO_ALLOW_ANY_CHANGE);
220
221 if(!audioDevice || SDL_AUDIO_ISFLOAT(audioSpec.format) ||
222 (SDL_AUDIO_BITSIZE(audioSpec.format) != 8 && SDL_AUDIO_BITSIZE(audioSpec.format) != 16)) {
223 LOG_DEBUG("SDL audio format unsupported, letting SDL convert it.");
224
225 if(audioDevice) SDL_CloseAudioDevice(audioDevice);
226
227 audioDevice = SDL_OpenAudioDevice(nullptr, 0, &asDesired, &audioSpec, 0);
228 }
229 audioOk = (audioDevice != 0);
230 #else
231 audioOk = (SDL_OpenAudio(&asDesired, &audioSpec) == 0);
232 #endif
233 #endif
234
235 if(!audioOk) {
236 LOG_ERROR("Unable to open audio: %s", SDL_GetError());
237 return;
238 }
239
240 #if OJ_SDL3
241 LOG_DEBUG("Opened %dHz Audio at %d bit, %d channels",
242 audioSpec.freq, SDL_AUDIO_BITSIZE(audioSpec.format), audioSpec.channels);
243 #else
244 LOG_DEBUG("Opened %dHz Audio at %d bit, %d channels with %d samples",
245 audioSpec.freq, SDL_AUDIO_BITSIZE(audioSpec.format), audioSpec.channels, audioSpec.samples);
246 #endif
247
248 // Load sounds
249 soundsLoaded = loadSounds("SOUNDS.000");
250
251 // Start audio for sfx to work
252 #if OJ_SDL3
253 SDL_ResumeAudioDevice(SDL_GetAudioStreamDevice(audioStream));
254 #elif OJ_SDL2
255 SDL_PauseAudioDevice(audioDevice, 0);
256 #else
257 SDL_PauseAudio(0);
258 #endif
259 }
260
261
262 /**
263 * Stop audio.
264 */
265 void closeAudio () {
266 stopMusic();
267
268 #if OJ_SDL3
269 SDL_CloseAudioDevice(SDL_GetAudioStreamDevice(audioStream));
270 SDL_DestroyAudioStream(audioStream);
271 #elif OJ_SDL2
272 SDL_CloseAudioDevice(audioDevice);
273 audioDevice = 0;
274 #else
275 SDL_CloseAudio();
276 #endif
277
278 if (rawSounds) {
279 for (int i = 0; i < nRawSounds; i++) {
280 delete[] rawSounds[i].data;
281 delete[] rawSounds[i].name;
282 }
283
284 delete[] rawSounds;
285 }
286
287 if (soundsLoaded) freeSounds();
288 }
289
290
291 /**
292 * Play music from the specified file.
293 *
294 * @param fileName Name of a file containing music data.
295 * @param restart Restart music when same file is played.
296 */
297 void playMusic (const char * fileName, bool restart) {
298 /* Only stop any existing music playing, if a different file
299 should be played or a restart has been requested. */
300 if ((currentMusic && (strcmp(fileName, currentMusic) == 0)) && !restart)
301 return;
302
303 stopMusic();
304
305 LockAudio();
306
307 // Load the music file
308 FilePtr file;
309 try {
310 file = std::make_unique<File>(fileName, PATH_TYPE_GAME);
311 } catch (int e) {
312 UnlockAudio();
313 return;
314 }
315
316 // Save current music filename
317 if (currentMusic) delete[] currentMusic;
318 currentMusic = createString(fileName);
319
320 // Find the size of the file
321 int size = file->getSize();
322
323 // Read the entire file into memory
324 file->seek(0, true);
325 unsigned char *psmData = file->loadBlock(size);
326
327 // Set up libpsmplug
328 ModPlug_Settings settings = {};
329 settings.mFlags = MUSIC_FLAGS;
330 settings.mChannels = audioSpec.channels;
331 settings.mBits = SDL_AUDIO_BITSIZE(audioSpec.format);
332 settings.mFrequency = audioSpec.freq;
333 settings.mResamplingMode = MUSIC_RESAMPLEMODE;
334 settings.mReverbDepth = 25;
335 settings.mReverbDelay = 40;
336 settings.mBassAmount = 50;
337 settings.mBassRange = 10;
338 settings.mSurroundDepth = 50;
339 settings.mSurroundDelay = 40;
340
341 // unlimited looping
342 settings.mLoopCount = -1;
343
344 ModPlug_SetSettings(&settings);
345
346 // Load the file into libmodplug
347 musicFile = ModPlug_Load(psmData, size);
348 delete[] psmData;
349
350 if (!musicFile) {
351 LOG_ERROR("Could not play music file: %s", fileName);
352 delete[] currentMusic;
353 currentMusic = nullptr;
354 }
355
356 // Re-apply volume setting
357 setMusicVolume(musicVolume);
358
359 // Start the audio playing
360 musicPaused = false;
361
362 UnlockAudio();
363 }
364
365
366 /**
367 * Pauses and Unpauses the current music.
368 *
369 * @param pause set to true to pause
370 */
371 void pauseMusic (bool pause) {
372 musicPaused = pause;
373 }
374
375
376 /**
377 * Stop the current music.
378 */
379 void stopMusic () {
380 // Stop the music playing
381 LockAudio();
382
383 if (musicFile) {
384 ModPlug_Unload(musicFile);
385 musicFile = nullptr;
386 }
387
388 // Cleanup
389 if (currentMusic) {
390 delete[] currentMusic;
391 currentMusic = nullptr;
392 }
393
394 UnlockAudio();
395 }
396
397
398 /**
399 * Gets the current music volume
400 *
401 * @return music volume (0-100)
402 */
403 int getMusicVolume () {
404 return musicVolume;
405 }
406
407
408 /**
409 * Sets the music volume
410 *
411 * @param volume new volume (0-100)
412 */
413 void setMusicVolume (int volume) {
414 musicVolume = CLAMP(volume, 0, MAX_VOLUME);
415
416 // do not access music player settings when not playing
417 if (!musicFile) return;
418
419 ModPlug_SetMasterVolume(musicFile, musicVolume * 2.56);
420 }
421
422
423 /**
424 * Gets the current music tempo
425 *
426 * @return music tempo (MUSIC_NORMAL, MUSIC_FAST)
427 */
428 MusicTempo getMusicTempo () {
429 return musicTempo;
430 }
431
432
433 /**
434 * Sets the music tempo
435 *
436 * @param tempo new tempo (MUSIC_NORMAL, MUSIC_FAST)
437 */
438 void setMusicTempo (MusicTempo tempo) {
439 musicTempo = tempo;
440
441 // do not access music player settings when not playing
442 if (!musicFile) return;
443
444 ModPlug_SetMusicTempoFactor(musicFile, static_cast<unsigned int>(tempo));
445 }
446
447
448 /**
449 * Load raw sound clips from the specified file.
450 *
451 * @param fileName Name of a file containing sound clips
452 */
453 bool loadSounds (const char *fileName) {
454 FilePtr file;
455
456 try {
457 file = std::make_unique<File>(fileName, PATH_TYPE_GAME);
458 } catch (int e) {
459 return false;
460 }
461
462 // Checking sound file header
463 char *identifier1 = file->loadString(3);
464 char identifier2 = file->loadChar();
465 if (strncmp(identifier1, "sfx", 2) != 0 || identifier2 != 0x1A) {
466 LOG_ERROR("Sound data not valid!");
467 delete[] identifier1;
468 return false;
469 }
470 delete[] identifier1;
471
472
473 // Locate the header data
474 file->seek(file->getSize() - 4, true);
475 int headerOffset = file->loadInt();
476
477 // Calculate number of sounds
478 nRawSounds = (file->getSize() - headerOffset) / 18;
479 LOG_TRACE("Loading %d sounds...", nRawSounds);
480
481 assert(nRawSounds < SE::MAX);
482
483 // Load sound clips
484 rawSounds = new RawSound[nRawSounds];
485
486 for (int i = 0; i < nRawSounds; i++) {
487
488 file->seek(headerOffset + (i * 18), true);
489
490 // Read the name of the clip
491 rawSounds[i].name = file->loadString(12);
492
493 // Read the offset of the clip
494 int offset = file->loadInt();
495
496 // Read the length of the clip
497 rawSounds[i].length = file->loadShort();
498
499 // Read the clip
500 file->seek(offset, true);
501 rawSounds[i].data = file->loadBlock(rawSounds[i].length);
502
503 }
504
505 resampleSounds();
506
507 return true;
508 }
509
510
511 /**
512 * Resample sound clip data.
513 */
514 void resampleSound (int index, const char* name, int rate) {
515 // Skip SE::NONE
516 int se = index + 1;
517
518 if(!isValidSoundIndex(static_cast<SE::Type>(se))) {
519 LOG_ERROR("Cannot resample Sound Index %d", se);
520 return;
521 }
522
523 // Empty names will just delete sounds
524 bool forDeletion = !strlen(name);
525
526 if (sounds[se].data) {
527 delete[] sounds[se].data;
528 sounds[se].data = nullptr;
529
530 if(forDeletion)
531 LOG_TRACE("Deleting Sound index %d", se);
532 else
533 LOG_TRACE("Overwriting Sound index %d: %s", se, name);
534 } else if(!forDeletion) {
535 LOG_MAX("Resampling Sound index %d: %s", se, name);
536 }
537
538 if (forDeletion)
539 return;
540
541 // Search for matching sound
542 for (int i = 0; i < nRawSounds; i++) {
543 if(strcmp(name, rawSounds[i].name) != 0) {
544 if (i == nRawSounds-1) {
545 LOG_WARN("Cannot find sound %s!", name);
546 return;
547 }
548 continue;
549 }
550
551 #if OJ_SDL2
552 // We let SDL2 resample as needed
553 SDL_AudioCVT cvt;
554 int res = SDL_BuildAudioCVT(&cvt, AUDIO_S8, 1, rate, audioSpec.format,
555 audioSpec.channels, audioSpec.freq);
556 if (res >= 0) {
557 cvt.len = rawSounds[i].length;
558 cvt.buf = new unsigned char[cvt.len * cvt.len_mult];
559 if(!cvt.buf) {
560 LOG_ERROR("Cannot create conversion buffer.");
561 return;
562 }
563 memcpy(cvt.buf, rawSounds[i].data, cvt.len);
564 sounds[se].length = cvt.len;
565 // only convert, if needed
566 if (res > 0) {
567 if((res = SDL_ConvertAudio(&cvt)) == 0) {
568 // successful
569 sounds[se].length = cvt.len_cvt;
570 }
571 }
572 }
573 if(res < 0) {
574 LOG_WARN("Cannot resample sound effect: %s", SDL_GetError());
575 return;
576 }
577 // From here it does not matter, if converted or already right samplerate
578 sounds[se].data = new unsigned char[sounds[se].length];
579 if(!sounds[se].data) {
580 LOG_ERROR("Cannot create buffer for resampled sound effect.");
581 return;
582 }
583 // Copy data over
584 memcpy(sounds[se].data, cvt.buf, sounds[se].length * sizeof(unsigned char));
585 delete[](cvt.buf);
586 #else
587 // Calculate the resampling factor
588 int rsFactor;
589 if (SDL_AUDIO_BITSIZE(audioSpec.format) == 8)
590 rsFactor = (F2 * audioSpec.freq) / rate;
591 else
592 rsFactor = (F4 * audioSpec.freq) / rate;
593
594 sounds[se].length = MUL(rawSounds[i].length, rsFactor);
595
596 // Allocate the buffer for the resampled clip
597 sounds[se].data = new unsigned char[sounds[se].length];
598 if(!sounds[se].data) {
599 LOG_ERROR("Cannot create buffer for resampled sound effect.");
600 return;
601 }
602
603 // Resample the clip
604 for (int sample = 0; sample < sounds[se].length; sample++)
605 sounds[se].data[sample] = rawSounds[i].data[DIV(sample, rsFactor)];
606 #endif
607 sounds[se].position = -1;
608
609 return;
610 }
611 }
612
613
614 /**
615 * Resample all sound clips to matching indices.
616 */
617 void resampleSounds() {
618 for (int i = 0; i < nRawSounds; i++) {
619 resampleSound(i, rawSounds[i].name, 11025);
620 }
621 }
622
623
624 /**
625 * Delete resampled sound clip data.
626 */
627 void freeSounds() {
628 if (!soundsLoaded) return;
629
630 for (int i = SE::NONE; i < SE::MAX; i++) {
631 if (sounds[i].data) delete[] sounds[i].data;
632 }
633 }
634
635
636 /**
637 * Set the sound clip to be played.
638 *
639 * @param index Number of the sound to play
640 */
641 void playSound(SE::Type index) {
642 // silently ignore
643 if (!soundsLoaded || index == SE::NONE) return;
644
645 // out of range
646 if (!isValidSoundIndex(index)) {
647 LOG_WARN("Cannot play invalid sound %d", index);
648 return;
649 }
650
651 // sound was deleted
652 if (!sounds[index].data) {
653 LOG_MAX("Cannot play empty sound %d", index);
654 return;
655 }
656
657 sounds[index].position = 0;
658 }
659
660
661 /**
662 * Check if a sound clip is playing.
663 *
664 * @param index Number of the sound to check
665 *
666 * @return Whether the sound is playing
667 */
668 bool isSoundPlaying (SE::Type index) {
669 if (!soundsLoaded || !isValidSoundIndex(index)) return false;
670
671 return (sounds[index].position > 0);
672 }
673
674
675 /**
676 * Gets the current sound effect volume
677 *
678 * @return sound volume (0-100)
679 */
680 int getSoundVolume () {
681 return soundVolume;
682 }
683
684
685 /**
686 * Sets the sound effect volume
687 *
688 * @param volume new volume (0-100)
689 */
690 void setSoundVolume (int volume) {
691 soundVolume = CLAMP(volume, 0, MAX_VOLUME);
692 }