| 1 | // Copyright (C) 2006-2009 by Tor Andersson, Lorenzo Marcantonio. |
| 2 | // Copyright (C) 2010 by Ben Cressey |
| 3 | // Copyright (C) 2021 by Chris Spiegel. |
| 4 | // |
| 5 | // This file is part of Gargoyle. |
| 6 | // |
| 7 | // Gargoyle is free software; you can redistribute it and/or modify |
| 8 | // it under the terms of the GNU General Public License as published by |
| 9 | // the Free Software Foundation; either version 2 of the License, or |
| 10 | // (at your option) any later version. |
| 11 | // |
| 12 | // Gargoyle is distributed in the hope that it will be useful, |
| 13 | // but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 14 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 15 | // GNU General Public License for more details. |
| 16 | // |
| 17 | // You should have received a copy of the GNU General Public License |
| 18 | // along with Gargoyle; if not, write to the Free Software |
| 19 | // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA |
| 20 | |
| 21 | #include <algorithm> |
| 22 | #include <chrono> |
| 23 | #include <cstddef> |
| 24 | #include <cstring> |
| 25 | #include <functional> |
| 26 | #include <memory> |
| 27 | #include <new> |
| 28 | #include <set> |
| 29 | #include <stdexcept> |
| 30 | #include <tuple> |
| 31 | #include <utility> |
| 32 | #include <vector> |
| 33 | |
| 34 | #include <unistd.h> |
| 35 | |
| 36 | #include <QtGlobal> |
| 37 | |
| 38 | #if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0) |
| 39 | #define HAS_QT6 |
| 40 | #endif |
| 41 | |
| 42 | #include <QAudioFormat> |
| 43 | #include <QIODevice> |
| 44 | #include <QTimer> |
| 45 | |
| 46 | #ifdef HAS_QT6 |
| 47 | #include <QAudioSink> |
| 48 | #include <QMediaDevices> |
| 49 | #else |
| 50 | #include <QAudioOutput> |
| 51 | #include <QSysInfo> |
| 52 | #endif |
| 53 | |
| 54 | #include <libopenmpt/libopenmpt.h> |
| 55 | #include <mpg123.h> |
| 56 | #include <sndfile.hh> |
| 57 | |
| 58 | #ifdef GARGLK_HAS_FLUIDSYNTH |
| 59 | #include <fluidsynth.h> |
| 60 | #endif |
| 61 | |
| 62 | #include "format.h" |
| 63 | |
| 64 | #include "glk.h" |
| 65 | #include "garglk.h" |
| 66 | |
| 67 | #include "gi_blorb.h" |
| 68 | |
| 69 | #define giblorb_ID_MOD (giblorb_make_id('M', 'O', 'D', ' ')) |
| 70 | #define giblorb_ID_OGG (giblorb_make_id('O', 'G', 'G', 'V')) |
| 71 | #define giblorb_ID_FORM (giblorb_make_id('F', 'O', 'R', 'M')) |
| 72 | #define giblorb_ID_AIFF (giblorb_make_id('A', 'I', 'F', 'F')) |
| 73 | |
| 74 | // non-standard types |
| 75 | #define giblorb_ID_MP3 (giblorb_make_id('M', 'P', '3', ' ')) |
| 76 | #define giblorb_ID_WAVE (giblorb_make_id('W', 'A', 'V', 'E')) |
| 77 | #define giblorb_ID_MIDI (giblorb_make_id('M', 'I', 'D', 'I')) |
| 78 | |
| 79 | #define GLK_MAXVOLUME 0x10000 |
| 80 | |
| 81 | static std::set<schanid_t> gli_channellist; |
| 82 | |
| 83 | static schanid_t gli_bleep_channel; |
| 84 | |
| 85 | #if MPG123_API_VERSION < 46 |
| 86 | static bool mp3_initialized; |
| 87 | #endif |
| 88 | |
| 89 | #ifdef _MSC_VER |
| 90 | using ssize_t = std::make_signed_t<size_t>; |
| 91 | #endif |
| 92 | |
| 93 | namespace { |
| 94 | |
| 95 | class VFS { |
| 96 | public: |
| 97 | explicit VFS(std::vector<unsigned char> buf) : m_buf(std::move(buf)) { |
| 98 | } |
| 99 | |
| 100 | qsizetype size() { |
| 101 | return m_buf.size(); |
| 102 | } |
| 103 | |
| 104 | off_t tell() const { |
| 105 | return m_offset; |
| 106 | } |
| 107 | |
| 108 | off_t seek(off_t offset, int whence) { |
| 109 | off_t new_offset = m_offset; |
| 110 | |
| 111 | switch (whence) { |
| 112 | case SEEK_SET: |
| 113 | new_offset = offset; |
| 114 | break; |
| 115 | case SEEK_CUR: |
| 116 | new_offset += offset; |
| 117 | break; |
| 118 | case SEEK_END: |
| 119 | new_offset = m_buf.size() + offset; |
| 120 | break; |
| 121 | default: |
| 122 | return -1; |
| 123 | } |
| 124 | |
| 125 | if (new_offset < 0) { |
| 126 | return -1; |
| 127 | } |
| 128 | |
| 129 | return m_offset = new_offset; |
| 130 | } |
| 131 | |
| 132 | void rewind() { |
| 133 | m_offset = 0; |
| 134 | } |
| 135 | |
| 136 | std::size_t read(void *ptr, off_t count) { |
| 137 | if (m_offset >= static_cast<off_t>(m_buf.size())) { |
| 138 | return 0; |
| 139 | } |
| 140 | |
| 141 | if (m_offset + count > static_cast<off_t>(m_buf.size())) { |
| 142 | count = m_buf.size() - m_offset; |
| 143 | } |
| 144 | |
| 145 | std::memcpy(ptr, &m_buf[m_offset], count); |
| 146 | m_offset += count; |
| 147 | |
| 148 | return count; |
| 149 | } |
| 150 | |
| 151 | private: |
| 152 | const std::vector<unsigned char> m_buf; |
| 153 | off_t m_offset = 0; |
| 154 | }; |
| 155 | |
| 156 | class SoundError : public std::runtime_error { |
| 157 | public: |
| 158 | explicit SoundError(const std::string &msg) : std::runtime_error(msg) { |
| 159 | } |
| 160 | }; |
| 161 | |
| 162 | class SoundSource : public QIODevice { |
| 163 | public: |
| 164 | explicit SoundSource(int plays) : m_plays(plays) { |
| 165 | } |
| 166 | |
| 167 | virtual qint64 source_read(void *data, qint64 max) = 0; |
| 168 | virtual void source_rewind() = 0; |
| 169 | |
| 170 | // Sources must use 32-bit floating point audio. |
| 171 | void set_format(int samplerate, int channels) { |
| 172 | m_format.setSampleRate(samplerate); |
| 173 | m_format.setChannelCount(channels); |
| 174 | #ifdef HAS_QT6 |
| 175 | m_format.setSampleFormat(QAudioFormat::Float); |
| 176 | #else |
| 177 | m_format.setSampleSize(32); |
| 178 | m_format.setCodec("audio/pcm"); |
| 179 | m_format.setByteOrder(static_cast<QAudioFormat::Endian>(QSysInfo::Endian::ByteOrder)); |
| 180 | m_format.setSampleType(QAudioFormat::Float); |
| 181 | #endif |
| 182 | } |
| 183 | |
| 184 | QAudioFormat format() { |
| 185 | return m_format; |
| 186 | } |
| 187 | |
| 188 | qint64 readData(char *data, qint64 max) override { |
| 189 | // QIODevice buffers data; if its buffer is full enough to |
| 190 | // satisfy its current needs, it calls readData with a max |
| 191 | // size of 0 (I'm not sure why it doesn't just skip calling it |
| 192 | // entirely). This does not preclude further calls with a |
| 193 | // positive max value in the future, so short-circuit here to |
| 194 | // avoid getting 0 bytes back from the decoder and triggering |
| 195 | // the EOF/handle repeat code below. |
| 196 | // |
| 197 | // The QIODevice docs say that readData "might be called with a |
| 198 | // maxSize of 0, which can be used to perform post-reading |
| 199 | // operations", but that's misleading as far as I can tell, |
| 200 | // given that it might also be called mid-read instead of just |
| 201 | // post-read. |
| 202 | if (max == 0) { |
| 203 | return 0; |
| 204 | } |
| 205 | |
| 206 | std::size_t n = 0; |
| 207 | if (m_plays > 0) { |
| 208 | n = source_read(data, max); |
| 209 | if (n == 0 && (m_plays == 0xffffffff || --m_plays > 0)) { |
| 210 | source_rewind(); |
| 211 | n = source_read(data, max); |
| 212 | } |
| 213 | } |
| 214 | |
| 215 | // Ensure at least one full audio buffer was written. |
| 216 | if (n == 0) { |
| 217 | qint64 needed = m_buffer_size - m_written; |
| 218 | |
| 219 | if (needed >= 0) { |
| 220 | n = std::min(needed, max); |
| 221 | std::memset(data, 0, n); |
| 222 | } |
| 223 | } |
| 224 | |
| 225 | m_written += n; |
| 226 | |
| 227 | return n; |
| 228 | } |
| 229 | |
| 230 | qint64 writeData(const char *, qint64) override { |
| 231 | return 0; |
| 232 | } |
| 233 | |
| 234 | void set_audio_buffer_size(qint64 size) |
| 235 | { |
| 236 | m_buffer_size = size; |
| 237 | } |
| 238 | |
| 239 | #ifdef HAS_QT6 |
| 240 | // from the consumer's point of view, SoundSource is a sequential stream of data |
| 241 | bool isSequential() const override { |
| 242 | return true; |
| 243 | } |
| 244 | |
| 245 | // The Windows implementation of QAudioSink uses this to determine whether there is more |
| 246 | // audio available to be played. We either claim to have a full buffer available if there |
| 247 | // are more loops to be played, or zero bytes if not. |
| 248 | qint64 bytesAvailable() const override { |
| 249 | return m_plays == 0 ? 0 : m_buffer_size; |
| 250 | } |
| 251 | #endif |
| 252 | |
| 253 | private: |
| 254 | QAudioFormat m_format; |
| 255 | glui32 m_plays; |
| 256 | qint64 m_buffer_size = 0; |
| 257 | qint64 m_written = 0; |
| 258 | }; |
| 259 | |
| 260 | // The C++ API requires C++17, so until Gargoyle switches from C++14 to |
| 261 | // C++17, use the C API. |
| 262 | class OpenMPTSource : public SoundSource { |
| 263 | public: |
| 264 | OpenMPTSource(const std::vector<unsigned char> &buf, int plays) : |
| 265 | SoundSource(plays), |
| 266 | m_mod(openmpt_module_create_from_memory2(buf.data(), buf.size(), nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr), openmpt_module_destroy) |
| 267 | { |
| 268 | if (!m_mod) { |
| 269 | throw SoundError("can't parse MOD file"); |
| 270 | } |
| 271 | |
| 272 | set_format(48000, 2); |
| 273 | } |
| 274 | |
| 275 | protected: |
| 276 | qint64 source_read(void *data, qint64 max) override { |
| 277 | return 8 * openmpt_module_read_interleaved_float_stereo(m_mod.get(), format().sampleRate(), max / 8, reinterpret_cast<float *>(data)); |
| 278 | } |
| 279 | |
| 280 | void source_rewind() override { |
| 281 | openmpt_module_set_position_seconds(m_mod.get(), 0); |
| 282 | } |
| 283 | |
| 284 | private: |
| 285 | std::unique_ptr<openmpt_module, decltype(&openmpt_module_destroy)> m_mod; |
| 286 | }; |
| 287 | |
| 288 | class SndfileSource : public SoundSource { |
| 289 | public: |
| 290 | SndfileSource(std::vector<unsigned char> buf, glui32 plays) : |
| 291 | SoundSource(plays), |
| 292 | m_vfs(std::move(buf)) |
| 293 | { |
| 294 | SF_VIRTUAL_IO io = get_io(); |
| 295 | m_soundfile = SndfileHandle(io, this); |
| 296 | if (!m_soundfile) { |
| 297 | throw SoundError("can't open with libsndfile"); |
| 298 | } |
| 299 | |
| 300 | set_format(m_soundfile.samplerate(), m_soundfile.channels()); |
| 301 | } |
| 302 | |
| 303 | qint64 source_read(void *data, qint64 max) override { |
| 304 | return 4 * m_soundfile.read(reinterpret_cast<float *>(data), max / 4); |
| 305 | } |
| 306 | |
| 307 | void source_rewind() override { |
| 308 | m_vfs.rewind(); |
| 309 | SF_VIRTUAL_IO io = get_io(); |
| 310 | m_soundfile = SndfileHandle(io, this); |
| 311 | } |
| 312 | |
| 313 | private: |
| 314 | SndfileHandle m_soundfile; |
| 315 | VFS m_vfs; |
| 316 | |
| 317 | static SF_VIRTUAL_IO get_io() { |
| 318 | SF_VIRTUAL_IO io; |
| 319 | |
| 320 | io.get_filelen = vio_get_filelen; |
| 321 | io.seek = vio_seek; |
| 322 | io.read = vio_read; |
| 323 | io.write = vio_write; |
| 324 | io.tell = vio_tell; |
| 325 | |
| 326 | return io; |
| 327 | } |
| 328 | |
| 329 | static VFS &vfs(void *source) { |
| 330 | return reinterpret_cast<SndfileSource *>(source)->m_vfs; |
| 331 | } |
| 332 | |
| 333 | static sf_count_t vio_get_filelen(void *source) { |
| 334 | return vfs(source).size(); |
| 335 | } |
| 336 | |
| 337 | static sf_count_t vio_seek(sf_count_t offset, int whence, void *source) { |
| 338 | return vfs(source).seek(offset, whence); |
| 339 | } |
| 340 | |
| 341 | static sf_count_t vio_read(void *ptr, sf_count_t count, void *source) { |
| 342 | return vfs(source).read(ptr, count); |
| 343 | } |
| 344 | |
| 345 | static sf_count_t vio_write(const void *, sf_count_t, void *) { |
| 346 | throw SoundError("writing not supported"); |
| 347 | } |
| 348 | |
| 349 | static sf_count_t vio_tell(void *source) { |
| 350 | return vfs(source).tell(); |
| 351 | } |
| 352 | }; |
| 353 | |
| 354 | class Mpg123Source : public SoundSource { |
| 355 | public: |
| 356 | Mpg123Source(std::vector<unsigned char> buf, glui32 plays) : |
| 357 | SoundSource(plays), |
| 358 | #if MPG123_API_VERSION < 46 |
| 359 | m_handle(nullptr, mpg123_delete), |
| 360 | #else |
| 361 | m_handle(mpg123_new(nullptr, nullptr), mpg123_delete), |
| 362 | #endif |
| 363 | m_vfs(std::move(buf)) |
| 364 | { |
| 365 | #if MPG123_API_VERSION < 46 |
| 366 | if (!mp3_initialized) { |
| 367 | throw SoundError("mpg123 not initialized"); |
| 368 | } |
| 369 | |
| 370 | m_handle.reset(mpg123_new(nullptr, nullptr)); |
| 371 | #endif |
| 372 | if (!m_handle) { |
| 373 | throw SoundError("can't create mp3 handle"); |
| 374 | } |
| 375 | |
| 376 | mpg123_replace_reader_handle(m_handle.get(), vio_read, vio_lseek, nullptr); |
| 377 | if (mpg123_open_handle(m_handle.get(), this) != MPG123_OK) { |
| 378 | throw SoundError("can't open mp3"); |
| 379 | } |
| 380 | |
| 381 | mpg123_format_none(m_handle.get()); |
| 382 | |
| 383 | #if MPG123_API_VERSION < 46 |
| 384 | if (mpg123_format(m_handle.get(), 44100, MPG123_STEREO | MPG123_MONO, MPG123_ENC_FLOAT_32) != MPG123_OK) { |
| 385 | #else |
| 386 | if (mpg123_format2(m_handle.get(), 0, MPG123_STEREO | MPG123_MONO, MPG123_ENC_FLOAT_32) != MPG123_OK) { |
| 387 | #endif |
| 388 | throw SoundError("can't set mp3 format"); |
| 389 | } |
| 390 | |
| 391 | int encoding; |
| 392 | if (mpg123_getformat(m_handle.get(), &m_rate, &m_channels, &encoding) != MPG123_OK) { |
| 393 | throw SoundError("can't get mp3 format information"); |
| 394 | } |
| 395 | |
| 396 | if (encoding != MPG123_ENC_FLOAT_32) { |
| 397 | throw SoundError("can't request floating point samples for mp3"); |
| 398 | } |
| 399 | |
| 400 | set_format(m_rate, m_channels); |
| 401 | } |
| 402 | |
| 403 | qint64 source_read(void *data, qint64 max) override { |
| 404 | int err; |
| 405 | std::size_t done; |
| 406 | |
| 407 | if (m_eof) { |
| 408 | return 0; |
| 409 | } |
| 410 | |
| 411 | #if MPG123_API_VERSION < 46 |
| 412 | err = mpg123_read(m_handle.get(), static_cast<unsigned char *>(data), max, &done); |
| 413 | #else |
| 414 | err = mpg123_read(m_handle.get(), data, max, &done); |
| 415 | #endif |
| 416 | |
| 417 | if (err != MPG123_OK && err != MPG123_DONE) { |
| 418 | return 0; |
| 419 | } |
| 420 | |
| 421 | if (err == MPG123_DONE) { |
| 422 | m_eof = true; |
| 423 | } |
| 424 | |
| 425 | return done; |
| 426 | } |
| 427 | |
| 428 | void source_rewind() override { |
| 429 | m_vfs.rewind(); |
| 430 | m_eof = mpg123_open_handle(m_handle.get(), this) != MPG123_OK; |
| 431 | } |
| 432 | |
| 433 | private: |
| 434 | std::unique_ptr<mpg123_handle, decltype(&mpg123_delete)> m_handle; |
| 435 | |
| 436 | VFS m_vfs; |
| 437 | long m_rate; |
| 438 | int m_channels; |
| 439 | bool m_eof = false; |
| 440 | |
| 441 | static VFS &vfs(void *source) { |
| 442 | return reinterpret_cast<Mpg123Source *>(source)->m_vfs; |
| 443 | } |
| 444 | |
| 445 | static ssize_t vio_read(void *source, void *ptr, std::size_t count) { |
| 446 | return vfs(source).read(ptr, count); |
| 447 | } |
| 448 | |
| 449 | static off_t vio_lseek(void *source, off_t offset, int whence) { |
| 450 | return vfs(source).seek(offset, whence); |
| 451 | } |
| 452 | }; |
| 453 | |
| 454 | #ifdef GARGLK_HAS_FLUIDSYNTH |
| 455 | class FluidSynthSource : public SoundSource { |
| 456 | public: |
| 457 | FluidSynthSource(const std::vector<unsigned char> &buf, glui32 plays) : |
| 458 | SoundSource(plays) |
| 459 | { |
| 460 | for (const auto &level : {FLUID_PANIC, FLUID_ERR, FLUID_WARN, FLUID_INFO, FLUID_DBG}) { |
| 461 | fluid_set_log_function(level, nullptr, nullptr); |
| 462 | } |
| 463 | |
| 464 | m_settings.reset(new_fluid_settings()); |
| 465 | if (m_settings == nullptr) { |
| 466 | throw SoundError("fluidsynth unable to allocate settings"); |
| 467 | } |
| 468 | |
| 469 | fluid_settings_setnum(m_settings.get(), "synth.gain", 0.6); |
| 470 | fluid_settings_setint(m_settings.get(), "synth.reverb.active", gli_conf_fluidsynth_reverb); |
| 471 | fluid_settings_setint(m_settings.get(), "synth.chorus.active", gli_conf_fluidsynth_chorus); |
| 472 | |
| 473 | double samplerate; |
| 474 | fluid_settings_setnum(m_settings.get(), "synth.sample-rate", 48000); |
| 475 | if (fluid_settings_getnum(m_settings.get(), "synth.sample-rate", &samplerate) == FLUID_FAILED) { |
| 476 | throw SoundError("fluidsynth unable to get sample rate"); |
| 477 | } |
| 478 | |
| 479 | m_synth.reset(new_fluid_synth(m_settings.get())); |
| 480 | if (m_synth == nullptr) { |
| 481 | throw SoundError("fluidsynth unable to allocate synth"); |
| 482 | } |
| 483 | |
| 484 | for (const auto &soundfont : gli_conf_soundfonts) { |
| 485 | fluid_synth_sfload(m_synth.get(), soundfont.c_str(), 1); |
| 486 | } |
| 487 | |
| 488 | if (fluid_synth_get_sfont(m_synth.get(), 0) == nullptr) { |
| 489 | char *s = nullptr; |
| 490 | |
| 491 | if (fluid_settings_dupstr(m_settings.get(), "synth.default-soundfont", &s) != FLUID_OK || |
| 492 | s == nullptr || |
| 493 | s[0] == 0) |
| 494 | { |
| 495 | fluid_free(s); |
| 496 | throw SoundError("fluidsynth unable to find default soundfont"); |
| 497 | } |
| 498 | |
| 499 | std::string soundfont = s; |
| 500 | fluid_free(s); |
| 501 | |
| 502 | if (fluid_synth_sfload(m_synth.get(), soundfont.c_str(), 1) == FLUID_FAILED) { |
| 503 | throw SoundError("unable to load sound font"); |
| 504 | } |
| 505 | } |
| 506 | |
| 507 | fluid_synth_set_interp_method(m_synth.get(), -1, FLUID_INTERP_7THORDER); |
| 508 | |
| 509 | m_player.reset(new_fluid_player(m_synth.get())); |
| 510 | if (m_player == nullptr) { |
| 511 | throw SoundError("fluidsynth unable to allocate player"); |
| 512 | } |
| 513 | |
| 514 | if (fluid_player_add_mem(m_player.get(), buf.data(), buf.size()) == FLUID_FAILED) { |
| 515 | throw SoundError("fluidsynth unable to load midi file"); |
| 516 | } |
| 517 | |
| 518 | if (fluid_player_play(m_player.get()) == FLUID_FAILED) { |
| 519 | throw SoundError("fluidsynth unable to play midi file"); |
| 520 | } |
| 521 | |
| 522 | set_format(samplerate, 2); |
| 523 | } |
| 524 | |
| 525 | protected: |
| 526 | qint64 source_read(void *data, qint64 max) override { |
| 527 | if (fluid_player_get_status(m_player.get()) == FLUID_PLAYER_DONE) { |
| 528 | return 0; |
| 529 | } |
| 530 | |
| 531 | if (fluid_synth_write_float(m_synth.get(), max / 8, data, 0, 2, data, 1, 2) != FLUID_OK) { |
| 532 | return 0; |
| 533 | } |
| 534 | |
| 535 | return max; |
| 536 | } |
| 537 | |
| 538 | void source_rewind() override { |
| 539 | fluid_player_stop(m_player.get()); |
| 540 | fluid_player_play(m_player.get()); |
| 541 | } |
| 542 | |
| 543 | private: |
| 544 | // The FluidSynth code handles null pointers in its delete |
| 545 | // functions, but does not document this fact, so to be future |
| 546 | // proof, create wrappers that check for null. |
| 547 | static void settings_deleter(fluid_settings_t *settings) { |
| 548 | if (settings != nullptr) { |
| 549 | delete_fluid_settings(settings); |
| 550 | } |
| 551 | } |
| 552 | |
| 553 | static void synth_deleter(fluid_synth_t *synth) { |
| 554 | if (synth != nullptr) { |
| 555 | delete_fluid_synth(synth); |
| 556 | } |
| 557 | } |
| 558 | |
| 559 | static void player_deleter(fluid_player_t *player) { |
| 560 | if (player != nullptr) { |
| 561 | delete_fluid_player(player); |
| 562 | } |
| 563 | } |
| 564 | |
| 565 | std::unique_ptr<fluid_settings_t, decltype(&settings_deleter)> m_settings{nullptr, settings_deleter}; |
| 566 | std::unique_ptr<fluid_synth_t, decltype(&synth_deleter)> m_synth{nullptr, synth_deleter}; |
| 567 | std::unique_ptr<fluid_player_t, decltype(&player_deleter)> m_player{nullptr, player_deleter}; |
| 568 | }; |
| 569 | #endif |
| 570 | |
| 571 | } |
| 572 | |
| 573 | struct glk_schannel_struct { |
| 574 | glk_schannel_struct(glui32 volume, glui32 rock_) : |
| 575 | current_volume(volume), |
| 576 | target_volume(volume), |
| 577 | rock(rock_), |
| 578 | disprock(gli_register_obj != nullptr ? |
| 579 | gli_register_obj(this, gidisp_Class_Schannel) : |
| 580 | gidispatch_rock_t{}) |
| 581 | { |
| 582 | timer.setTimerType(Qt::TimerType::PreciseTimer); |
| 583 | } |
| 584 | |
| 585 | glk_schannel_struct(const glk_schannel_struct &) = delete; |
| 586 | glk_schannel_struct &operator=(const glk_schannel_struct &) = delete; |
| 587 | |
| 588 | ~glk_schannel_struct() { |
| 589 | if (gli_unregister_obj != nullptr) { |
| 590 | gli_unregister_obj(this, gidisp_Class_Schannel, disprock); |
| 591 | } |
| 592 | } |
| 593 | |
| 594 | void set_current_volume() { |
| 595 | auto target_volume = static_cast<double>(current_volume) / GLK_MAXVOLUME; |
| 596 | if (audio) { |
| 597 | audio->setVolume(target_volume); |
| 598 | } |
| 599 | } |
| 600 | |
| 601 | // Source comes first so it's deleted last, since QAudioOutput still |
| 602 | // holds a pointer to it. This is a shared_ptr to emphasize that |
| 603 | // it's shared with QAudioOutput, but QAudioOutput doesn't use |
| 604 | // shared_ptr, so it's really just informative. The real advantage |
| 605 | // of a smart pointer here is automatic deletion of the allocated |
| 606 | // pointer on deletion of the sound channel. |
| 607 | std::shared_ptr<SoundSource> source; |
| 608 | |
| 609 | // It is possible for this object to be destroyed on shutdown, i.e. |
| 610 | // when static objects are being destroyed (e.g. if |
| 611 | // glk_schannel_delete() is called in a static object's destructor). |
| 612 | // Gargoyle itself doesn't do this, but applications/interpreters |
| 613 | // are allowed to. The problem is that at least some Qt audio |
| 614 | // backends (PulseAudio for one) are implemented as static objects. |
| 615 | // The order of destruction of static objects can't be controlled |
| 616 | // between different files, meaning it's possible for the backend to |
| 617 | // be destroyed before this audio object is destroyed; but the |
| 618 | // destruction of this audio object relies on the audio backend to |
| 619 | // exist. If it's destroyed first, the result is undefined behavior. |
| 620 | // To work around this, a custom deleter is used which will only |
| 621 | // delete this instance if Gargoyle is not shutting down, as |
| 622 | // determined by the gli_exiting flag. |
| 623 | #ifdef HAS_QT6 |
| 624 | std::unique_ptr<QAudioSink, std::function<void(QAudioSink *)>> audio; |
| 625 | #else |
| 626 | std::unique_ptr<QAudioOutput, std::function<void(QAudioOutput *)>> audio; |
| 627 | #endif |
| 628 | |
| 629 | QTimer timer; |
| 630 | double duration = 0; |
| 631 | double difference = 0; |
| 632 | std::chrono::steady_clock::time_point last_volume_bump; |
| 633 | long current_volume; |
| 634 | glui32 target_volume; |
| 635 | glui32 volume_notify = 0; |
| 636 | |
| 637 | bool paused = false; |
| 638 | |
| 639 | glui32 rock; |
| 640 | gidispatch_rock_t disprock; |
| 641 | }; |
| 642 | |
| 643 | gidispatch_rock_t gli_sound_get_channel_disprock(const channel_t *chan) |
| 644 | { |
| 645 | return chan->disprock; |
| 646 | } |
| 647 | |
| 648 | void gli_initialize_sound() |
| 649 | { |
| 650 | #if MPG123_API_VERSION < 46 |
| 651 | mp3_initialized = mpg123_init() == MPG123_OK; |
| 652 | #endif |
| 653 | } |
| 654 | |
| 655 | schanid_t glk_schannel_create(glui32 rock) |
| 656 | { |
| 657 | return glk_schannel_create_ext(rock, GLK_MAXVOLUME); |
| 658 | } |
| 659 | |
| 660 | schanid_t glk_schannel_create_ext(glui32 rock, glui32 volume) |
| 661 | { |
| 662 | channel_t *chan; |
| 663 | |
| 664 | if (!gli_conf_sound) { |
| 665 | return nullptr; |
| 666 | } |
| 667 | |
| 668 | chan = new channel_t(volume, rock); |
| 669 | |
| 670 | auto on_timeout = [chan]() { |
| 671 | auto now = std::chrono::steady_clock::now(); |
| 672 | double elapsed = std::chrono::duration<double>(now - chan->last_volume_bump).count(); |
| 673 | chan->last_volume_bump = now; |
| 674 | |
| 675 | chan->current_volume += chan->difference * elapsed / chan->duration; |
| 676 | |
| 677 | if ((chan->difference > 0 && chan->current_volume >= chan->target_volume) || |
| 678 | (chan->difference < 0 && chan->current_volume <= chan->target_volume)) |
| 679 | { |
| 680 | chan->current_volume = chan->target_volume; |
| 681 | } |
| 682 | |
| 683 | if (chan->current_volume == chan->target_volume) { |
| 684 | if (chan->volume_notify != 0) { |
| 685 | gli_event_store(evtype_VolumeNotify, nullptr, 0, chan->volume_notify); |
| 686 | gli_notification_waiting(); |
| 687 | } |
| 688 | chan->timer.stop(); |
| 689 | } |
| 690 | |
| 691 | chan->set_current_volume(); |
| 692 | }; |
| 693 | QObject::connect(&chan->timer, &QTimer::timeout, on_timeout); |
| 694 | |
| 695 | gli_channellist.insert(chan); |
| 696 | |
| 697 | return chan; |
| 698 | } |
| 699 | |
| 700 | void glk_schannel_destroy(schanid_t chan) |
| 701 | { |
| 702 | if (chan == nullptr) { |
| 703 | gli_strict_warning("schannel_destroy: invalid id."); |
| 704 | return; |
| 705 | } |
| 706 | |
| 707 | glk_schannel_stop(chan); |
| 708 | |
| 709 | // If this is running on exit, then it's possible for |
| 710 | // gli_channellist to be destroyed before this is called. |
| 711 | if (!gli_exiting) { |
| 712 | gli_channellist.erase(chan); |
| 713 | } |
| 714 | |
| 715 | delete chan; |
| 716 | } |
| 717 | |
| 718 | schanid_t glk_schannel_iterate(schanid_t chan, glui32 *rock) |
| 719 | { |
| 720 | std::set<schanid_t>::iterator it; |
| 721 | |
| 722 | if (chan == nullptr) { |
| 723 | it = gli_channellist.begin(); |
| 724 | } else { |
| 725 | it = gli_channellist.find(chan); |
| 726 | if (it != gli_channellist.end()) { |
| 727 | ++it; |
| 728 | } |
| 729 | } |
| 730 | |
| 731 | if (it == gli_channellist.end()) { |
| 732 | if (rock != nullptr) { |
| 733 | *rock = 0; |
| 734 | } |
| 735 | |
| 736 | return nullptr; |
| 737 | } else { |
| 738 | if (rock != nullptr) { |
| 739 | *rock = (*it)->rock; |
| 740 | } |
| 741 | |
| 742 | return *it; |
| 743 | } |
| 744 | } |
| 745 | |
| 746 | glui32 glk_schannel_get_rock(schanid_t chan) |
| 747 | { |
| 748 | if (chan == nullptr) { |
| 749 | gli_strict_warning("schannel_get_rock: invalid id."); |
| 750 | return 0; |
| 751 | } |
| 752 | return chan->rock; |
| 753 | } |
| 754 | |
| 755 | glui32 glk_schannel_play(schanid_t chan, glui32 snd) |
| 756 | { |
| 757 | return glk_schannel_play_ext(chan, snd, 1, 0); |
| 758 | } |
| 759 | |
| 760 | glui32 glk_schannel_play_multi(schanid_t *chanarray, glui32 chancount, glui32 *sndarray, glui32 soundcount, glui32 notify) |
| 761 | { |
| 762 | glui32 successes = 0; |
| 763 | |
| 764 | for (glui32 i = 0; i < chancount; i++) { |
| 765 | successes += glk_schannel_play_ext(chanarray[i], sndarray[i], 1, notify); |
| 766 | } |
| 767 | |
| 768 | return successes; |
| 769 | } |
| 770 | |
| 771 | void glk_sound_load_hint(glui32 snd, glui32 flag) |
| 772 | { |
| 773 | } |
| 774 | |
| 775 | void glk_schannel_set_volume(schanid_t chan, glui32 vol) |
| 776 | { |
| 777 | glk_schannel_set_volume_ext(chan, vol, 0, 0); |
| 778 | } |
| 779 | |
| 780 | void glk_schannel_set_volume_ext(schanid_t chan, glui32 vol, glui32 duration, glui32 notify) |
| 781 | { |
| 782 | if (chan == nullptr) { |
| 783 | gli_strict_warning("schannel_set_volume: invalid id."); |
| 784 | return; |
| 785 | } |
| 786 | |
| 787 | if (vol > GLK_MAXVOLUME) { |
| 788 | vol = GLK_MAXVOLUME; |
| 789 | } |
| 790 | |
| 791 | chan->current_volume = chan->target_volume; |
| 792 | chan->target_volume = vol; |
| 793 | chan->volume_notify = notify; |
| 794 | |
| 795 | if (duration == 0) { |
| 796 | chan->current_volume = chan->target_volume; |
| 797 | chan->set_current_volume(); |
| 798 | } else { |
| 799 | chan->duration = duration / 1000.0; |
| 800 | chan->difference = static_cast<double>(chan->target_volume) - chan->current_volume; |
| 801 | chan->timer.start(100); |
| 802 | } |
| 803 | |
| 804 | chan->last_volume_bump = std::chrono::steady_clock::now(); |
| 805 | } |
| 806 | |
| 807 | static int detect_format(const std::vector<unsigned char> &data) |
| 808 | { |
| 809 | struct Magic { |
| 810 | virtual ~Magic() = default; |
| 811 | virtual bool matches(const std::vector<unsigned char> &data) const = 0; |
| 812 | }; |
| 813 | |
| 814 | struct MagicString : public Magic { |
| 815 | MagicString(qint64 offset, std::string string) : |
| 816 | m_offset(offset), |
| 817 | m_string(std::move(string)) |
| 818 | { |
| 819 | } |
| 820 | |
| 821 | bool matches(const std::vector<unsigned char> &data) const override { |
| 822 | if (m_offset + m_string.size() > data.size()) { |
| 823 | return false; |
| 824 | } |
| 825 | |
| 826 | return std::memcmp(&data[m_offset], m_string.data(), m_string.size()) == 0; |
| 827 | } |
| 828 | |
| 829 | private: |
| 830 | const qint64 m_offset; |
| 831 | const std::string m_string; |
| 832 | }; |
| 833 | |
| 834 | struct MagicMod : public Magic { |
| 835 | bool matches(const std::vector<unsigned char> &data) const override { |
| 836 | std::size_t size = std::min(openmpt_probe_file_header_get_recommended_size(), static_cast<std::size_t>(data.size())); |
| 837 | |
| 838 | return openmpt_probe_file_header(OPENMPT_PROBE_FILE_HEADER_FLAGS_DEFAULT, |
| 839 | data.data(), size, data.size(), |
| 840 | nullptr, nullptr, nullptr, nullptr, nullptr, nullptr) == OPENMPT_PROBE_FILE_HEADER_RESULT_SUCCESS; |
| 841 | } |
| 842 | }; |
| 843 | |
| 844 | std::vector<std::pair<std::shared_ptr<Magic>, int>> magics = { |
| 845 | {std::make_shared<MagicString>(0, "FORM"), giblorb_ID_FORM}, |
| 846 | {std::make_shared<MagicString>(0, "RIFF"), giblorb_ID_WAVE}, |
| 847 | {std::make_shared<MagicString>(0, "OggS"), giblorb_ID_OGG}, |
| 848 | {std::make_shared<MagicString>(0, "MThd"), giblorb_ID_MIDI}, |
| 849 | |
| 850 | {std::make_shared<MagicMod>(), giblorb_ID_MOD}, |
| 851 | |
| 852 | // ID3-tagged MP3s have a magic string, but untagged MP3 |
| 853 | // files don't, as they are just collections of frames, each |
| 854 | // with a sync header. All MP3 sync headers start with an |
| 855 | // 11-bit frame sync which is set to all ones. The next 4 |
| 856 | // bits can be anything except all zeros, and the bit |
| 857 | // following that can be 0 or 1, giving 6 possible values |
| 858 | // for the first 2 bytes of the frame. This may well have |
| 859 | // false positives, but mpg123 will then hopefully fail to |
| 860 | // load the file. |
| 861 | {std::make_shared<MagicString>(0, "ID3"), giblorb_ID_MP3}, |
| 862 | {std::make_shared<MagicString>(0, "\xff\xe2"), giblorb_ID_MP3}, |
| 863 | {std::make_shared<MagicString>(0, "\xff\xe3"), giblorb_ID_MP3}, |
| 864 | {std::make_shared<MagicString>(0, "\xff\xf2"), giblorb_ID_MP3}, |
| 865 | {std::make_shared<MagicString>(0, "\xff\xf3"), giblorb_ID_MP3}, |
| 866 | {std::make_shared<MagicString>(0, "\xff\xfa"), giblorb_ID_MP3}, |
| 867 | {std::make_shared<MagicString>(0, "\xff\xfb"), giblorb_ID_MP3}, |
| 868 | }; |
| 869 | |
| 870 | for (const auto &pair : magics) { |
| 871 | if (pair.first->matches(data)) { |
| 872 | return pair.second; |
| 873 | } |
| 874 | } |
| 875 | |
| 876 | throw SoundError("no matching magic"); |
| 877 | } |
| 878 | |
| 879 | static std::pair<int, std::vector<unsigned char>> load_bleep_resource(glui32 snd) |
| 880 | { |
| 881 | if (snd != 1 && snd != 2) { |
| 882 | throw SoundError("invalid bleep selected"); |
| 883 | } |
| 884 | |
| 885 | auto data = gli_bleeps.at(snd); |
| 886 | return {detect_format(data), data}; |
| 887 | } |
| 888 | |
| 889 | static std::pair<int, std::vector<unsigned char>> load_sound_resource(glui32 snd) |
| 890 | { |
| 891 | std::vector<unsigned char> data; |
| 892 | |
| 893 | if (giblorb_get_resource_map() != nullptr) { |
| 894 | glui32 type; |
| 895 | |
| 896 | if (!giblorb_copy_resource(giblorb_ID_Snd, snd, type, data)) { |
| 897 | throw SoundError("can't get blorb resource"); |
| 898 | } |
| 899 | |
| 900 | return std::make_pair(type, data); |
| 901 | } else { |
| 902 | const auto &resource_map = gli_get_resource_map(giblorb_ID_Snd); |
| 903 | if (!resource_map.empty()) { |
| 904 | try { |
| 905 | data = resource_map.at(snd); |
| 906 | } catch (const std::out_of_range &) { |
| 907 | throw SoundError("invalid resource"); |
| 908 | } |
| 909 | } else { |
| 910 | auto filename = Format("{}/SND{}", gli_workdir, snd); |
| 911 | |
| 912 | if (!garglk::read_file(filename, data)) { |
| 913 | throw SoundError("can't open SND file"); |
| 914 | } |
| 915 | } |
| 916 | |
| 917 | return {detect_format(data), data}; |
| 918 | } |
| 919 | } |
| 920 | |
| 921 | static glui32 gli_schannel_play_ext(schanid_t chan, glui32 snd, glui32 repeats, glui32 notify, const std::function<std::pair<int, std::vector<unsigned char>>(glui32)> &load_resource) |
| 922 | { |
| 923 | if (chan == nullptr) { |
| 924 | gli_strict_warning("schannel_play_ext: invalid id."); |
| 925 | return 0; |
| 926 | } |
| 927 | |
| 928 | glk_schannel_stop(chan); |
| 929 | |
| 930 | if (repeats == 0) { |
| 931 | return 1; |
| 932 | } |
| 933 | |
| 934 | std::shared_ptr<SoundSource> source; |
| 935 | try { |
| 936 | int type; |
| 937 | std::vector<unsigned char> data; |
| 938 | |
| 939 | std::tie(type, data) = load_resource(snd); |
| 940 | |
| 941 | try { |
| 942 | switch (type) { |
| 943 | case giblorb_ID_MOD: |
| 944 | source.reset(new OpenMPTSource(data, repeats)); |
| 945 | break; |
| 946 | case giblorb_ID_AIFF: |
| 947 | case giblorb_ID_FORM: |
| 948 | case giblorb_ID_OGG: |
| 949 | case giblorb_ID_WAVE: |
| 950 | source.reset(new SndfileSource(data, repeats)); |
| 951 | break; |
| 952 | case giblorb_ID_MP3: |
| 953 | source.reset(new Mpg123Source(data, repeats)); |
| 954 | break; |
| 955 | #ifdef GARGLK_HAS_FLUIDSYNTH |
| 956 | case giblorb_ID_MIDI: |
| 957 | source.reset(new FluidSynthSource(data, repeats)); |
| 958 | break; |
| 959 | #endif |
| 960 | default: |
| 961 | return 0; |
| 962 | } |
| 963 | } catch (const std::bad_alloc &) { |
| 964 | throw SoundError("unable to allocate"); |
| 965 | } |
| 966 | |
| 967 | if (!source->open(QIODevice::ReadOnly)) { |
| 968 | throw SoundError("unable to open source"); |
| 969 | } |
| 970 | |
| 971 | QAudioFormat format = source->format(); |
| 972 | #ifdef HAS_QT6 |
| 973 | auto device = QMediaDevices::defaultAudioOutput(); |
| 974 | if (!device.isFormatSupported(format)) { |
| 975 | throw SoundError("unsupported source format"); |
| 976 | } |
| 977 | |
| 978 | chan->audio = decltype(chan->audio)(new QAudioSink(device, format), [](QAudioSink *audio) { |
| 979 | if (!gli_exiting) { |
| 980 | delete audio; |
| 981 | } |
| 982 | }); |
| 983 | #else |
| 984 | QAudioDeviceInfo info(QAudioDeviceInfo::defaultOutputDevice()); |
| 985 | if (!info.isFormatSupported(format)) { |
| 986 | throw SoundError("unsupported source format"); |
| 987 | } |
| 988 | |
| 989 | chan->audio = decltype(chan->audio)(new QAudioOutput(format), [](QAudioOutput *audio) { |
| 990 | if (!gli_exiting) { |
| 991 | delete audio; |
| 992 | } |
| 993 | }); |
| 994 | #endif |
| 995 | chan->source = std::move(source); |
| 996 | |
| 997 | if (notify != 0) { |
| 998 | auto on_change = [snd, notify](QAudio::State state) { |
| 999 | if (state == QAudio::State::IdleState) { |
| 1000 | gli_event_store(evtype_SoundNotify, nullptr, snd, notify); |
| 1001 | gli_notification_waiting(); |
| 1002 | } |
| 1003 | }; |
| 1004 | |
| 1005 | #ifdef HAS_QT6 |
| 1006 | QObject::connect(chan->audio.get(), &QAudioSink::stateChanged, on_change); |
| 1007 | #else |
| 1008 | QObject::connect(chan->audio.get(), &QAudioOutput::stateChanged, on_change); |
| 1009 | #endif |
| 1010 | } |
| 1011 | |
| 1012 | chan->set_current_volume(); |
| 1013 | |
| 1014 | #ifdef HAS_QT6 |
| 1015 | // Need to initially provide a little bit of audio or QAudioSink will immediately stop playback. |
| 1016 | chan->source->set_audio_buffer_size(16384); |
| 1017 | #endif |
| 1018 | |
| 1019 | chan->audio->start(chan->source.get()); |
| 1020 | if (chan->audio->error() != QAudio::NoError) { |
| 1021 | throw SoundError("unable to start sound"); |
| 1022 | } |
| 1023 | |
| 1024 | chan->source->set_audio_buffer_size(chan->audio->bufferSize()); |
| 1025 | |
| 1026 | if (chan->paused) { |
| 1027 | chan->audio->suspend(); |
| 1028 | } |
| 1029 | |
| 1030 | return 1; |
| 1031 | } catch (const SoundError &) { |
| 1032 | return 0; |
| 1033 | } |
| 1034 | } |
| 1035 | |
| 1036 | glui32 glk_schannel_play_ext(schanid_t chan, glui32 snd, glui32 repeats, glui32 notify) |
| 1037 | { |
| 1038 | return gli_schannel_play_ext(chan, snd, repeats, notify, load_sound_resource); |
| 1039 | } |
| 1040 | |
| 1041 | void glk_schannel_pause(schanid_t chan) |
| 1042 | { |
| 1043 | if (chan == nullptr) { |
| 1044 | gli_strict_warning("schannel_pause: invalid id."); |
| 1045 | return; |
| 1046 | } |
| 1047 | |
| 1048 | chan->paused = true; |
| 1049 | |
| 1050 | if (chan->audio) { |
| 1051 | chan->audio->suspend(); |
| 1052 | } |
| 1053 | } |
| 1054 | |
| 1055 | void glk_schannel_unpause(schanid_t chan) |
| 1056 | { |
| 1057 | if (chan == nullptr) { |
| 1058 | gli_strict_warning("schannel_unpause: invalid id."); |
| 1059 | return; |
| 1060 | } |
| 1061 | |
| 1062 | chan->paused = false; |
| 1063 | |
| 1064 | if (chan->audio) { |
| 1065 | chan->audio->resume(); |
| 1066 | } |
| 1067 | } |
| 1068 | |
| 1069 | void glk_schannel_stop(schanid_t chan) |
| 1070 | { |
| 1071 | if (chan == nullptr) { |
| 1072 | gli_strict_warning("schannel_stop: invalid id."); |
| 1073 | return; |
| 1074 | } |
| 1075 | |
| 1076 | if (!chan->audio) { |
| 1077 | return; |
| 1078 | } |
| 1079 | |
| 1080 | // If Gargoyle is exiting, then Qt's audio backend may have already |
| 1081 | // been destroyed, meaning calling chan->audio functions can lead to |
| 1082 | // undefined behavior. Simply ignore this request in that case. |
| 1083 | if (!gli_exiting) { |
| 1084 | chan->audio->stop(); |
| 1085 | chan->timer.stop(); |
| 1086 | chan->audio.reset(nullptr); |
| 1087 | } |
| 1088 | } |
| 1089 | |
| 1090 | void garglk_zbleep(glui32 number) |
| 1091 | { |
| 1092 | if (gli_bleep_channel == nullptr) { |
| 1093 | gli_bleep_channel = glk_schannel_create(0); |
| 1094 | if (gli_bleep_channel != nullptr) { |
| 1095 | glk_schannel_set_volume(gli_bleep_channel, 0x8000); |
| 1096 | } |
| 1097 | } |
| 1098 | |
| 1099 | if (gli_bleep_channel != nullptr) { |
| 1100 | try { |
| 1101 | gli_schannel_play_ext(gli_bleep_channel, number, 1, 0, load_bleep_resource); |
| 1102 | } catch (const Bleeps::Empty &) { |
| 1103 | } |
| 1104 | } |
| 1105 | } |