Debian Codegraph @

src/engine/audio.cpp

raw symbols SCIP
1 /***************************************************************************
2 * fheroes2: https://github.com/ihhub/fheroes2 *
3 * Copyright (C) 2019 - 2025 *
4 * *
5 * Free Heroes2 Engine: http://sourceforge.net/projects/fheroes2 *
6 * Copyright (C) 2008 by Andrey Afletdinov <[email protected]> *
7 * *
8 * This program is free software; you can redistribute it and/or modify *
9 * it under the terms of the GNU General Public License as published by *
10 * the Free Software Foundation; either version 2 of the License, or *
11 * (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 *
20 * Free Software Foundation, Inc., *
21 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
22 ***************************************************************************/
23
24 #include "audio.h"
25
26 #include <algorithm>
27 #include <atomic>
28 #include <cassert>
29 #include <cmath>
30 #include <list>
31 #include <map>
32 #include <memory>
33 #include <mutex>
34 #include <ostream>
35 #include <utility>
36 #include <variant>
37
38 // Managing compiler warnings for SDL headers
39 #if defined( __GNUC__ )
40 #pragma GCC diagnostic push
41
42 #pragma GCC diagnostic ignored "-Wdouble-promotion"
43 #pragma GCC diagnostic ignored "-Wold-style-cast"
44 #pragma GCC diagnostic ignored "-Wswitch-default"
45 #endif
46
47 #include <SDL_audio.h>
48 #include <SDL_error.h>
49 #include <SDL_mixer.h>
50 #include <SDL_rwops.h>
51 #include <SDL_stdinc.h>
52
53 // Managing compiler warnings for SDL headers
54 #if defined( __GNUC__ )
55 #pragma GCC diagnostic pop
56 #endif
57
58 #include "core.h"
59 #include "dir.h"
60 #include "logging.h"
61 #include "system.h"
62 #include "thread.h"
63 #include "timing.h"
64
65 namespace
66 {
67 struct AudioSpec
68 {
69 #if defined( TARGET_PS_VITA )
70 // Notice: The PS Vita sound resampler is CPU intensive if the value is not 22050.
71 int frequency = 22050;
72 #else
73 // Notice: Value 22050 causes music distortion on Windows.
74 int frequency = 44100;
75 #endif
76 // Signed 16-bit samples with platform-dependent byte order
77 uint16_t format = AUDIO_S16SYS;
78 // Stereo audio support
79 int channels = 2;
80 #if defined( ANDROID ) || defined( __IPHONEOS__ )
81 // Value greater than 1024 causes audio distortion on Android and on iOS.
82 int chunkSize = 1024;
83 #elif defined( __EMSCRIPTEN__ )
84 // When a WebAssembly app is running in a browser, no background threads (emulated by the web workers) have
85 // access to the audio. The audio can only be accessed (and feeded) from the main thread (when yielding to
86 // the browser's event loop). The chunk size should be large enough to avoid playback issues caused by other
87 // activities performed on the main thread. On the other hand, it shouldn't be too big, because it is possible
88 // to stop the audio playback only after the current chunk has been completely played.
89 int chunkSize = 8192;
90 #else
91 int chunkSize = 2048;
92 #endif
93 };
94
95 std::atomic<bool> isInitialized{ false };
96
97 std::atomic<int> mixerChannelCount{ 0 };
98
99 bool isMuted{ false };
100 int savedMixerVolume{ 0 };
101 int savedMusicVolume{ 0 };
102
103 int musicFadeInMs{ 0 };
104
105 // This mutex protects all operations with audio. In order to avoid deadlocks, it shouldn't
106 // be acquired in any callback functions that can be called by SDL_Mixer.
107 std::recursive_mutex audioMutex;
108
109 class SoundSampleManager
110 {
111 public:
112 SoundSampleManager() = default;
113 SoundSampleManager( const SoundSampleManager & ) = delete;
114
115 ~SoundSampleManager()
116 {
117 // Make sure that all sound samples have been eventually freed
118 assert( std::all_of( _channelSamples.begin(), _channelSamples.end(), []( const auto & item ) {
119 static const decltype( item.second ) nullQueue{ nullptr, nullptr };
120
121 return item.second == nullQueue;
122 } ) );
123 }
124
125 SoundSampleManager & operator=( const SoundSampleManager & ) = delete;
126
127 void channelStarted( const int channelId, Mix_Chunk * sample )
128 {
129 assert( channelId >= 0 && sample != nullptr );
130
131 const auto iter = _channelSamples.find( channelId );
132
133 if ( iter != _channelSamples.end() ) {
134 auto & sampleQueue = iter->second;
135
136 if ( sampleQueue.first == nullptr ) {
137 sampleQueue.first = sample;
138 }
139 else if ( sampleQueue.second == nullptr ) {
140 sampleQueue.second = sample;
141 }
142 else {
143 // The sample queue is already full, this shouldn't happen
144 assert( 0 );
145 }
146
147 return;
148 }
149
150 const auto res = _channelSamples.try_emplace( channelId, std::make_pair( sample, nullptr ) );
151 if ( !res.second ) {
152 assert( 0 );
153 }
154 }
155
156 // This method can be called from the SDL_Mixer callback (without acquiring the audioMutex)
157 void channelFinished( const int channelId )
158 {
159 assert( channelId >= 0 );
160
161 const std::scoped_lock<std::mutex> lock( _channelsToCleanupMutex );
162
163 _channelsToCleanup.push_back( channelId );
164 }
165
166 void clearFinishedSamples()
167 {
168 std::vector<int> channelsToCleanup;
169
170 {
171 const std::scoped_lock<std::mutex> lock( _channelsToCleanupMutex );
172
173 std::swap( channelsToCleanup, _channelsToCleanup );
174 }
175
176 for ( const int channel : channelsToCleanup ) {
177 const auto iter = _channelSamples.find( channel );
178 assert( iter != _channelSamples.end() );
179
180 auto & sampleQueue = iter->second;
181 assert( sampleQueue.first != nullptr );
182
183 Mix_FreeChunk( sampleQueue.first );
184
185 // Shift the sample queue
186 sampleQueue.first = sampleQueue.second;
187 sampleQueue.second = nullptr;
188 }
189 }
190
191 private:
192 std::map<int, std::pair<Mix_Chunk *, Mix_Chunk *>> _channelSamples;
193
194 std::vector<int> _channelsToCleanup;
195 // This mutex protects operations with _channelsToCleanup
196 std::mutex _channelsToCleanupMutex;
197 };
198
199 SoundSampleManager soundSampleManager;
200
201 // This is the callback function set by Mix_ChannelFinished(). As a rule, it is called from
202 // a SDL_Mixer internal thread. Calls of any SDL_Mixer functions are not allowed in callbacks.
203 void SDLCALL channelFinished( const int channelId )
204 {
205 // This callback function should never be called if audio is not initialized
206 assert( isInitialized );
207
208 soundSampleManager.channelFinished( channelId );
209 }
210
211 class MusicInfo
212 {
213 public:
214 explicit MusicInfo( std::vector<uint8_t> v )
215 : _source( std::move( v ) )
216 {
217 // Do nothing
218 }
219
220 explicit MusicInfo( std::string file )
221 : _source( std::move( file ) )
222 {
223 // Do nothing
224 }
225
226 MusicInfo( const MusicInfo & ) = delete;
227
228 ~MusicInfo() = default;
229
230 MusicInfo & operator=( const MusicInfo & ) = delete;
231
232 // Mix_Music objects should never be cached because they store the state of the music decoder's backend,
233 // and should be passed to functions like Mix_PlayMusic() only once, otherwise weird things can happen.
234 std::unique_ptr<Mix_Music, void ( * )( Mix_Music * )> createMusic() const
235 {
236 if ( std::holds_alternative<std::vector<uint8_t>>( _source ) ) {
237 const std::vector<uint8_t> & v = std::get<std::vector<uint8_t>>( _source );
238
239 const std::unique_ptr<SDL_RWops, void ( * )( SDL_RWops * )> rwops( SDL_RWFromConstMem( v.data(), static_cast<int>( v.size() ) ), SDL_FreeRW );
240 if ( !rwops ) {
241 ERROR_LOG( "Failed to create a music track from memory. The error: " << SDL_GetError() )
242
243 return { nullptr, Mix_FreeMusic };
244 }
245
246 std::unique_ptr<Mix_Music, void ( * )( Mix_Music * )> result( Mix_LoadMUS_RW( rwops.get(), 0 ), Mix_FreeMusic );
247 if ( !result ) {
248 ERROR_LOG( "Failed to create a music track from memory. The error: " << Mix_GetError() )
249 }
250
251 return result;
252 }
253
254 if ( std::holds_alternative<std::string>( _source ) ) {
255 const std::string & file = std::get<std::string>( _source );
256
257 std::unique_ptr<Mix_Music, void ( * )( Mix_Music * )> result( Mix_LoadMUS( System::encLocalToUTF8( file ).c_str() ), Mix_FreeMusic );
258 if ( !result ) {
259 ERROR_LOG( "Failed to create a music track from file " << file << ". The error: " << Mix_GetError() )
260 }
261
262 return result;
263 }
264
265 assert( 0 );
266
267 return { nullptr, Mix_FreeMusic };
268 }
269
270 double getPosition() const
271 {
272 return _position;
273 }
274
275 void setPosition( const double pos )
276 {
277 _position = pos;
278 }
279
280 private:
281 const std::variant<std::vector<uint8_t>, std::string> _source;
282 double _position{ 0 };
283 };
284
285 class MusicTrackManager
286 {
287 public:
288 MusicTrackManager() = default;
289 MusicTrackManager( const MusicTrackManager & ) = delete;
290
291 ~MusicTrackManager()
292 {
293 // Make sure that all music tracks have been eventually freed
294 assert( _musicQueue == nullptr );
295 }
296
297 MusicTrackManager & operator=( const MusicTrackManager & ) = delete;
298
299 bool isTrackInMusicDB( const uint64_t musicUID ) const
300 {
301 return ( _musicDB.find( musicUID ) != _musicDB.end() );
302 }
303
304 std::shared_ptr<MusicInfo> getTrackFromMusicDB( const uint64_t musicUID ) const
305 {
306 const auto iter = _musicDB.find( musicUID );
307 assert( iter != _musicDB.end() );
308
309 return iter->second;
310 }
311
312 void addTrackToMusicDB( const uint64_t musicUID, const std::shared_ptr<MusicInfo> & track )
313 {
314 const auto res = _musicDB.try_emplace( musicUID, track );
315 if ( !res.second ) {
316 assert( 0 );
317 }
318 }
319
320 void clearMusicDB()
321 {
322 _musicDB.clear();
323 }
324
325 std::weak_ptr<MusicInfo> getCurrentTrack() const
326 {
327 return _currentTrack;
328 }
329
330 uint64_t getCurrentTrackUID() const
331 {
332 return _currentTrackUID;
333 }
334
335 Music::PlaybackMode getCurrentTrackPlaybackMode() const
336 {
337 return _currentTrackPlaybackMode;
338 }
339
340 bool isCurrentTrackBeingHalted() const
341 {
342 return _isCurrentTrackBeingHalted;
343 }
344
345 // This method can be called from the SDL_Mixer callback (without acquiring the audioMutex)
346 uint64_t getCurrentTrackChangeCounter() const
347 {
348 return _currentTrackChangeCounter;
349 }
350
351 double getCurrentTrackPosition() const
352 {
353 return _currentTrackTimer.getS();
354 }
355
356 void updateCurrentTrack( const uint64_t musicUID, const Music::PlaybackMode trackPlaybackMode )
357 {
358 _currentTrack = getTrackFromMusicDB( musicUID );
359
360 _currentTrackUID = musicUID;
361 _currentTrackPlaybackMode = trackPlaybackMode;
362 _isCurrentTrackBeingHalted = false;
363
364 ++_currentTrackChangeCounter;
365 }
366
367 void resetCurrentTrack()
368 {
369 _currentTrack = {};
370
371 _currentTrackUID = 0;
372 _currentTrackPlaybackMode = Music::PlaybackMode::PLAY_ONCE;
373 _isCurrentTrackBeingHalted = false;
374
375 ++_currentTrackChangeCounter;
376 }
377
378 void prepareToHaltCurrentTrack()
379 {
380 _isCurrentTrackBeingHalted = true;
381 }
382
383 void resetTimer()
384 {
385 _currentTrackTimer.reset();
386 }
387
388 void musicStarted( Mix_Music * mus )
389 {
390 // If the _musicQueue is not nullptr, then the music queue (consisting of only one music
391 // track) is already full, this shouldn't happen
392 assert( _musicQueue == nullptr );
393
394 _musicQueue = mus;
395 }
396
397 void clearFinishedMusic()
398 {
399 // This queue consists of only one music track
400 if ( _musicQueue == nullptr ) {
401 return;
402 }
403
404 Mix_FreeMusic( _musicQueue );
405
406 _musicQueue = nullptr;
407 }
408
409 private:
410 std::map<uint64_t, std::shared_ptr<MusicInfo>> _musicDB;
411
412 std::weak_ptr<MusicInfo> _currentTrack;
413
414 uint64_t _currentTrackUID{ 0 };
415 Music::PlaybackMode _currentTrackPlaybackMode{ Music::PlaybackMode::PLAY_ONCE };
416 bool _isCurrentTrackBeingHalted{ false };
417
418 // This counter should be incremented every time the current track or its playback mode changes
419 std::atomic<uint64_t> _currentTrackChangeCounter{ 0 };
420
421 fheroes2::Time _currentTrackTimer;
422
423 Mix_Music * _musicQueue{ nullptr };
424 };
425
426 MusicTrackManager musicTrackManager;
427
428 void playMusic( const uint64_t musicUID, Music::PlaybackMode playbackMode );
429
430 class MusicRestartManager final : public MultiThreading::AsyncManager
431 {
432 public:
433 void restartCurrentMusicTrack()
434 {
435 const std::scoped_lock<std::mutex> lock( _mutex );
436
437 _trackChangeCounter = musicTrackManager.getCurrentTrackChangeCounter();
438
439 notifyWorker();
440 }
441
442 private:
443 // This method is called by the worker thread and is protected by _mutex
444 bool prepareTask() override
445 {
446 // Make a copy for the worker thread to ensure that this counter will
447 // not be changed by another thread in the middle of executeTask()
448 _taskTrackChangeCounter = _trackChangeCounter;
449
450 return false;
451 }
452
453 // This method is called by the worker thread, but is not protected by _mutex
454 void executeTask() override
455 {
456 const std::scoped_lock<std::recursive_mutex> lock( audioMutex );
457
458 if ( !isInitialized ) {
459 return;
460 }
461
462 // The current track managed to change during the start of this task
463 if ( _taskTrackChangeCounter != musicTrackManager.getCurrentTrackChangeCounter() ) {
464 return;
465 }
466
467 // The current track has been intentionally halted and should not be restarted
468 if ( musicTrackManager.isCurrentTrackBeingHalted() ) {
469 return;
470 }
471
472 if ( musicTrackManager.getCurrentTrackPlaybackMode() == Music::PlaybackMode::PLAY_ONCE ) {
473 return;
474 }
475
476 const std::shared_ptr<MusicInfo> currentTrack = musicTrackManager.getCurrentTrack().lock();
477 assert( currentTrack );
478
479 currentTrack->setPosition( 0 );
480
481 playMusic( musicTrackManager.getCurrentTrackUID(), musicTrackManager.getCurrentTrackPlaybackMode() );
482 }
483
484 // This variable can be accessed by multiple threads and it is protected by _mutex
485 uint64_t _trackChangeCounter{ 0 };
486 // This variable can be accessed only by the worker thread
487 uint64_t _taskTrackChangeCounter{ 0 };
488 };
489
490 MusicRestartManager musicRestartManager;
491
492 // This is the callback function set by Mix_HookMusicFinished(). As a rule, it is called from
493 // a SDL_Mixer internal thread. Calls of any SDL_Mixer functions are not allowed in callbacks.
494 void SDLCALL musicFinished()
495 {
496 // This callback function should never be called if audio is not initialized
497 assert( isInitialized );
498
499 musicRestartManager.restartCurrentMusicTrack();
500 }
501
502 void playMusic( const uint64_t musicUID, const Music::PlaybackMode playbackMode )
503 {
504 // This function should never be called if a music track is currently playing.
505 // Thus we have a guarantee that the Mix_HookMusicFinished()'s callback will
506 // not be called while we are modifying the current track information.
507 assert( !Music::isPlaying() );
508
509 musicTrackManager.clearFinishedMusic();
510
511 const std::shared_ptr<MusicInfo> track = musicTrackManager.getTrackFromMusicDB( musicUID );
512 assert( track );
513
514 std::unique_ptr<Mix_Music, void ( * )( Mix_Music * )> mus = track->createMusic();
515 if ( !mus ) {
516 musicTrackManager.resetCurrentTrack();
517
518 return;
519 }
520
521 // Update the current track information while the music playback is not yet started, so the
522 // Mix_HookMusicFinished()'s callback cannot be called
523 musicTrackManager.updateCurrentTrack( musicUID, playbackMode );
524
525 int returnCode = -1;
526
527 // Resume the music only if at least 1 second of the track has been played.
528 if ( playbackMode == Music::PlaybackMode::RESUME_AND_PLAY_INFINITE && track->getPosition() > 1 ) {
529 returnCode = Mix_FadeInMusicPos( mus.get(), 0, musicFadeInMs, track->getPosition() );
530
531 if ( returnCode != 0 ) {
532 ERROR_LOG( "Failed to resume the music track. The error: " << Mix_GetError() )
533 }
534 }
535
536 // Either there is no need to resume music playback, or the resumption failed. Let's try to
537 // start the playback from the beginning.
538 if ( returnCode != 0 ) {
539 track->setPosition( 0 );
540
541 returnCode = Mix_FadeInMusic( mus.get(), 0, musicFadeInMs );
542
543 if ( returnCode != 0 ) {
544 ERROR_LOG( "Failed to play the music track. The error: " << Mix_GetError() )
545 }
546 }
547
548 if ( returnCode != 0 ) {
549 // Since the music playback failed, the Mix_HookMusicFinished()'s callback cannot be called
550 // here, so we can safely reset the current track information
551 musicTrackManager.resetCurrentTrack();
552
553 return;
554 }
555
556 // For better accuracy reset the timer right after the actual playback starts
557 musicTrackManager.resetTimer();
558
559 // There can be no more than one element in the music queue - the current track, the previous
560 // one should already be freed
561 musicTrackManager.musicStarted( mus.release() );
562 }
563
564 // By the Weber-Fechner law, humans subjective sound sensation is proportional logarithm of sound intensity.
565 // So for linear changing sound intensity we have to change the volume exponential.
566 // There is a good explanation at https://www.dr-lex.be/info-stuff/volumecontrols.html.
567 // This function maps sound volumes in percents to SDL units with values [0..MIX_MAX_VOLUME] by exponential law.
568 int normalizeToSDLVolume( const int volumePercentage )
569 {
570 if ( volumePercentage < 0 ) {
571 // Why are you passing a negative volume value?
572 assert( 0 );
573 return 0;
574 }
575
576 if ( volumePercentage >= 100 ) {
577 // Reserve an extra 0.5 dB for possible sound overloads in SDL_mixer, multiplying max volume by 50/53.
578 return MIX_MAX_VOLUME * 50 / 53;
579 }
580
581 // MIX_MAX_VOLUME is divided by 10.6, not 10 to reserve an extra 0.5 dB for possible sound overloads in SDL_mixer.
582 return static_cast<int>( ( std::exp( std::log( 10 + 1 ) * volumePercentage / 100 ) - 1 ) / 10.6 * MIX_MAX_VOLUME );
583 }
584
585 // Synchronizes the volume settings of all active mixer channels
586 void syncChannelsVolume()
587 {
588 if ( Mix_AllocateChannels( -1 ) < 2 ) {
589 return;
590 }
591
592 Mix_Volume( -1, Mix_Volume( 0, -1 ) );
593 }
594
595 #ifndef NDEBUG
596 // Checks whether the volume settings of all active mixer channels are synchronized
597 bool checkChannelsVolumeSync()
598 {
599 const int channelsCount = Mix_AllocateChannels( -1 );
600 if ( channelsCount < 2 ) {
601 return true;
602 }
603
604 const int vol = Mix_Volume( 0, -1 );
605
606 for ( int i = 1; i < channelsCount; ++i ) {
607 if ( Mix_Volume( i, -1 ) != vol ) {
608 return false;
609 }
610 }
611
612 return true;
613 }
614 #endif
615 }
616
617 void Audio::Init()
618 {
619 const std::scoped_lock<std::recursive_mutex> lock( audioMutex );
620
621 if ( isInitialized ) {
622 // If this assertion blows up you are trying to initialize an already initialized system.
623 assert( 0 );
624 return;
625 }
626
627 if ( !fheroes2::isComponentInitialized( fheroes2::SystemInitializationComponent::Audio ) ) {
628 ERROR_LOG( "The audio subsystem was not initialized." )
629 return;
630 }
631
632 const int initializationFlags = MIX_INIT_FLAC | MIX_INIT_MP3 | MIX_INIT_OGG | MIX_INIT_MID;
633 const int initializedFlags = Mix_Init( initializationFlags );
634 if ( ( initializedFlags & initializationFlags ) != initializationFlags ) {
635 DEBUG_LOG( DBG_ENGINE, DBG_WARN,
636 "Expected music initialization flags as " << initializationFlags << " but received " << ( initializedFlags & initializationFlags ) )
637
638 if ( ( initializedFlags & MIX_INIT_FLAC ) == 0 ) {
639 DEBUG_LOG( DBG_ENGINE, DBG_WARN, "FLAC module failed to be initialized" )
640 }
641
642 if ( ( initializedFlags & MIX_INIT_MP3 ) == 0 ) {
643 DEBUG_LOG( DBG_ENGINE, DBG_WARN, "MP3 module failed to be initialized" )
644 }
645
646 if ( ( initializedFlags & MIX_INIT_OGG ) == 0 ) {
647 DEBUG_LOG( DBG_ENGINE, DBG_WARN, "OGG module failed to be initialized" )
648 }
649
650 if ( ( initializedFlags & MIX_INIT_MID ) == 0 ) {
651 DEBUG_LOG( DBG_ENGINE, DBG_WARN, "MID module failed to be initialized" )
652 }
653 }
654
655 const AudioSpec audioSpec;
656
657 if ( Mix_OpenAudio( audioSpec.frequency, audioSpec.format, audioSpec.channels, audioSpec.chunkSize ) != 0 ) {
658 ERROR_LOG( "Failed to initialize an audio device. The error: " << Mix_GetError() )
659 return;
660 }
661
662 int frequency = 0;
663 uint16_t format = 0;
664 int channels = 0;
665
666 const int deviceInitCount = Mix_QuerySpec( &frequency, &format, &channels );
667 if ( deviceInitCount == 0 ) {
668 ERROR_LOG( "Failed to query an audio device specs. The error: " << Mix_GetError() )
669 }
670
671 if ( deviceInitCount != 1 ) {
672 // The device must be opened only once.
673 assert( 0 );
674 ERROR_LOG( "Trying to initialize an audio system that has been already initialized." )
675 }
676
677 if ( audioSpec.frequency != frequency ) {
678 // At least on Windows the standard frequency is 48000 Hz. Sounds in the game are 22500 Hz frequency.
679 // However, resampling is done inside SDL so this is not exactly an error.
680 DEBUG_LOG( DBG_ENGINE, DBG_WARN, "Audio frequency is initialized as " << frequency << " instead of " << audioSpec.frequency )
681 }
682
683 if ( audioSpec.format != format ) {
684 ERROR_LOG( "Audio format is initialized as " << format << " instead of " << audioSpec.format )
685 }
686
687 if ( audioSpec.channels != channels ) {
688 ERROR_LOG( "Number of audio channels is initialized as " << channels << " instead of " << audioSpec.channels )
689 }
690
691 // Make sure that all mixer channels have the same volume settings.
692 syncChannelsVolume();
693
694 // By default this value should be MIX_CHANNELS.
695 mixerChannelCount = Mix_AllocateChannels( -1 );
696
697 isMuted = false;
698 savedMixerVolume = 0;
699 savedMusicVolume = 0;
700
701 musicRestartManager.createWorker();
702
703 Mix_ChannelFinished( channelFinished );
704 Mix_HookMusicFinished( musicFinished );
705
706 isInitialized = true;
707 }
708
709 void Audio::Quit()
710 {
711 {
712 const std::scoped_lock<std::recursive_mutex> lock( audioMutex );
713
714 if ( !isInitialized ) {
715 // Nothing to do.
716 return;
717 }
718
719 if ( !fheroes2::isComponentInitialized( fheroes2::SystemInitializationComponent::Audio ) ) {
720 // Something wrong with the logic! The component must be initialized.
721 assert( 0 );
722 return;
723 }
724
725 Music::Stop();
726 Mixer::Stop();
727
728 Mix_ChannelFinished( nullptr );
729 Mix_HookMusicFinished( nullptr );
730
731 soundSampleManager.clearFinishedSamples();
732
733 musicTrackManager.clearFinishedMusic();
734 musicTrackManager.clearMusicDB();
735
736 Mix_CloseAudio();
737 Mix_Quit();
738
739 mixerChannelCount = 0;
740
741 isInitialized = false;
742 }
743
744 // We can't hold the audioMutex here because if MusicRestartManager's working
745 // thread is already waiting on it, then there will be a deadlock while waiting
746 // for it to join. The Mix_HookMusicFinished()'s callback can no longer be called
747 // at the moment because it has been already unregistered.
748 musicRestartManager.stopWorker();
749 }
750
751 void Audio::Mute()
752 {
753 const std::scoped_lock<std::recursive_mutex> lock( audioMutex );
754
755 if ( isMuted || !isInitialized ) {
756 return;
757 }
758
759 assert( Mix_AllocateChannels( -1 ) > 0 && checkChannelsVolumeSync() );
760
761 isMuted = true;
762
763 // Mix_Volume( -1, X ) returns the average of all channels' volumes, but since they all have to have the same volume (and we just checked that their volume settings
764 // are in sync) it is safe to use its result here.
765 savedMixerVolume = Mix_Volume( -1, 0 );
766 savedMusicVolume = Mix_VolumeMusic( 0 );
767 }
768
769 void Audio::Unmute()
770 {
771 const std::scoped_lock<std::recursive_mutex> lock( audioMutex );
772
773 if ( !isMuted || !isInitialized ) {
774 return;
775 }
776
777 assert( Mix_AllocateChannels( -1 ) > 0 && savedMixerVolume >= 0 && savedMusicVolume >= 0 );
778
779 isMuted = false;
780
781 Mix_Volume( -1, savedMixerVolume );
782 Mix_VolumeMusic( savedMusicVolume );
783 }
784
785 bool Audio::isValid()
786 {
787 return isInitialized;
788 }
789
790 void Mixer::SetChannels( const int num )
791 {
792 if ( num <= 0 ) {
793 // When trying to allocate zero channels, an attempt to call Mix_Volume( -1, X ) results in division by zero when calculating the average volume
794 assert( 0 );
795 return;
796 }
797
798 const std::scoped_lock<std::recursive_mutex> lock( audioMutex );
799
800 if ( !isInitialized ) {
801 return;
802 }
803
804 assert( checkChannelsVolumeSync() );
805
806 mixerChannelCount = Mix_AllocateChannels( num );
807 if ( num != mixerChannelCount ) {
808 ERROR_LOG( "Failed to allocate the requested number of audio channels. The requested number of channels is " << num << ", the actual allocated number is "
809 << mixerChannelCount )
810 }
811
812 assert( mixerChannelCount > 0 );
813
814 if ( isMuted ) {
815 // Make sure that all mixer channels (including the ones that have just been allocated) are muted.
816 Mix_Volume( -1, 0 );
817 }
818 else {
819 // Make sure that all mixer channels (including the ones that have just been allocated) have the same volume settings.
820 syncChannelsVolume();
821 }
822 }
823
824 int Mixer::getChannelCount()
825 {
826 return mixerChannelCount;
827 }
828
829 int Mixer::Play( const uint8_t * ptr, const uint32_t size, const bool loop, const std::optional<std::pair<int16_t, uint8_t>> position /* = {} */ )
830 {
831 if ( ptr == nullptr || size == 0 ) {
832 // You are trying to play an empty sound. Check your logic!
833 assert( 0 );
834 return -1;
835 }
836
837 const std::scoped_lock<std::recursive_mutex> lock( audioMutex );
838
839 if ( !isInitialized ) {
840 return -1;
841 }
842
843 soundSampleManager.clearFinishedSamples();
844
845 const std::unique_ptr<SDL_RWops, void ( * )( SDL_RWops * )> rwops( SDL_RWFromConstMem( ptr, static_cast<int>( size ) ), SDL_FreeRW );
846 if ( !rwops ) {
847 ERROR_LOG( "Failed to create an audio chunk from memory. The error: " << SDL_GetError() )
848 return -1;
849 }
850
851 std::unique_ptr<Mix_Chunk, void ( * )( Mix_Chunk * )> sample( Mix_LoadWAV_RW( rwops.get(), 0 ), Mix_FreeChunk );
852 if ( !sample ) {
853 ERROR_LOG( "Failed to create an audio chunk from memory. The error: " << Mix_GetError() )
854 return -1;
855 }
856
857 // SDL itself maintains all internal channel bookkeeping, so when using the "first free channel"
858 // for playback, it is not known in advance which channel will be used. If additional channel
859 // setup is needed, then, to avoid arbitrary volume fluctuations, we will temporarily mute the
860 // audio chunk itself until we can properly adjust the channel parameters.
861 const int chunkVolume = position ? Mix_VolumeChunk( sample.get(), 0 ) : 0;
862 if ( chunkVolume < 0 ) {
863 ERROR_LOG( "Failed to mute the audio chunk. The error: " << Mix_GetError() )
864 return -1;
865 }
866
867 const int channel = Mix_PlayChannel( -1, sample.get(), loop ? -1 : 0 );
868 if ( channel < 0 ) {
869 ERROR_LOG( "Failed to play the audio chunk. The error: " << Mix_GetError() )
870 return channel;
871 }
872
873 if ( position ) {
874 // Immediately pause the channel so as not to continue playing while it is being set up
875 Mix_Pause( channel );
876
877 setPosition( channel, position->first, position->second );
878
879 // When restoring the volume of an audio chunk, the only correct result of the call is zero,
880 // because this is exactly what the volume of the muted chunk should be
881 if ( Mix_VolumeChunk( sample.get(), chunkVolume ) != 0 ) {
882 ERROR_LOG( "Failed to restore the volume of the audio chunk for channel " << channel << ". The error: " << Mix_GetError() )
883 }
884
885 // Resume the channel as soon as all its parameters are settled
886 Mix_Resume( channel );
887 }
888
889 // There can be a maximum of two items in the sample queue for a channel:
890 // the previous sample (if it hasn't been freed yet) and the current one
891 soundSampleManager.channelStarted( channel, sample.release() );
892
893 return channel;
894 }
895
896 void Mixer::setPosition( const int channelId, const int16_t angle, const uint8_t distance )
897 {
898 const std::scoped_lock<std::recursive_mutex> lock( audioMutex );
899
900 if ( !isInitialized ) {
901 return;
902 }
903
904 if ( Mix_SetPosition( channelId, angle, distance ) == 0 ) {
905 ERROR_LOG( "Failed to set the position of channel " << channelId << ". The error: " << Mix_GetError() )
906 }
907 }
908
909 void Mixer::setVolume( const int volumePercentage )
910 {
911 const int volume = normalizeToSDLVolume( volumePercentage );
912
913 const std::scoped_lock<std::recursive_mutex> lock( audioMutex );
914
915 if ( !isInitialized ) {
916 return;
917 }
918
919 assert( Mix_AllocateChannels( -1 ) > 0 && checkChannelsVolumeSync() );
920
921 if ( isMuted ) {
922 savedMixerVolume = volume;
923 return;
924 }
925
926 Mix_Volume( -1, volume );
927 }
928
929 void Mixer::Stop( const int channelId /* = -1 */ )
930 {
931 const std::scoped_lock<std::recursive_mutex> lock( audioMutex );
932
933 if ( !isInitialized ) {
934 return;
935 }
936
937 if ( Mix_HaltChannel( channelId ) != 0 ) {
938 ERROR_LOG( "Failed to halt channel " << channelId << ". The error: " << Mix_GetError() )
939 }
940 }
941
942 bool Mixer::isPlaying( const int channelId )
943 {
944 const std::scoped_lock<std::recursive_mutex> lock( audioMutex );
945
946 return isInitialized && Mix_Playing( channelId ) > 0;
947 }
948
949 bool Music::Play( const uint64_t musicUID, const PlaybackMode playbackMode )
950 {
951 const std::scoped_lock<std::recursive_mutex> lock( audioMutex );
952
953 if ( !isInitialized ) {
954 return false;
955 }
956
957 if ( musicTrackManager.isTrackInMusicDB( musicUID ) ) {
958 Stop();
959
960 playMusic( musicUID, playbackMode );
961
962 return true;
963 }
964
965 return false;
966 }
967
968 void Music::Play( const uint64_t musicUID, const std::vector<uint8_t> & v, const PlaybackMode playbackMode )
969 {
970 if ( v.empty() ) {
971 return;
972 }
973
974 const std::scoped_lock<std::recursive_mutex> lock( audioMutex );
975
976 if ( !isInitialized ) {
977 return;
978 }
979
980 musicTrackManager.addTrackToMusicDB( musicUID, std::make_shared<MusicInfo>( v ) );
981
982 Stop();
983
984 playMusic( musicUID, playbackMode );
985 }
986
987 void Music::Play( const uint64_t musicUID, const std::string & file, const PlaybackMode playbackMode )
988 {
989 if ( file.empty() ) {
990 // Nothing to play, the file name is empty.
991 return;
992 }
993
994 const std::scoped_lock<std::recursive_mutex> lock( audioMutex );
995
996 if ( !isInitialized ) {
997 return;
998 }
999
1000 musicTrackManager.addTrackToMusicDB( musicUID, std::make_shared<MusicInfo>( file ) );
1001
1002 Stop();
1003
1004 playMusic( musicUID, playbackMode );
1005 }
1006
1007 void Music::SetFadeInMs( const int timeMs )
1008 {
1009 if ( timeMs < 0 ) {
1010 // Why are you even setting a negative value?
1011 assert( 0 );
1012 return;
1013 }
1014
1015 const std::scoped_lock<std::recursive_mutex> lock( audioMutex );
1016
1017 musicFadeInMs = timeMs;
1018 }
1019
1020 void Music::setVolume( const int volumePercentage )
1021 {
1022 const int volume = normalizeToSDLVolume( volumePercentage );
1023
1024 const std::scoped_lock<std::recursive_mutex> lock( audioMutex );
1025
1026 if ( !isInitialized ) {
1027 return;
1028 }
1029
1030 if ( isMuted ) {
1031 savedMusicVolume = volume;
1032 return;
1033 }
1034
1035 Mix_VolumeMusic( volume );
1036 }
1037
1038 void Music::Stop()
1039 {
1040 const std::scoped_lock<std::recursive_mutex> lock( audioMutex );
1041
1042 if ( !isInitialized ) {
1043 return;
1044 }
1045
1046 if ( musicTrackManager.getCurrentTrack().expired() ) {
1047 // Nothing to do.
1048 return;
1049 }
1050
1051 // Some platforms (such as WebAssembly) may not support background threads. In this case,
1052 // the Mix_HookMusicFinished()'s callback can trigger an immediate restart of playback of
1053 // the stopped track. This is not what we want, so we should notify that this track will
1054 // be intentionally stopped and should not be restarted.
1055 musicTrackManager.prepareToHaltCurrentTrack();
1056
1057 // Always returns 0. After this call we have a guarantee that the Mix_HookMusicFinished()'s
1058 // callback will not be called while we are modifying the current track information.
1059 Mix_HaltMusic();
1060
1061 const std::shared_ptr<MusicInfo> currentTrack = musicTrackManager.getCurrentTrack().lock();
1062 assert( currentTrack );
1063
1064 // We can and should reliably calculate the current playback position, let's remember it
1065 if ( musicTrackManager.getCurrentTrackPlaybackMode() == PlaybackMode::RESUME_AND_PLAY_INFINITE ) {
1066 currentTrack->setPosition( currentTrack->getPosition() + musicTrackManager.getCurrentTrackPosition() );
1067 }
1068 // We either shouldn't (PLAY_ONCE) or can't (REWIND_AND_PLAY_INFINITE) reliably calculate the
1069 // current playback position, let's reset it to zero
1070 else {
1071 currentTrack->setPosition( 0 );
1072 }
1073
1074 musicTrackManager.resetCurrentTrack();
1075 }
1076
1077 bool Music::isPlaying()
1078 {
1079 const std::scoped_lock<std::recursive_mutex> lock( audioMutex );
1080
1081 return isInitialized && Mix_PlayingMusic();
1082 }
1083
1084 void Music::setMidiSoundFonts( const ListFiles & files )
1085 {
1086 const std::scoped_lock<std::recursive_mutex> lock( audioMutex );
1087
1088 if ( !isInitialized ) {
1089 return;
1090 }
1091
1092 std::string filePaths;
1093
1094 for ( const std::string & file : files ) {
1095 filePaths.append( file );
1096 filePaths.push_back( ';' );
1097 }
1098
1099 // Remove the last semicolon
1100 if ( !filePaths.empty() ) {
1101 assert( filePaths.back() == ';' );
1102
1103 filePaths.pop_back();
1104 }
1105
1106 if ( Mix_SetSoundFonts( System::encLocalToUTF8( filePaths ).c_str() ) == 0 ) {
1107 ERROR_LOG( "Failed to set MIDI SoundFonts using paths " << filePaths << ". The error: " << Mix_GetError() )
1108 }
1109 }
1110
1111 void Music::setMidiTimidityCfg( const std::string & path )
1112 {
1113 const std::scoped_lock<std::recursive_mutex> lock( audioMutex );
1114
1115 if ( !isInitialized ) {
1116 return;
1117 }
1118
1119 #if SDL_MIXER_VERSION_ATLEAST( 2, 6, 0 )
1120 if ( Mix_SetTimidityCfg( System::encLocalToUTF8( path ).c_str() ) == 0 ) {
1121 ERROR_LOG( "Failed to set the path to the timidity.cfg file to " << path << ". The error: " << Mix_GetError() )
1122 }
1123 #else
1124 ERROR_LOG( "Failed to set the path to the timidity.cfg file to " << path << ". The error: operation not supported" )
1125 #endif
1126 }