Debian Codegraph @

CorsixTH/Src/sdl_audio.cpp

raw
1 /*
2 Copyright (c) 2009 Peter "Corsix" Cawley
3
4 Permission is hereby granted, free of charge, to any person obtaining a copy of
5 this software and associated documentation files (the "Software"), to deal in
6 the Software without restriction, including without limitation the rights to
7 use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
8 of the Software, and to permit persons to whom the Software is furnished to do
9 so, subject to the following conditions:
10
11 The above copyright notice and this permission notice shall be included in all
12 copies or substantial portions of the Software.
13
14 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20 SOFTWARE.
21 */
22
23 #include "config.h"
24
25 #include <SDL_events.h>
26 #include <SDL_mixer.h>
27 #include <SDL_rwops.h>
28 #include <SDL_thread.h>
29
30 #include <array>
31 #include <cmath>
32 #include <cstdlib>
33 #include <cstring>
34
35 #include "lua.hpp"
36 #include "lua_sdl.h"
37 #include "th_lua.h"
38 #include "xmi2mid.h"
39 #ifdef _MSC_VER
40 #pragma comment(lib, "SDL2_mixer")
41 #endif
42
43 class music {
44 public:
45 Mix_Music* pMusic{nullptr};
46
47 music() = default;
48
49 ~music() {
50 if (pMusic) {
51 Mix_FreeMusic(pMusic);
52 pMusic = nullptr;
53 }
54 }
55 };
56
57 namespace {
58
59 void audio_music_over_callback() {
60 SDL_Event e;
61 e.type = SDL_USEREVENT_MUSIC_OVER;
62 SDL_PushEvent(&e);
63 }
64
65 int l_init(lua_State* L) {
66 constexpr int chunk_size = 2048;
67 size_t soundfont_path_len;
68 const char* sound_font = luaL_optlstring(L, 4, nullptr, &soundfont_path_len);
69
70 // soundfont must be set before Mix_OpenAudio the first time or else
71 // fluidsynth is not loaded
72 if (sound_font != nullptr) {
73 Mix_SetSoundFonts(sound_font);
74 }
75
76 int err = Mix_OpenAudio(
77 static_cast<int>(luaL_optinteger(L, 1, MIX_DEFAULT_FREQUENCY)),
78 MIX_DEFAULT_FORMAT,
79 static_cast<int>(luaL_optinteger(L, 2, MIX_DEFAULT_CHANNELS)),
80 static_cast<int>(luaL_optinteger(L, 3, chunk_size)));
81 if (err != 0) {
82 lua_pushboolean(L, 0);
83 lua_pushstring(L, Mix_GetError());
84 return 2;
85 } else {
86 lua_pushboolean(L, 1);
87 Mix_HookMusicFinished(audio_music_over_callback);
88 return 1;
89 }
90 }
91
92 int l_destroy(lua_State* L) {
93 Mix_CloseAudio();
94 return 0;
95 }
96
97 struct load_music_async_data {
98 lua_State* L;
99 Mix_Music* music;
100 SDL_RWops* rwop;
101 char* err;
102 SDL_Thread* thread;
103 };
104
105 int load_music_async_thread(void* arg) {
106 load_music_async_data* async = (load_music_async_data*)arg;
107
108 async->music = Mix_LoadMUS_RW(async->rwop, 1);
109 async->rwop = nullptr;
110 if (async->music == nullptr) {
111 size_t iLen = std::strlen(Mix_GetError()) + 1;
112 async->err = (char*)malloc(iLen);
113 std::memcpy(async->err, Mix_GetError(), iLen);
114 }
115 SDL_Event e;
116 e.type = SDL_USEREVENT_MUSIC_LOADED;
117 e.user.data1 = arg;
118 SDL_PushEvent(&e);
119 return 0;
120 }
121
122 int l_load_music_async(lua_State* L) {
123 size_t iLength;
124 const uint8_t* pData = luaT_checkfile(L, 1, &iLength);
125 luaL_checktype(L, 2, LUA_TFUNCTION);
126 SDL_RWops* rwop = SDL_RWFromConstMem(pData, (int)iLength);
127 lua_settop(L, 2);
128
129 load_music_async_data* async = luaT_new<load_music_async_data>(L);
130 lua_pushlightuserdata(L, async);
131 lua_pushvalue(L, -2);
132 lua_settable(L, LUA_REGISTRYINDEX);
133 async->L = L;
134 async->music = nullptr;
135 async->rwop = rwop;
136 async->err = nullptr;
137 lua_createtable(L, 2, 0);
138 lua_pushvalue(L, 2);
139 lua_rawseti(L, -2, 1);
140 luaT_stdnew<music>(L, luaT_environindex, true);
141 lua_pushvalue(L, 1);
142 luaT_setenvfield(L, -2, "data");
143 lua_rawseti(L, -2, 2);
144 lua_settable(L, LUA_REGISTRYINDEX);
145
146 /*
147 In registry:
148 [light userdata async] -> [full userdata async]
149 [full userdata async] -> {
150 [1] = callback_function,
151 [2] = empty music_t userdata,
152 }
153
154 New thread will load music, and inform the main loop, which will then
155 call the callback and remove the new entries from the registry.
156 */
157
158 async->thread =
159 SDL_CreateThread(load_music_async_thread, "music_thread", async);
160
161 return 0;
162 }
163
164 int l_load_music(lua_State* L) {
165 size_t iLength;
166 const uint8_t* pData = luaT_checkfile(L, 1, &iLength);
167 SDL_RWops* rwop = SDL_RWFromConstMem(pData, (int)iLength);
168 Mix_Music* pMusic = Mix_LoadMUS_RW(rwop, 1);
169 if (pMusic == nullptr) {
170 lua_pushnil(L);
171 lua_pushstring(L, Mix_GetError());
172 return 2;
173 }
174 music* pLMusic = luaT_stdnew<music>(L, luaT_environindex, true);
175 pLMusic->pMusic = pMusic;
176 lua_pushvalue(L, 1);
177 luaT_setenvfield(L, -2, "data");
178 return 1;
179 }
180
181 int l_music_volume(lua_State* L) {
182 lua_Number fValue = luaL_checknumber(L, 1);
183 fValue = fValue * (lua_Number)MIX_MAX_VOLUME;
184 int iVolume = static_cast<int>(std::lround(fValue));
185 if (iVolume < 0) {
186 iVolume = 0;
187 } else if (iVolume > MIX_MAX_VOLUME) {
188 iVolume = MIX_MAX_VOLUME;
189 }
190 Mix_VolumeMusic(iVolume);
191 return 0;
192 }
193
194 int l_play_music(lua_State* L) {
195 music* pLMusic = luaT_testuserdata<music>(L, -1);
196 int err = Mix_PlayMusic(pLMusic->pMusic,
197 static_cast<int>(luaL_optinteger(L, 2, 1)));
198 if (err != 0) {
199 lua_pushnil(L);
200 lua_pushstring(L, Mix_GetError());
201 return 2;
202 }
203 lua_pushboolean(L, 1);
204 return 1;
205 }
206
207 int l_pause_music(lua_State* L) {
208 Mix_PauseMusic();
209 lua_pushboolean(L, Mix_PausedMusic() != 0 ? 1 : 0);
210 return 1;
211 }
212
213 int l_resume_music(lua_State* L) {
214 Mix_ResumeMusic();
215 lua_pushboolean(L, Mix_PausedMusic() == 0 ? 1 : 0);
216 return 1;
217 }
218
219 int l_stop_music(lua_State* L) {
220 Mix_HaltMusic();
221 return 0;
222 }
223
224 int l_transcode_xmi(lua_State* L) {
225 size_t iLength;
226 const uint8_t* pData = luaT_checkfile(L, 1, &iLength);
227
228 try {
229 size_t iMidLength;
230 uint8_t* pMidData = transcode_xmi_to_midi(pData, iLength, &iMidLength);
231 if (pMidData == nullptr) {
232 lua_pushnil(L);
233 lua_pushliteral(L, "Unable to transcode XMI to MIDI");
234 return 2;
235 }
236 lua_pushlstring(L, reinterpret_cast<char*>(pMidData), iMidLength);
237 delete[] pMidData;
238 } catch (const std::exception& e) {
239 luaL_error(L, "transcode_xmi exception: %s", e.what());
240 }
241
242 return 1;
243 }
244
245 constexpr std::array<struct luaL_Reg, 4> sdl_audiolib{
246 {{"init", l_init},
247 {"transcodeXmiToMid", l_transcode_xmi},
248 {"destroy", l_destroy},
249 {nullptr, nullptr}}};
250
251 constexpr std::array<struct luaL_Reg, 8> sdl_musiclib{
252 {{"loadMusic", l_load_music},
253 {"loadMusicAsync", l_load_music_async},
254 {"playMusic", l_play_music},
255 {"stopMusic", l_stop_music},
256 {"pauseMusic", l_pause_music},
257 {"resumeMusic", l_resume_music},
258 {"setMusicVolume", l_music_volume},
259 {nullptr, nullptr}}};
260
261 } // namespace
262
263 int l_load_music_async_callback(lua_State* L) {
264 load_music_async_data* async = (load_music_async_data*)lua_touserdata(L, 1);
265
266 // Frees resources allocated to the thread
267 SDL_WaitThread(async->thread, nullptr);
268
269 // Replace light UD with full UD
270 lua_pushvalue(L, 1);
271 lua_gettable(L, LUA_REGISTRYINDEX);
272 lua_insert(L, 1);
273 lua_pushnil(L);
274 lua_settable(L, LUA_REGISTRYINDEX);
275
276 // Get CB function
277 lua_pushvalue(L, 1);
278 lua_gettable(L, LUA_REGISTRYINDEX);
279 lua_rawgeti(L, -1, 1);
280
281 // Push CB arguments
282 int nargs = 1;
283 if (async->music == nullptr) {
284 lua_pushnil(L);
285 if (async->err) {
286 if (*async->err) {
287 lua_pushstring(L, async->err);
288 nargs = 2;
289 }
290 free(async->err);
291 }
292 } else {
293 lua_rawgeti(L, 2, 2);
294 music* pLMusic = (music*)lua_touserdata(L, -1);
295 pLMusic->pMusic = async->music;
296 async->music = nullptr;
297 }
298
299 // Finish cleanup
300 lua_pushvalue(L, 1);
301 lua_pushnil(L);
302 lua_settable(L, LUA_REGISTRYINDEX);
303
304 // Callback
305 lua_call(L, nargs, 0);
306
307 return 0;
308 }
309
310 int luaopen_sdl_audio(lua_State* L) {
311 lua_newtable(L);
312 luaT_setfuncs(L, sdl_audiolib.data());
313 lua_pushboolean(L, 1);
314 lua_setfield(L, -2, "loaded");
315
316 lua_createtable(L, 0, 2);
317 lua_pushvalue(L, -1);
318 lua_replace(L, luaT_environindex);
319 lua_pushvalue(L, luaT_environindex);
320 luaT_pushcclosure(L, luaT_stdgc<music, luaT_environindex>, 1);
321 lua_setfield(L, -2, "__gc");
322 lua_pushvalue(L, 1);
323 lua_setfield(L, -2, "__index");
324 lua_pop(L, 1);
325 luaT_setfuncs(L, sdl_musiclib.data());
326
327 return 1;
328 }