Debian Codegraph @

CorsixTH/Src/th_sound.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 "th_sound.h"
24
25 #include "config.h"
26
27 #include <SDL_mixer.h>
28 #include <SDL_rwops.h>
29
30 #include <algorithm>
31 #include <chrono>
32 #include <cmath>
33 #include <cstring>
34 #include <new>
35
36 #include "th.h"
37
38 // https://github.com/CorsixTH/theme-hospital-spec/blob/master/format-specification.md#info
39 constexpr size_t archive_header_size = 234;
40 constexpr size_t archive_header_table_position_offset = 50;
41 constexpr size_t archive_header_table_length_offset = 58;
42 constexpr size_t sound_entry_size = 32;
43 constexpr size_t sound_entry_position_offset = 18;
44 constexpr size_t sound_entry_length_offset = 26;
45
46 bool sound_archive::load_from_th_file(const uint8_t* pData,
47 size_t iDataLength) {
48 if (iDataLength < sizeof(uint32_t) + archive_header_size) {
49 return false;
50 }
51
52 // Last 4 bytes of the file is the position of the header
53 uint32_t headerPosition =
54 bytes_to_uint32_le(pData + iDataLength - sizeof(uint32_t));
55
56 // safety check on header position
57 if (static_cast<size_t>(headerPosition) >=
58 iDataLength - archive_header_size) {
59 return false;
60 }
61
62 // table position
63 size_t tablePosition = static_cast<size_t>(bytes_to_uint32_le(
64 pData + headerPosition + archive_header_table_position_offset));
65 size_t tableLength = static_cast<size_t>(bytes_to_uint32_le(
66 pData + headerPosition + archive_header_table_length_offset));
67
68 data.resize(iDataLength);
69 std::copy_n(pData, iDataLength, data.begin());
70
71 size_t soundFileCount = tableLength / sound_entry_size;
72 sound_files.clear();
73 for (int i = 0; i < soundFileCount; ++i) {
74 size_t offset = tablePosition + i * sound_entry_size;
75 if (offset + sound_entry_size > iDataLength) {
76 return false; // Out of bounds
77 }
78 sound_dat_sound_info soundInfo{
79 {},
80 bytes_to_uint32_le(data.data() + offset + sound_entry_position_offset),
81 bytes_to_uint32_le(data.data() + offset + sound_entry_length_offset)};
82 std::copy_n(data.data() + offset, soundInfo.sound_name.size(),
83 soundInfo.sound_name.begin());
84 sound_files.push_back(soundInfo);
85 }
86
87 return true;
88 }
89
90 size_t sound_archive::get_number_of_sounds() const {
91 return sound_files.size();
92 }
93
94 const char* sound_archive::get_sound_name(size_t iIndex) const {
95 if (iIndex >= sound_files.size()) return nullptr;
96 return sound_files[iIndex].sound_name.data();
97 }
98
99 constexpr uint32_t fourcc(const char c1, const char c2, const char c3,
100 const char c4) {
101 return ((static_cast<uint32_t>(static_cast<uint8_t>(c1)) << 0) |
102 (static_cast<uint32_t>(static_cast<uint8_t>(c2)) << 8) |
103 (static_cast<uint32_t>(static_cast<uint8_t>(c3)) << 16) |
104 (static_cast<uint32_t>(static_cast<uint8_t>(c4)) << 24));
105 }
106
107 namespace {
108
109 template <typename A, typename B>
110 inline uint64_t mul64(A a, B b) {
111 return static_cast<uint64_t>(a) * static_cast<uint64_t>(b);
112 }
113
114 } // namespace
115
116 size_t sound_archive::get_sound_duration(size_t iIndex) {
117 SDL_RWops* pFile = load_sound(iIndex);
118 if (!pFile) {
119 return 0;
120 }
121
122 uint16_t iWaveAudioFormat = 0;
123 uint16_t iWaveChannelCount = 0;
124 uint32_t iWaveSampleRate = 0;
125 uint32_t iWaveByteRate = 0;
126 uint16_t iWaveBlockAlign = 0;
127 uint16_t iWaveBitsPerSample = 0;
128 uint32_t iWaveDataLength = 0;
129
130 // This is a very crude RIFF parser, but it does the job.
131 uint32_t iFourCC;
132 uint32_t iChunkLength;
133 for (;;) {
134 if (SDL_RWread(pFile, &iFourCC, 4, 1) != 1) {
135 break;
136 }
137 if (SDL_RWread(pFile, &iChunkLength, 4, 1) != 1) {
138 break;
139 }
140 if (iFourCC == fourcc('R', 'I', 'F', 'F') ||
141 iFourCC == fourcc('L', 'I', 'S', 'T')) {
142 if (iChunkLength >= 4) {
143 if (SDL_RWread(pFile, &iFourCC, 4, 1) != 1) {
144 break;
145 } else {
146 continue;
147 }
148 }
149 }
150 if (iFourCC == fourcc('f', 'm', 't', ' ') && iChunkLength >= 16) {
151 if (SDL_RWread(pFile, &iWaveAudioFormat, 2, 1) != 1) {
152 break;
153 }
154 if (SDL_RWread(pFile, &iWaveChannelCount, 2, 1) != 1) {
155 break;
156 }
157 if (SDL_RWread(pFile, &iWaveSampleRate, 4, 1) != 1) {
158 break;
159 }
160 if (SDL_RWread(pFile, &iWaveByteRate, 4, 1) != 1) {
161 break;
162 }
163 if (SDL_RWread(pFile, &iWaveBlockAlign, 2, 1) != 1) {
164 break;
165 }
166 if (SDL_RWread(pFile, &iWaveBitsPerSample, 2, 1) != 1) {
167 break;
168 }
169 iChunkLength -= 16;
170 }
171 // Finally:
172 if (iFourCC == fourcc('d', 'a', 't', 'a')) {
173 iWaveDataLength = iChunkLength;
174 break;
175 }
176 if (SDL_RWseek(pFile, iChunkLength + (iChunkLength & 1), RW_SEEK_CUR) ==
177 -1) {
178 break;
179 }
180 }
181 SDL_RWclose(pFile);
182 if (iWaveAudioFormat != 1 || iWaveChannelCount == 0 || iWaveSampleRate == 0 ||
183 iWaveDataLength == 0 || iWaveBitsPerSample == 0) {
184 return 0;
185 }
186
187 return static_cast<size_t>(
188 mul64(iWaveDataLength, 8000) /
189 mul64(mul64(iWaveBitsPerSample, iWaveChannelCount), iWaveSampleRate));
190 }
191
192 SDL_RWops* sound_archive::load_sound(size_t iIndex) {
193 if (iIndex >= sound_files.size()) {
194 return nullptr;
195 }
196
197 sound_dat_sound_info pFile = sound_files[iIndex];
198 return SDL_RWFromConstMem(data.data() + pFile.position,
199 static_cast<int>(pFile.length));
200 }
201
202 sound_player* sound_player::singleton = nullptr;
203
204 sound_player::sound_player()
205 : sounds(nullptr),
206 sound_count(0),
207 camera_x(0),
208 camera_y(0),
209 camera_radius(1.0),
210 master_volume(1.0),
211 sound_effect_volume(0.5),
212 positionless_volume(MIX_MAX_VOLUME),
213 sound_effects_enabled(true) {
214 singleton = this;
215 Mix_AllocateChannels(number_of_channels);
216 Mix_ChannelFinished(on_channel_finished);
217 channels.fill(null_handle);
218
219 // Avoid likely having the same handles in save games
220 auto seconds = std::chrono::duration_cast<std::chrono::seconds>(
221 std::chrono::system_clock::now().time_since_epoch())
222 .count();
223 next_playing_track_handle = static_cast<uint32_t>(seconds);
224 }
225
226 sound_player::~sound_player() {
227 populate_from(nullptr);
228 if (singleton == this) {
229 singleton = nullptr;
230 }
231 }
232
233 void sound_player::on_channel_finished(int iChannel) {
234 sound_player* pThis = get_singleton();
235 if (pThis == nullptr) return;
236
237 pThis->release_channel(iChannel);
238 }
239
240 sound_player* sound_player::get_singleton() { return singleton; }
241
242 void sound_player::populate_from(sound_archive* pArchive) {
243 for (size_t i = 0; i < sound_count; ++i) {
244 Mix_FreeChunk(sounds[i]);
245 }
246 delete[] sounds;
247 sounds = nullptr;
248 sound_count = 0;
249
250 if (pArchive == nullptr) return;
251
252 sounds = new Mix_Chunk*[pArchive->get_number_of_sounds()];
253 for (; sound_count < pArchive->get_number_of_sounds(); ++sound_count) {
254 sounds[sound_count] = nullptr;
255 if (SDL_RWops* pRwop = pArchive->load_sound(sound_count)) {
256 sounds[sound_count] = Mix_LoadWAV_RW(pRwop, 1);
257 if (sounds[sound_count]) {
258 Mix_VolumeChunk(sounds[sound_count], MIX_MAX_VOLUME);
259 }
260 }
261 }
262 }
263
264 uint32_t sound_player::play(size_t iIndex, double dVolume, int loops) {
265 if (iIndex >= sound_count || !sounds[iIndex]) {
266 return null_handle;
267 }
268
269 return play_raw(iIndex, static_cast<int>(positionless_volume * dVolume),
270 loops);
271 }
272
273 uint32_t sound_player::play_at(size_t iIndex, int iX, int iY, int loops) {
274 if (sound_effects_enabled) {
275 return play_at(iIndex, sound_effect_volume, iX, iY, loops);
276 }
277 return null_handle;
278 }
279
280 uint32_t sound_player::play_at(size_t iIndex, double dVolume, int iX, int iY,
281 int loops) {
282 if (iIndex >= sound_count || !sounds[iIndex]) {
283 return null_handle;
284 }
285
286 const double fDX = iX - camera_x;
287 const double fDY = iY - camera_y;
288 double fDistance = sqrt(fDX * fDX + fDY * fDY);
289 if (fDistance > camera_radius) return null_handle;
290 fDistance = fDistance / camera_radius;
291
292 double fVolume =
293 master_volume * (1.0 - fDistance * 0.8) * (MIX_MAX_VOLUME * dVolume);
294
295 return play_raw(iIndex, static_cast<int>(std::lround(fVolume)), loops);
296 }
297
298 sound_player::toggle_pause_result sound_player::toggle_pause(uint32_t handle) {
299 int channel = playing_channel_for_handle(handle);
300 if (channel < 0) {
301 return toggle_pause_result::error;
302 }
303 if (Mix_Paused(channel)) {
304 Mix_Resume(channel);
305 return toggle_pause_result::resumed;
306 } else {
307 Mix_Pause(channel);
308 return toggle_pause_result::paused;
309 }
310 }
311
312 void sound_player::stop(uint32_t handle) {
313 int channel = playing_channel_for_handle(handle);
314 if (channel < 0) {
315 return;
316 }
317 Mix_HaltChannel(channel);
318 release_channel(channel);
319 }
320
321 bool sound_player::is_playing(uint32_t handle) {
322 return playing_channel_for_handle(handle) >= 0;
323 }
324
325 void sound_player::set_sound_effect_volume(double dVolume) {
326 sound_effect_volume = dVolume;
327 }
328
329 void sound_player::set_sound_effects_enabled(bool bOn) {
330 sound_effects_enabled = bOn;
331 }
332
333 int sound_player::reserve_channel() {
334 std::scoped_lock lock(channel_mutex);
335 for (size_t i = 0; i < channels.size(); ++i) {
336 if (channels[i] == null_handle) {
337 // Don't assign a null handle to a playing track
338 if (next_playing_track_handle == null_handle) {
339 next_playing_track_handle++;
340 }
341 channels[i] = next_playing_track_handle++;
342 return static_cast<int>(i);
343 }
344 }
345
346 return -1;
347 }
348
349 void sound_player::release_channel(int iChannel) {
350 std::scoped_lock lock(channel_mutex);
351 channels[iChannel] = null_handle;
352 }
353
354 uint32_t sound_player::play_raw(size_t iIndex, int iVolume, int loops) {
355 int iChannel = reserve_channel();
356 if (iChannel < 0) {
357 return null_handle;
358 }
359
360 Mix_Volume(iChannel, iVolume);
361 Mix_PlayChannel(iChannel, sounds[iIndex], loops);
362
363 return channels[iChannel];
364 }
365
366 void sound_player::set_camera(int iX, int iY, int iRadius) {
367 camera_x = iX;
368 camera_y = iY;
369 camera_radius = static_cast<double>(iRadius);
370 if (camera_radius < 0.001) camera_radius = 0.001;
371 }
372
373 int sound_player::playing_channel_for_handle(uint32_t handle) {
374 std::scoped_lock lock(channel_mutex);
375
376 if (handle == null_handle) {
377 return -1;
378 }
379
380 for (size_t i = 0; i < channels.size(); ++i) {
381 if (channels[i] == handle) {
382 return static_cast<int>(i);
383 }
384 }
385 return -1;
386 }