OpenTTD Source  20241121-master-g67a0fccfad
sdl_s.cpp
Go to the documentation of this file.
1 /*
2  * This file is part of OpenTTD.
3  * OpenTTD 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, version 2.
4  * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6  */
7 
10 #ifdef WITH_SDL
11 
12 #include "../stdafx.h"
13 
14 #include "../mixer.h"
15 #include "sdl_s.h"
16 #include <SDL.h>
17 
18 #include "../safeguards.h"
19 
22 
28 static void CDECL fill_sound_buffer(void *, Uint8 *stream, int len)
29 {
30  MxMixSamples(stream, len / 4);
31 }
32 
33 std::optional<std::string_view> SoundDriver_SDL::Start(const StringList &parm)
34 {
35  SDL_AudioSpec spec;
36 
37  /* Only initialise SDL if the video driver hasn't done it already */
38  int ret_code = 0;
39  if (SDL_WasInit(SDL_INIT_EVERYTHING) == 0) {
40  ret_code = SDL_Init(SDL_INIT_AUDIO | SDL_INIT_NOPARACHUTE);
41  } else if (SDL_WasInit(SDL_INIT_AUDIO) == 0) {
42  ret_code = SDL_InitSubSystem(SDL_INIT_AUDIO);
43  }
44  if (ret_code == -1) return SDL_GetError();
45 
46  spec.freq = GetDriverParamInt(parm, "hz", 44100);
47  spec.format = AUDIO_S16SYS;
48  spec.channels = 2;
49  spec.samples = GetDriverParamInt(parm, "samples", 1024);
50  spec.callback = fill_sound_buffer;
51  MxInitialize(spec.freq);
52  SDL_OpenAudio(&spec, &spec);
53  SDL_PauseAudio(0);
54  return std::nullopt;
55 }
56 
58 {
59  SDL_CloseAudio();
60  SDL_QuitSubSystem(SDL_INIT_AUDIO);
61  if (SDL_WasInit(SDL_INIT_EVERYTHING) == 0) {
62  SDL_Quit(); // If there's nothing left, quit SDL
63  }
64 }
65 
66 #endif /* WITH_SDL */
Factory for the SDL sound driver.
Definition: sdl_s.h:25
std::optional< std::string_view > Start(const StringList &param) override
Start this driver.
Definition: sdl_s.cpp:33
void Stop() override
Stop this driver.
Definition: sdl_s.cpp:57
int GetDriverParamInt(const StringList &parm, const char *name, int def)
Get an integer parameter the list of parameters.
Definition: driver.cpp:76
static FSoundDriver_SDL iFSoundDriver_SDL
Factory for the SDL sound driver.
Definition: sdl_s.cpp:21
static void CDECL fill_sound_buffer(void *, Uint8 *stream, int len)
Callback that fills the sound buffer.
Definition: sdl_s.cpp:28
Base for playing sound via SDL.
std::vector< std::string > StringList
Type for a list of strings.
Definition: string_type.h:60