1 /*
2 * This file is part of EasyRPG Player.
3 *
4 * EasyRPG Player is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * EasyRPG Player is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with EasyRPG Player. If not, see <http://www.gnu.org/licenses/>.
16 */
17
18 #include "system.h"
19
20 #include <cstring>
21 #include <cassert>
22 #include <memory>
23 #include "audio_decoder_midi.h"
24 #include "audio_generic.h"
25 #include "audio_generic_midiout.h"
26 #include "filefinder.h"
27 #include "output.h"
28
29 GenericAudio::BgmChannel GenericAudio::BGM_Channels[nr_of_bgm_channels];
30 GenericAudio::SeChannel GenericAudio::SE_Channels[nr_of_se_channels];
31 bool GenericAudio::BGM_PlayedOnceIndicator;
32
33 std::vector<int16_t> GenericAudio::sample_buffer = {};
34 std::vector<uint8_t> GenericAudio::scrap_buffer = {};
35 unsigned GenericAudio::scrap_buffer_size = 0;
36 std::vector<float> GenericAudio::mixer_buffer = {};
37
38 std::unique_ptr<GenericAudioMidiOut> GenericAudio::midi_thread;
39
GenericAudio()40 GenericAudio::GenericAudio() {
41 int i = 0;
42 for (auto& BGM_Channel : BGM_Channels) {
43 BGM_Channel.id = i++;
44 BGM_Channel.decoder.reset();
45 }
46 i = 0;
47 for (auto& SE_Channel : SE_Channels) {
48 SE_Channel.id = i++;
49 SE_Channel.decoder.reset();
50 }
51 BGM_PlayedOnceIndicator = false;
52 midi_thread.reset();
53
54 // Initialize to some arbitrary (low-quality) format to prevent crashes
55 // when the inheriting class doesn't call SetFormat
56 SetFormat(12345, AudioDecoder::Format::S8, 1);
57 }
58
BGM_Play(Filesystem_Stream::InputStream stream,int volume,int pitch,int fadein)59 void GenericAudio::BGM_Play(Filesystem_Stream::InputStream stream, int volume, int pitch, int fadein) {
60 bool bgm_set = false;
61 for (auto& BGM_Channel : BGM_Channels) {
62 BGM_Channel.stopped = true; //Stop all running background music
63 if (!BGM_Channel.IsUsed() && !bgm_set) {
64 // If there is an unused bgm channel
65 bgm_set = true;
66 LockMutex();
67 BGM_PlayedOnceIndicator = false;
68 UnlockMutex();
69 PlayOnChannel(BGM_Channel, std::move(stream), volume, pitch, fadein);
70 }
71 }
72 }
73
BGM_Pause()74 void GenericAudio::BGM_Pause() {
75 for (auto& BGM_Channel : BGM_Channels) {
76 if (BGM_Channel.IsUsed()) {
77 BGM_Channel.SetPaused(true);
78 }
79 }
80 }
81
BGM_Resume()82 void GenericAudio::BGM_Resume() {
83 for (auto& BGM_Channel : BGM_Channels) {
84 if (BGM_Channel.IsUsed()) {
85 BGM_Channel.SetPaused(false);
86 }
87 }
88 }
89
BGM_Stop()90 void GenericAudio::BGM_Stop() {
91 LockMutex();
92 for (auto& BGM_Channel : BGM_Channels) {
93 BGM_Channel.Stop();
94 }
95 UnlockMutex();
96 }
97
BGM_PlayedOnce() const98 bool GenericAudio::BGM_PlayedOnce() const {
99 if (BGM_PlayedOnceIndicator) {
100 return BGM_PlayedOnceIndicator;
101 }
102
103 LockMutex();
104 // Audio Decoders set this in the Decoding thread
105 for (auto& BGM_Channel : BGM_Channels) {
106 if (BGM_Channel.midi_out_used) {
107 BGM_PlayedOnceIndicator = midi_thread->GetMidiOut().GetLoopCount() > 0;
108 }
109 }
110 UnlockMutex();
111
112 return BGM_PlayedOnceIndicator;
113 }
114
BGM_IsPlaying() const115 bool GenericAudio::BGM_IsPlaying() const {
116 for (auto& BGM_Channel : BGM_Channels) {
117 if (!BGM_Channel.stopped) {
118 return true;
119 };
120 }
121 return false;
122 }
123
BGM_GetTicks() const124 int GenericAudio::BGM_GetTicks() const {
125 unsigned ticks = 0;
126 LockMutex();
127 for (auto& BGM_Channel : BGM_Channels) {
128 int cur_ticks = BGM_Channel.GetTicks();
129 if (cur_ticks >= 0) {
130 ticks = static_cast<unsigned>(cur_ticks);
131 }
132 }
133 UnlockMutex();
134 return ticks;
135 }
136
BGM_Fade(int fade)137 void GenericAudio::BGM_Fade(int fade) {
138 LockMutex();
139 for (auto& BGM_Channel : BGM_Channels) {
140 BGM_Channel.SetFade(fade);
141 }
142 UnlockMutex();
143 }
144
BGM_Volume(int volume)145 void GenericAudio::BGM_Volume(int volume) {
146 LockMutex();
147 for (auto& BGM_Channel : BGM_Channels) {
148 BGM_Channel.SetVolume(volume);
149 }
150 UnlockMutex();
151 }
152
BGM_Pitch(int pitch)153 void GenericAudio::BGM_Pitch(int pitch) {
154 LockMutex();
155 for (auto& BGM_Channel : BGM_Channels) {
156 BGM_Channel.SetPitch(pitch);
157 }
158 UnlockMutex();
159 }
160
SE_Play(Filesystem_Stream::InputStream stream,int volume,int pitch)161 void GenericAudio::SE_Play(Filesystem_Stream::InputStream stream, int volume, int pitch) {
162 for (auto& SE_Channel : SE_Channels) {
163 if (!SE_Channel.decoder) {
164 //If there is an unused se channel
165 PlayOnChannel(SE_Channel, std::move(stream), volume, pitch);
166 return;
167 }
168 }
169 // FIXME Not displaying as warning because multiple games exhaust free channels available, see #1356
170 Output::Debug("Couldn't play {} SE. No free channel available", stream.GetName());
171 }
172
SE_Stop()173 void GenericAudio::SE_Stop() {
174 for (auto& SE_Channel : SE_Channels) {
175 SE_Channel.stopped = true; //Stop all running sound effects
176 }
177 }
178
Update()179 void GenericAudio::Update() {
180 // no-op, handled by the Decode function called through a thread
181 }
182
SetFormat(int frequency,AudioDecoder::Format format,int channels)183 void GenericAudio::SetFormat(int frequency, AudioDecoder::Format format, int channels) {
184 output_format.frequency = frequency;
185 output_format.format = format;
186 output_format.channels = channels;
187 }
188
PlayOnChannel(BgmChannel & chan,Filesystem_Stream::InputStream filestream,int volume,int pitch,int fadein)189 bool GenericAudio::PlayOnChannel(BgmChannel& chan, Filesystem_Stream::InputStream filestream, int volume, int pitch, int fadein) {
190 chan.paused = true; // Pause channel so the audio thread doesn't work on it
191 chan.stopped = false; // Unstop channel so the audio thread doesn't delete it
192
193 if (!filestream) {
194 Output::Warning("BGM file not readable: {}", filestream.GetName());
195 return false;
196 }
197
198 // Midiout is only supported on channel 0 because this is an exclusive resource
199 if (chan.id == 0 && GenericAudioMidiOut::IsSupported(filestream)) {
200 chan.decoder.reset();
201
202 // FIXME: Try Fluidsynth and WildMidi first
203 // If they work fallback to the normal AudioDecoder handler below
204 // There should be a way to configure the order
205 if (!MidiDecoder::CreateFluidsynth(filestream, true) && !MidiDecoder::CreateWildMidi(filestream, true)) {
206 if (!midi_thread) {
207 midi_thread = std::make_unique<GenericAudioMidiOut>();
208 if (midi_thread->IsInitialized()) {
209 midi_thread->StartThread();
210 } else {
211 midi_thread.reset();
212 }
213 }
214
215 if (midi_thread) {
216 midi_thread->LockMutex();
217 auto &midi_out = midi_thread->GetMidiOut();
218 if (midi_out.Open(std::move(filestream))) {
219 midi_out.SetPitch(pitch);
220 midi_out.SetVolume(0);
221 midi_out.SetFade(volume, std::chrono::milliseconds(fadein));
222 midi_out.SetLooping(true);
223 midi_out.Resume();
224 chan.paused = false;
225 chan.midi_out_used = true;
226 midi_thread->UnlockMutex();
227 return true;
228 }
229 midi_thread->UnlockMutex();
230 }
231 }
232 }
233
234 if (midi_thread) {
235 midi_thread->GetMidiOut().Reset();
236 }
237
238 chan.decoder = AudioDecoder::Create(filestream);
239 chan.midi_out_used = false;
240 if (chan.decoder && chan.decoder->Open(std::move(filestream))) {
241 chan.decoder->SetPitch(pitch);
242 chan.decoder->SetFormat(output_format.frequency, output_format.format, output_format.channels);
243 chan.decoder->SetVolume(0);
244 chan.decoder->SetFade(volume, std::chrono::milliseconds(fadein));
245 chan.decoder->SetLooping(true);
246 chan.paused = false; // Unpause channel -> Play it.
247
248 return true;
249 } else {
250 Output::Warning("Couldn't play BGM {}. Format not supported", filestream.GetName());
251 }
252
253 return false;
254 }
255
PlayOnChannel(SeChannel & chan,Filesystem_Stream::InputStream filestream,int volume,int pitch)256 bool GenericAudio::PlayOnChannel(SeChannel& chan, Filesystem_Stream::InputStream filestream, int volume, int pitch) {
257 chan.paused = true; // Pause channel so the audio thread doesn't work on it
258 chan.stopped = false; // Unstop channel so the audio thread doesn't delete it
259
260 std::unique_ptr<AudioSeCache> cache = AudioSeCache::Create(std::move(filestream));
261 if (cache) {
262 chan.decoder = cache->CreateSeDecoder();
263 chan.decoder->SetPitch(pitch);
264 chan.decoder->SetFormat(output_format.frequency, output_format.format, output_format.channels);
265 chan.decoder->SetVolume(volume);
266 chan.paused = false; // Unpause channel -> Play it.
267 return true;
268 } else {
269 Output::Warning("Couldn't play SE {}. Format not supported", filestream.GetName());
270 }
271
272 return false;
273 }
274
Decode(uint8_t * output_buffer,int buffer_length)275 void GenericAudio::Decode(uint8_t* output_buffer, int buffer_length) {
276 bool channel_active = false;
277 float total_volume = 0;
278 int samples_per_frame = buffer_length / output_format.channels / 2;
279
280 assert(buffer_length > 0);
281
282 if (sample_buffer.size() != (size_t)buffer_length) {
283 sample_buffer.resize(buffer_length);
284 }
285 if (mixer_buffer.size() != (size_t)buffer_length) {
286 mixer_buffer.resize(buffer_length);
287 }
288 scrap_buffer_size = samples_per_frame * output_format.channels * sizeof(uint32_t);
289 if (scrap_buffer.size() != scrap_buffer_size) {
290 scrap_buffer.resize(scrap_buffer_size);
291 }
292 memset(mixer_buffer.data(), '\0', mixer_buffer.size());
293
294 for (unsigned i = 0; i < nr_of_bgm_channels + nr_of_se_channels; i++) {
295 int read_bytes = 0;
296 int channels = 0;
297 int samplesize = 0;
298 int frequency = 0;
299 AudioDecoder::Format sampleformat;
300 float volume;
301
302 // Mix BGM and SE together;
303 bool is_bgm_channel = i < nr_of_bgm_channels;
304 bool channel_used = false;
305
306 if (is_bgm_channel) {
307 BgmChannel& currently_mixed_channel = BGM_Channels[i];
308 float current_master_volume = 1.0;
309
310 if (currently_mixed_channel.decoder && !currently_mixed_channel.paused) {
311 if (currently_mixed_channel.stopped) {
312 currently_mixed_channel.decoder.reset();
313 } else {
314 currently_mixed_channel.decoder->Update(std::chrono::microseconds(1000 * 1000 / 60));
315 volume = current_master_volume * (currently_mixed_channel.decoder->GetVolume() / 100.0);
316 currently_mixed_channel.decoder->GetFormat(frequency, sampleformat, channels);
317 samplesize = AudioDecoder::GetSamplesizeForFormat(sampleformat);
318
319 total_volume += volume;
320
321 // determine how much data has to be read from this channel (but cap at the bounds of the scrap buffer)
322 unsigned bytes_to_read = (samplesize * channels * samples_per_frame);
323 bytes_to_read = (bytes_to_read < scrap_buffer_size) ? bytes_to_read : scrap_buffer_size;
324
325 read_bytes = currently_mixed_channel.decoder->Decode(scrap_buffer.data(), bytes_to_read);
326
327 if (read_bytes < 0) {
328 // An error occured when reading - the channel is faulty - discard
329 currently_mixed_channel.decoder.reset();
330 continue; // skip this loop run - there is nothing to mix
331 }
332
333 if (!currently_mixed_channel.stopped) {
334 BGM_PlayedOnceIndicator = currently_mixed_channel.decoder->GetLoopCount() > 0;
335 }
336
337 channel_used = true;
338 }
339 }
340 } else {
341 SeChannel& currently_mixed_channel = SE_Channels[i - nr_of_bgm_channels];
342 float current_master_volume = 1.0;
343
344 if (currently_mixed_channel.decoder && !currently_mixed_channel.paused) {
345 if (currently_mixed_channel.stopped) {
346 currently_mixed_channel.decoder.reset();
347 } else {
348 volume = current_master_volume * (currently_mixed_channel.decoder->GetVolume() / 100.0);
349 currently_mixed_channel.decoder->GetFormat(frequency, sampleformat, channels);
350 samplesize = AudioDecoder::GetSamplesizeForFormat(sampleformat);
351
352 total_volume += volume;
353
354 // determine how much data has to be read from this channel (but cap at the bounds of the scrap buffer)
355 unsigned bytes_to_read = (samplesize * channels * samples_per_frame);
356 bytes_to_read = (bytes_to_read < scrap_buffer_size) ? bytes_to_read : scrap_buffer_size;
357
358 read_bytes = currently_mixed_channel.decoder->Decode(scrap_buffer.data(), bytes_to_read);
359
360 if (read_bytes < 0) {
361 // An error occured when reading - the channel is faulty - discard
362 currently_mixed_channel.decoder.reset();
363 continue; // skip this loop run - there is nothing to mix
364 }
365
366 // Now decide what to do when a channel has reached its end
367 if (currently_mixed_channel.decoder->IsFinished()) {
368 // SE are only played once so free the se if finished
369 currently_mixed_channel.decoder.reset();
370 }
371
372 channel_used = true;
373 }
374 }
375 }
376
377 //--------------------------------------------------------------------------------------------------------------------//
378 // From here downwards the currently_mixed_channel decoder may already be freed - so don't use it below this comment. //
379 //--------------------------------------------------------------------------------------------------------------------//
380
381 if (channel_used) {
382 for (unsigned ii = 0; ii < (unsigned)(read_bytes / (samplesize * channels)); ii++) {
383
384 float vall = volume;
385 float valr = vall;
386
387 // Convert to floating point
388 switch (sampleformat) {
389 case AudioDecoder::Format::S8:
390 vall *= (((int8_t *) scrap_buffer.data())[ii * channels] / 128.0);
391 valr *= (((int8_t *) scrap_buffer.data())[ii * channels + 1] / 128.0);
392 break;
393 case AudioDecoder::Format::U8:
394 vall *= (((uint8_t *) scrap_buffer.data())[ii * channels] / 128.0 - 1.0);
395 valr *= (((uint8_t *) scrap_buffer.data())[ii * channels + 1] / 128.0 - 1.0);
396 break;
397 case AudioDecoder::Format::S16:
398 vall *= (((int16_t *) scrap_buffer.data())[ii * channels] / 32768.0);
399 valr *= (((int16_t *) scrap_buffer.data())[ii * channels + 1] / 32768.0);
400 break;
401 case AudioDecoder::Format::U16:
402 vall *= (((uint16_t *) scrap_buffer.data())[ii * channels] / 32768.0 - 1.0);
403 valr *= (((uint16_t *) scrap_buffer.data())[ii * channels + 1] / 32768.0 - 1.0);
404 break;
405 case AudioDecoder::Format::S32:
406 vall *= (((int32_t *) scrap_buffer.data())[ii * channels] / 2147483648.0);
407 valr *= (((int32_t *) scrap_buffer.data())[ii * channels + 1] / 2147483648.0);
408 break;
409 case AudioDecoder::Format::U32:
410 vall *= (((uint32_t *) scrap_buffer.data())[ii * channels] / 2147483648.0 - 1.0);
411 valr *= (((uint32_t *) scrap_buffer.data())[ii * channels + 1] / 2147483648.0 - 1.0);
412 break;
413 case AudioDecoder::Format::F32:
414 vall *= (((float *) scrap_buffer.data())[ii * channels]);
415 valr *= (((float *) scrap_buffer.data())[ii * channels + 1]);
416 break;
417 }
418
419 if (!channel_active) {
420 // first channel
421 mixer_buffer[ii * output_format.channels] = vall;
422 if (channels > 1) {
423 mixer_buffer[ii * output_format.channels + 1] = valr;
424 } else {
425 mixer_buffer[ii * output_format.channels + 1] = mixer_buffer[ii * output_format.channels];
426 }
427 } else {
428 mixer_buffer[ii * output_format.channels] += vall;
429 if (channels > 1) {
430 mixer_buffer[ii * output_format.channels + 1] += valr;
431 } else {
432 mixer_buffer[ii * output_format.channels + 1] = mixer_buffer[ii * output_format.channels];
433 }
434 }
435
436 }
437 channel_active = true;
438 }
439 }
440
441 if (channel_active) {
442 if (total_volume > 1.0) {
443 float threshold = 0.8;
444 for (unsigned i = 0; i < (unsigned)(samples_per_frame * 2); i++) {
445 float sample = mixer_buffer[i];
446 float sign = (sample < 0) ? -1.0 : 1.0;
447 sample /= sign;
448 //dynamic range compression
449 if (sample > threshold) {
450 sample_buffer[i] = sign * 32768.0 * (threshold + (1.0 - threshold) * (sample - threshold) / (total_volume - threshold));
451 } else {
452 sample_buffer[i] = sign * sample * 32768.0;
453 }
454 }
455 } else {
456 //No dynamic range compression necessary
457 for (unsigned i = 0; i < (unsigned)(samples_per_frame * 2); i++) {
458 sample_buffer[i] = mixer_buffer[i] * 32768.0;
459 }
460 }
461
462 memcpy(output_buffer, sample_buffer.data(), buffer_length);
463 } else {
464 memset(output_buffer, '\0', buffer_length);
465 }
466 }
467
Stop()468 void GenericAudio::BgmChannel::Stop() {
469 stopped = true;
470 if (midi_out_used) {
471 midi_out_used = false;
472 midi_thread->GetMidiOut().Reset();
473 midi_thread->GetMidiOut().Pause();
474 } else if (decoder) {
475 decoder.reset();
476 }
477 }
478
SetPaused(bool newPaused)479 void GenericAudio::BgmChannel::SetPaused(bool newPaused) {
480 paused = newPaused;
481 if (midi_out_used) {
482 if (newPaused) {
483 midi_thread->GetMidiOut().Pause();
484 } else {
485 midi_thread->GetMidiOut().Resume();
486 }
487 }
488 }
489
GetTicks() const490 int GenericAudio::BgmChannel::GetTicks() const {
491 if (midi_out_used) {
492 return midi_thread->GetMidiOut().GetTicks();
493 } else if (decoder) {
494 return decoder->GetTicks();
495 }
496 return -1;
497 }
498
SetFade(int fade)499 void GenericAudio::BgmChannel::SetFade(int fade) {
500 if (midi_out_used) {
501 midi_thread->GetMidiOut().SetFade(0, std::chrono::milliseconds(fade));
502 } else if (decoder) {
503 decoder->SetFade(0, std::chrono::milliseconds(fade));
504 }
505 }
506
SetVolume(int volume)507 void GenericAudio::BgmChannel::SetVolume(int volume) {
508 if (midi_out_used) {
509 midi_thread->GetMidiOut().SetVolume(volume);
510 } else if (decoder) {
511 decoder->SetVolume(volume);
512 }
513 }
514
SetPitch(int pitch)515 void GenericAudio::BgmChannel::SetPitch(int pitch) {
516 if (midi_out_used) {
517 midi_thread->GetMidiOut().SetPitch(pitch);
518 } else if (decoder) {
519 decoder->SetPitch(pitch);
520 }
521 }
522
IsUsed() const523 bool GenericAudio::BgmChannel::IsUsed() const {
524 return decoder || midi_out_used;
525 }
526