Initial public OpenBMH 0.1 source (by Codex)
This commit is contained in:
commit
558fbf166b
613 files changed
+168029
No files matched your search
@@ -0,0 +1,26 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-only
|
||||
add_library(openbmh_audio STATIC container.cpp playback.cpp semantic_cues.cpp music_fallback.cpp mixer.cpp
|
||||
original.cpp third_party/nuked-opl3/opl3.c)
|
||||
target_include_directories(openbmh_audio PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
|
||||
target_link_libraries(openbmh_audio PUBLIC ${BMH_SDL_TARGET})
|
||||
|
||||
add_executable(openbmh_sound sound_driver.cpp)
|
||||
target_link_libraries(openbmh_sound PRIVATE openbmh_audio bmhcore)
|
||||
|
||||
add_executable(openbmh_original_audio_validation original_validation.cpp)
|
||||
target_link_libraries(openbmh_original_audio_validation PRIVATE openbmh_audio bmhcore)
|
||||
bmh_add_data_test(NAME openbmh_original_audio_validation COMMAND openbmh_original_audio_validation "${BMH_DATA}")
|
||||
set_tests_properties(openbmh_original_audio_validation PROPERTIES
|
||||
ENVIRONMENT "SDL_AUDIODRIVER=dummy;SDL_VIDEODRIVER=dummy")
|
||||
|
||||
add_executable(openbmh_audio_validation validation.cpp)
|
||||
target_link_libraries(openbmh_audio_validation PRIVATE openbmh_audio)
|
||||
add_test(NAME openbmh_audio_validation COMMAND openbmh_audio_validation)
|
||||
set_tests_properties(openbmh_audio_validation PROPERTIES ENVIRONMENT "SDL_AUDIODRIVER=dummy;SDL_VIDEODRIVER=dummy")
|
||||
|
||||
# SDL.h renames main to SDL_main on Windows: the two programs need SDL2main for the entry point
|
||||
if(TARGET SDL2::SDL2main)
|
||||
target_link_libraries(openbmh_sound PRIVATE SDL2::SDL2main)
|
||||
target_link_libraries(openbmh_audio_validation PRIVATE SDL2::SDL2main)
|
||||
target_link_libraries(openbmh_original_audio_validation PRIVATE SDL2::SDL2main)
|
||||
endif()
|
||||
@@ -0,0 +1,190 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#include "container.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <limits>
|
||||
|
||||
namespace openbmh::audio {
|
||||
namespace {
|
||||
std::uint32_t read_le32(std::span<const std::uint8_t> bytes, std::size_t at) {
|
||||
return static_cast<std::uint32_t>(bytes[at]) |
|
||||
(static_cast<std::uint32_t>(bytes[at + 1]) << 8) |
|
||||
(static_cast<std::uint32_t>(bytes[at + 2]) << 16) |
|
||||
(static_cast<std::uint32_t>(bytes[at + 3]) << 24);
|
||||
}
|
||||
}
|
||||
|
||||
bool parse_container(std::span<const std::uint8_t> bytes, Container& out,
|
||||
std::string& error) {
|
||||
out.chunks.clear();
|
||||
error.clear();
|
||||
if (bytes.size() < 16) {
|
||||
error = "truncated FORM/ALPTRAUM header";
|
||||
return false;
|
||||
}
|
||||
if (bytes[0] != 'F' || bytes[1] != 'O' || bytes[2] != 'R' || bytes[3] != 'M') {
|
||||
error = "missing FORM signature";
|
||||
return false;
|
||||
}
|
||||
if (std::string(bytes.begin() + 8, bytes.begin() + 16) != "ALPTRAUM") {
|
||||
error = "unsupported FORM type (expected ALPTRAUM)";
|
||||
return false;
|
||||
}
|
||||
const auto declared = read_le32(bytes, 4);
|
||||
if (declared != bytes.size() - 8 && declared != bytes.size()) {
|
||||
error = "FORM length does not match either observed ALPTRAUM convention";
|
||||
return false;
|
||||
}
|
||||
// The only observed full-file-size header is S/2003's SEFX variant. Keep
|
||||
// this exception tied to that exact, byte-verified layout; do not silently
|
||||
// accept it for the SONG/TRCK/PART music containers.
|
||||
const bool sefx_variant = declared == bytes.size() && bytes.size() == 65380 &&
|
||||
bytes[16] == 'H' && bytes[17] == 'E' && bytes[18] == 'D' && bytes[19] == 'R' &&
|
||||
bytes[32] == 'S' && bytes[33] == 'E' && bytes[34] == 'F' && bytes[35] == 'X';
|
||||
if (declared == bytes.size() && !sefx_variant) {
|
||||
error = "full-file FORM length is only established for the 2003 SEFX variant";
|
||||
return false;
|
||||
}
|
||||
|
||||
std::size_t at = 16;
|
||||
while (at < bytes.size()) {
|
||||
if (bytes.size() - at < 8) {
|
||||
error = "truncated chunk header";
|
||||
out.chunks.clear();
|
||||
return false;
|
||||
}
|
||||
const std::uint32_t size = read_le32(bytes, at + 4);
|
||||
const std::size_t payload = at + 8;
|
||||
if (size > bytes.size() - payload) {
|
||||
error = "chunk payload exceeds container bounds";
|
||||
out.chunks.clear();
|
||||
return false;
|
||||
}
|
||||
out.chunks.push_back({std::string(bytes.begin() + at, bytes.begin() + at + 4),
|
||||
payload, size});
|
||||
at = payload + size;
|
||||
}
|
||||
if (sefx_variant && (out.chunks.size() != 4 || out.chunks[0].id != "HEDR" ||
|
||||
out.chunks[1].id != "SEFX" || out.chunks[2].id != "INST" ||
|
||||
out.chunks[3].id != "SAMP" || out.chunks[0].payload_size != 8 ||
|
||||
out.chunks[1].payload_size != 212 || out.chunks[2].payload_size != 228 ||
|
||||
out.chunks[3].payload_size != 64884)) {
|
||||
error = "full-file FORM length does not match the observed 2003 SEFX chunk layout";
|
||||
out.chunks.clear();
|
||||
return false;
|
||||
}
|
||||
if (sefx_variant) {
|
||||
const auto& sefx = out.chunks[1];
|
||||
const auto payload = bytes.subspan(sefx.payload_offset, sefx.payload_size);
|
||||
const std::size_t records = (payload.size() - 4) / 16;
|
||||
if (payload[0] != 0 || payload[1] != 0 || payload[2] != 7 || payload[3] != 0 ||
|
||||
(payload.size() - 4) % 16 != 0 || records != 13) {
|
||||
error = "2003 SEFX prefix or fixed-record table is malformed";
|
||||
out.chunks.clear();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool decode_sample(std::span<const std::uint8_t> payload, std::size_t index,
|
||||
PcmSample& out, std::string& error) {
|
||||
out = {};
|
||||
error.clear();
|
||||
if (payload.size() < 4) { error = "truncated SAMP header"; return false; }
|
||||
const std::size_t count = static_cast<std::size_t>(payload[2]) |
|
||||
(static_cast<std::size_t>(payload[3]) << 8);
|
||||
constexpr std::size_t kRecordSize = 16;
|
||||
constexpr std::size_t kMaxSamples = 256;
|
||||
if (count > kMaxSamples || count > (payload.size() - 4) / kRecordSize) {
|
||||
error = "SAMP descriptor table exceeds payload bounds"; return false;
|
||||
}
|
||||
if (index >= count) { error = "sample index is outside the SAMP table"; return false; }
|
||||
const std::size_t data_offset = 4 + count * kRecordSize;
|
||||
const std::size_t record = 4 + index * kRecordSize;
|
||||
const std::uint32_t start = static_cast<std::uint32_t>(payload[record]) |
|
||||
(static_cast<std::uint32_t>(payload[record + 1]) << 8);
|
||||
const std::uint32_t length = static_cast<std::uint32_t>(payload[record + 2]) |
|
||||
(static_cast<std::uint32_t>(payload[record + 3]) << 8);
|
||||
const std::uint32_t rate = static_cast<std::uint32_t>(payload[record + 8]) |
|
||||
(static_cast<std::uint32_t>(payload[record + 9]) << 8);
|
||||
const std::size_t data_size = payload.size() - data_offset;
|
||||
if (length == 0 || start > data_size || length > data_size - start) {
|
||||
error = "SAMP sample span exceeds sample payload"; return false;
|
||||
}
|
||||
if (rate < 4000 || rate > 48000) {
|
||||
error = "unsupported SAMP sample rate"; return false;
|
||||
}
|
||||
out.sample_rate = rate;
|
||||
out.mono.reserve(length);
|
||||
const std::size_t first = data_offset + start;
|
||||
for (std::size_t i = 0; i < length; ++i) {
|
||||
out.mono.push_back(static_cast<std::int16_t>(
|
||||
(static_cast<int>(payload[first + i]) - 128) * 256));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool decode_original_cue(std::span<const std::uint8_t> bytes,
|
||||
std::uint8_t original_id, OriginalCue& out,
|
||||
std::string& error) {
|
||||
out = {};
|
||||
error.clear();
|
||||
if (original_id < 10 || original_id > 22) {
|
||||
error = "original SFX ID is outside the observed 10..22 dispatch range";
|
||||
return false;
|
||||
}
|
||||
Container container;
|
||||
if (!parse_container(bytes, container, error)) return false;
|
||||
const auto declared_form = read_le32(bytes, 4);
|
||||
if (bytes.size() != 65380 || declared_form != bytes.size() || container.chunks.size() != 4 ||
|
||||
container.chunks[0].id != "HEDR" || container.chunks[0].payload_size != 8 ||
|
||||
container.chunks[1].id != "SEFX" || container.chunks[1].payload_size != 212 ||
|
||||
container.chunks[2].id != "INST" || container.chunks[2].payload_size != 228 ||
|
||||
container.chunks[3].id != "SAMP" || container.chunks[3].payload_size != 64884) {
|
||||
error = "original cue decoding is limited to the exact observed 2003 SEFX bank";
|
||||
return false;
|
||||
}
|
||||
const auto find = [&container](const char* id) -> const Chunk* {
|
||||
const auto it = std::find_if(container.chunks.begin(), container.chunks.end(),
|
||||
[id](const Chunk& c) { return c.id == id; });
|
||||
return it == container.chunks.end() ? nullptr : &*it;
|
||||
};
|
||||
const Chunk* sefx = find("SEFX");
|
||||
const Chunk* samp = find("SAMP");
|
||||
if (!sefx || !samp) {
|
||||
error = "original cue needs both SEFX and SAMP chunks";
|
||||
return false;
|
||||
}
|
||||
const auto sefx_data = bytes.subspan(sefx->payload_offset, sefx->payload_size);
|
||||
constexpr std::size_t kPrefixBytes = 4;
|
||||
constexpr std::size_t kRecordBytes = 16;
|
||||
constexpr std::size_t kRecordCount = 13;
|
||||
if (sefx_data.size() != kPrefixBytes + kRecordBytes * kRecordCount ||
|
||||
sefx_data[0] != 0 || sefx_data[1] != 0 || sefx_data[2] != 7 || sefx_data[3] != 0) {
|
||||
error = "unsupported SEFX layout for original-cue lookup";
|
||||
return false;
|
||||
}
|
||||
// PauseMusic subtracts 10 before dispatch. Subspan indexes that
|
||||
// SEFX record; its type-9 records address the loaded sample slots 16..21.
|
||||
const std::size_t sefx_index = static_cast<std::size_t>(original_id - 10);
|
||||
const std::size_t record = kPrefixBytes + sefx_index * kRecordBytes;
|
||||
const std::uint8_t sample_slot = sefx_data[record];
|
||||
if (sefx_data[record + 1] != 9 || sample_slot < 16 || sample_slot > 21) {
|
||||
error = "original cue is not a directly decoded type-9 SAMP effect";
|
||||
return false;
|
||||
}
|
||||
const auto sample_index = static_cast<std::size_t>(sample_slot - 16);
|
||||
const auto samp_data = bytes.subspan(samp->payload_offset, samp->payload_size);
|
||||
if (samp_data[2] != 6 || samp_data[3] != 0) {
|
||||
error = "2003 SAMP table does not have the six observed entries";
|
||||
return false;
|
||||
}
|
||||
if (!decode_sample(samp_data, sample_index, out.pcm, error)) return false;
|
||||
out.original_id = original_id;
|
||||
out.sefx_index = static_cast<std::uint8_t>(sefx_index);
|
||||
out.sample_index = static_cast<std::uint8_t>(sample_index);
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace openbmh::audio
|
||||
@@ -0,0 +1,48 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <span>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace openbmh::audio {
|
||||
|
||||
struct Chunk {
|
||||
std::string id;
|
||||
std::size_t payload_offset{};
|
||||
std::size_t payload_size{};
|
||||
};
|
||||
|
||||
struct Container { std::vector<Chunk> chunks; };
|
||||
|
||||
struct PcmSample {
|
||||
std::uint32_t sample_rate{};
|
||||
std::vector<std::int16_t> mono;
|
||||
};
|
||||
|
||||
struct OriginalCue {
|
||||
std::uint8_t original_id{};
|
||||
std::uint8_t sefx_index{};
|
||||
std::uint8_t sample_index{};
|
||||
PcmSample pcm;
|
||||
};
|
||||
|
||||
// Parses the observed FORM/ALPTRAUM wrapper. Chunk lengths are little endian;
|
||||
// chunks are adjacent with no alignment byte. Payloads remain in the caller's buffer.
|
||||
bool parse_container(std::span<const std::uint8_t> bytes, Container& out,
|
||||
std::string& error);
|
||||
|
||||
// Converts one bounded SAMP sample span from unsigned 8-bit DMA data to signed
|
||||
// 16-bit mono PCM, using the rate stored in its 16-byte descriptor.
|
||||
bool decode_sample(std::span<const std::uint8_t> samp_payload, std::size_t index,
|
||||
PcmSample& out, std::string& error);
|
||||
|
||||
// Resolves only the observed PCM-backed SEFX effects (original IDs 17..22).
|
||||
// IDs 10..16 use the separate instrument path and remain unsupported here.
|
||||
bool decode_original_cue(std::span<const std::uint8_t> container_bytes,
|
||||
std::uint8_t original_id, OriginalCue& out,
|
||||
std::string& error);
|
||||
|
||||
} // namespace openbmh::audio
|
||||
@@ -0,0 +1,129 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#include "mixer.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <limits>
|
||||
|
||||
namespace openbmh::audio {
|
||||
namespace {
|
||||
constexpr std::size_t kMaxLoopBytes = 2U * 1024U * 1024U;
|
||||
constexpr std::size_t kMaxVoiceBytes = 2U * 1024U * 1024U;
|
||||
constexpr std::size_t kMaxPerVoiceBytes = kMaxVoiceBytes / 8;
|
||||
|
||||
bool convert_rate(std::span<const std::int16_t> input, std::uint32_t source_rate,
|
||||
std::uint32_t output_rate, std::size_t byte_limit,
|
||||
std::vector<std::int16_t>& output, std::string& error) {
|
||||
output.clear();
|
||||
if (input.empty() || source_rate < 4000 || source_rate > 192000 ||
|
||||
output_rate < 4000 || output_rate > 192000) {
|
||||
error = "invalid PCM rate or empty input";
|
||||
return false;
|
||||
}
|
||||
if (input.size() > (std::numeric_limits<std::uint64_t>::max() - source_rate / 2) /
|
||||
output_rate) {
|
||||
error = "PCM input size overflows sample-rate conversion";
|
||||
return false;
|
||||
}
|
||||
const auto count64 = (static_cast<std::uint64_t>(input.size()) * output_rate + source_rate / 2) /
|
||||
source_rate;
|
||||
if (!count64 || count64 > byte_limit / sizeof(std::int16_t) ||
|
||||
count64 > std::numeric_limits<std::size_t>::max()) {
|
||||
error = "converted PCM exceeds mixer buffer limit";
|
||||
return false;
|
||||
}
|
||||
const auto count = static_cast<std::size_t>(count64);
|
||||
output.resize(count);
|
||||
for (std::size_t i = 0; i < count; ++i) {
|
||||
const auto source_index = std::min(input.size() - 1,
|
||||
static_cast<std::size_t>((static_cast<std::uint64_t>(i) * source_rate + output_rate / 2) /
|
||||
output_rate));
|
||||
output[i] = input[source_index];
|
||||
}
|
||||
error.clear();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
bool Mixer::start_music_loop(const PcmSample& loop, std::uint32_t output_rate,
|
||||
std::string& error) {
|
||||
std::vector<std::int16_t> converted;
|
||||
if (!convert_rate(loop.mono, loop.sample_rate, output_rate, kMaxLoopBytes, converted, error))
|
||||
return false;
|
||||
music_ = std::move(converted);
|
||||
music_cursor_ = 0;
|
||||
error.clear();
|
||||
return true;
|
||||
}
|
||||
|
||||
void Mixer::stop_music() noexcept {
|
||||
music_.clear();
|
||||
music_cursor_ = 0;
|
||||
}
|
||||
|
||||
bool Mixer::add_voice(std::span<const std::int16_t> samples, std::uint32_t sample_rate,
|
||||
std::uint32_t output_rate, std::string& error) {
|
||||
std::vector<std::int16_t> converted;
|
||||
if (!convert_rate(samples, sample_rate, output_rate, kMaxPerVoiceBytes, converted, error))
|
||||
return false;
|
||||
if (converted.size() * sizeof(std::int16_t) > kMaxVoiceBytes - voice_bytes_) {
|
||||
error = "combined active cue voices exceed mixer buffer limit";
|
||||
return false;
|
||||
}
|
||||
const auto free_voice = std::find_if(voices_.begin(), voices_.end(),
|
||||
[](const Voice& voice) { return voice.cursor >= voice.samples.size(); });
|
||||
if (free_voice == voices_.end()) {
|
||||
error = "all fixed mixer cue voices are active";
|
||||
return false;
|
||||
}
|
||||
voice_bytes_ += converted.size() * sizeof(std::int16_t);
|
||||
free_voice->samples = std::move(converted);
|
||||
free_voice->cursor = 0;
|
||||
error.clear();
|
||||
return true;
|
||||
}
|
||||
|
||||
void Mixer::clear() noexcept {
|
||||
stop_music();
|
||||
for (auto& voice : voices_) {
|
||||
voice.samples.clear();
|
||||
voice.cursor = 0;
|
||||
}
|
||||
voice_bytes_ = 0;
|
||||
}
|
||||
|
||||
bool Mixer::active() const noexcept {
|
||||
return !music_.empty() || active_voices() != 0;
|
||||
}
|
||||
|
||||
std::size_t Mixer::active_voices() const noexcept {
|
||||
return static_cast<std::size_t>(std::count_if(voices_.begin(), voices_.end(),
|
||||
[](const Voice& voice) { return voice.cursor < voice.samples.size(); }));
|
||||
}
|
||||
|
||||
bool Mixer::mix_block(std::span<std::int16_t> output, float volume) noexcept {
|
||||
if (!active() || output.empty() || !std::isfinite(volume)) return false;
|
||||
const float bounded_volume = std::clamp(volume, 0.0F, 1.0F);
|
||||
for (auto& dst : output) {
|
||||
std::int32_t mixed = 0;
|
||||
if (!music_.empty()) {
|
||||
mixed += music_[music_cursor_++];
|
||||
if (music_cursor_ == music_.size()) music_cursor_ = 0;
|
||||
}
|
||||
for (auto& voice : voices_) {
|
||||
if (voice.cursor < voice.samples.size()) {
|
||||
mixed += voice.samples[voice.cursor++];
|
||||
if (voice.cursor == voice.samples.size()) {
|
||||
voice_bytes_ -= voice.samples.size() * sizeof(std::int16_t);
|
||||
voice.samples.clear();
|
||||
voice.cursor = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
const auto scaled = std::lround(static_cast<float>(mixed) * bounded_volume);
|
||||
dst = static_cast<std::int16_t>(std::clamp<long>(scaled, -32768, 32767));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace openbmh::audio
|
||||
@@ -0,0 +1,38 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#pragma once
|
||||
|
||||
#include "container.hpp"
|
||||
|
||||
#include <array>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <span>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace openbmh::audio {
|
||||
|
||||
// Small allocation-bounded PCM mixer. Setup/add_voice may allocate; mix_block
|
||||
// only reads its prepared buffers and writes into caller-owned storage.
|
||||
class Mixer {
|
||||
public:
|
||||
bool start_music_loop(const PcmSample& loop, std::uint32_t output_rate,
|
||||
std::string& error);
|
||||
void stop_music() noexcept;
|
||||
bool add_voice(std::span<const std::int16_t> samples, std::uint32_t sample_rate,
|
||||
std::uint32_t output_rate, std::string& error);
|
||||
void clear() noexcept;
|
||||
bool active() const noexcept;
|
||||
bool has_music() const noexcept { return !music_.empty(); }
|
||||
std::size_t active_voices() const noexcept;
|
||||
bool mix_block(std::span<std::int16_t> output, float volume) noexcept;
|
||||
|
||||
private:
|
||||
struct Voice { std::vector<std::int16_t> samples; std::size_t cursor{}; };
|
||||
std::vector<std::int16_t> music_;
|
||||
std::size_t music_cursor_{};
|
||||
std::array<Voice, 8> voices_{};
|
||||
std::size_t voice_bytes_{};
|
||||
};
|
||||
|
||||
} // namespace openbmh::audio
|
||||
@@ -0,0 +1,91 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#include "music_fallback.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
|
||||
namespace openbmh::audio {
|
||||
namespace {
|
||||
constexpr std::uint32_t kRate = 22050;
|
||||
constexpr std::uint32_t kBeatsPerMinute = 108;
|
||||
constexpr std::uint32_t kBars = 8;
|
||||
constexpr std::uint32_t kBeatsPerBar = 4;
|
||||
constexpr double kPi = 3.14159265358979323846;
|
||||
constexpr std::size_t kLoopFrames =
|
||||
static_cast<std::size_t>(kRate) * 60 * kBars * kBeatsPerBar / kBeatsPerMinute;
|
||||
|
||||
constexpr std::array<int, 4> kBassMidi{43, 38, 40, 36}; // G2, D2, E2, C2
|
||||
constexpr std::array<std::array<int, 3>, 4> kChordMidi{{
|
||||
{{55, 59, 62}}, // G major
|
||||
{{50, 54, 57}}, // D major
|
||||
{{52, 55, 59}}, // E minor
|
||||
{{48, 52, 55}}, // C major
|
||||
}};
|
||||
constexpr std::array<int, 16> kLeadMidi{
|
||||
67, 71, 74, 71, 69, 74, 78, 74,
|
||||
71, 76, 79, 76, 67, 72, 76, 72,
|
||||
};
|
||||
|
||||
double midi_hz(int midi) {
|
||||
return 440.0 * std::pow(2.0, static_cast<double>(midi - 69) / 12.0);
|
||||
}
|
||||
|
||||
std::int16_t clamp_sample(double value) {
|
||||
const auto rounded = static_cast<long>(std::lround(value));
|
||||
return static_cast<std::int16_t>(std::clamp(rounded, -32768L, 32767L));
|
||||
}
|
||||
}
|
||||
|
||||
bool synthesize_matchday_music_loop(PcmSample& out, std::string& error) {
|
||||
out = {};
|
||||
error.clear();
|
||||
out.sample_rate = kRate;
|
||||
out.mono.resize(kLoopFrames);
|
||||
|
||||
const double samples_per_beat = static_cast<double>(kRate) * 60.0 / kBeatsPerMinute;
|
||||
const std::size_t lead_gate = static_cast<std::size_t>(samples_per_beat * 0.72);
|
||||
const std::size_t fade_frames = kRate / 200; // 5 ms endpoint ramp for a clean loop seam.
|
||||
|
||||
for (std::size_t frame = 0; frame < kLoopFrames; ++frame) {
|
||||
const double beat_position = static_cast<double>(frame) / samples_per_beat;
|
||||
const auto bar = static_cast<std::size_t>(beat_position / kBeatsPerBar) % kBars;
|
||||
const double beat_fraction = std::fmod(beat_position, 1.0);
|
||||
const double bar_fraction = std::fmod(beat_position / kBeatsPerBar, 1.0);
|
||||
|
||||
const double bass_phase = 2.0 * kPi * midi_hz(kBassMidi[bar % 4]) * frame / kRate;
|
||||
const double bass_envelope = 0.78 + 0.22 * std::cos(kPi * beat_fraction);
|
||||
double mixed = 2600.0 * bass_envelope *
|
||||
(std::sin(bass_phase) + 0.18 * std::sin(2.0 * bass_phase));
|
||||
|
||||
const auto& chord = kChordMidi[bar % 4];
|
||||
const double pad_envelope = 0.58 + 0.16 * std::cos(2.0 * kPi * bar_fraction);
|
||||
for (std::size_t note = 0; note < chord.size(); ++note) {
|
||||
const double phase = 2.0 * kPi * midi_hz(chord[note]) * frame / kRate;
|
||||
mixed += 1350.0 * pad_envelope *
|
||||
(std::sin(phase) + 0.12 * std::sin(2.0 * phase));
|
||||
}
|
||||
|
||||
// A short eighth-note lead gives the loop a recognizable repeated motif.
|
||||
const auto step = static_cast<std::size_t>(beat_position * 2.0) % kLeadMidi.size();
|
||||
const double step_fraction = std::fmod(beat_position * 2.0, 1.0);
|
||||
const auto lead_elapsed = static_cast<std::size_t>(step_fraction * samples_per_beat / 2.0);
|
||||
if (lead_elapsed < lead_gate) {
|
||||
const double phase = 2.0 * kPi * midi_hz(kLeadMidi[step]) * lead_elapsed / kRate;
|
||||
const double attack = std::min(1.0, static_cast<double>(lead_elapsed) / (kRate / 160));
|
||||
const double release = std::min(1.0,
|
||||
static_cast<double>(lead_gate - lead_elapsed) / (kRate / 35));
|
||||
const double envelope = std::min(attack, release);
|
||||
mixed += 3600.0 * envelope *
|
||||
(std::sin(phase) + 0.22 * std::sin(2.0 * phase));
|
||||
}
|
||||
|
||||
const auto edge = std::min(frame, kLoopFrames - 1 - frame);
|
||||
const double seam_envelope = std::min(1.0, static_cast<double>(edge) / fade_frames);
|
||||
out.mono[frame] = clamp_sample(mixed * seam_envelope);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace openbmh::audio
|
||||
@@ -0,0 +1,14 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#pragma once
|
||||
|
||||
#include "container.hpp"
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace openbmh::audio {
|
||||
|
||||
// Builds an explicitly synthetic, deterministic 8-bar matchday loop. This is
|
||||
// presentation fallback material, not decoded original music or a Sound ID.
|
||||
bool synthesize_matchday_music_loop(PcmSample& out, std::string& error);
|
||||
|
||||
} // namespace openbmh::audio
|
||||
@@ -0,0 +1,468 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#include "original.hpp"
|
||||
#include "container.hpp"
|
||||
#include "third_party/nuked-opl3/opl3.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <stdexcept>
|
||||
|
||||
namespace openbmh::audio {
|
||||
namespace {
|
||||
using Bytes = std::span<const std::uint8_t>;
|
||||
std::uint16_t word(Bytes b, std::size_t at) {
|
||||
if (at > b.size() || b.size() - at < 2) throw std::runtime_error("truncated audio word");
|
||||
return std::uint16_t(b[at] | (unsigned(b[at + 1]) << 8));
|
||||
}
|
||||
std::uint32_t dword(Bytes b, std::size_t at) {
|
||||
return std::uint32_t(word(b, at)) | (std::uint32_t(word(b, at + 2)) << 16);
|
||||
}
|
||||
Bytes chunk(Bytes bytes, const Container& c, const char* name) {
|
||||
const Chunk* found = nullptr;
|
||||
for (const auto& p : c.chunks) if (p.id == name) {
|
||||
if (found) throw std::runtime_error("duplicate Original audio chunk");
|
||||
found = &p;
|
||||
}
|
||||
if (!found) throw std::runtime_error(std::string("missing Original audio chunk ") + name);
|
||||
return bytes.subspan(found->payload_offset, found->payload_size);
|
||||
}
|
||||
bool room(Bytes b, std::size_t at, std::size_t n) noexcept {
|
||||
return at <= b.size() && n <= b.size() - at;
|
||||
}
|
||||
}
|
||||
|
||||
struct OriginalSynth::State {
|
||||
struct Sample { Bytes data, loop; std::uint8_t time_constant{}; };
|
||||
struct Bank {
|
||||
std::vector<std::array<std::uint8_t, 32>> instruments;
|
||||
std::vector<Sample> samples;
|
||||
};
|
||||
struct Song : Bank {
|
||||
Bytes tracks, parts;
|
||||
std::array<std::size_t, 16> start{}, loop{};
|
||||
std::vector<std::size_t> patterns;
|
||||
std::uint16_t tempo{}, end{}, repeat{};
|
||||
};
|
||||
struct Track {
|
||||
std::size_t next{}, loop{}, cursor{};
|
||||
std::uint8_t tick{}, instrument{}, volume{}, transpose{}, first{}, end{}, channel{};
|
||||
bool active{};
|
||||
};
|
||||
struct Channel {
|
||||
std::uint8_t duration{}, instrument{255}, level{255}, high{}, reserved{}, release{255}, priority{};
|
||||
std::uint8_t modulator{}, carrier{};
|
||||
};
|
||||
OriginalAssets assets;
|
||||
std::array<Song, 3> songs;
|
||||
Bank effects;
|
||||
std::array<std::array<std::uint8_t, 16>, 13> sfx{};
|
||||
std::array<Track, 16> tracks{};
|
||||
std::array<Channel, 9> channels{};
|
||||
opl3_chip chip{};
|
||||
OriginalAudioOptions options;
|
||||
OriginalAudioStats stats;
|
||||
std::uint32_t rate{};
|
||||
std::uint64_t pit_phase{}, dma_phase{};
|
||||
Bytes dma;
|
||||
std::size_t dma_cursor{};
|
||||
std::uint8_t dma_constant{}, dma_priority{}, dma_slot{}, ambient_slot{255};
|
||||
bool dma_loop{}, dma_effect{}, dry{};
|
||||
unsigned tempo_tick{};
|
||||
std::function<void(std::uint8_t, std::uint8_t)> register_observer;
|
||||
std::function<void(std::uint8_t)> sample_observer;
|
||||
|
||||
void write(std::uint8_t reg, std::uint8_t value) noexcept {
|
||||
if (dry) return;
|
||||
++stats.register_writes;
|
||||
OPL3_WriteRegBuffered(&chip, reg, value);
|
||||
if (register_observer) register_observer(reg, value);
|
||||
}
|
||||
void reset_chip() noexcept {
|
||||
OPL3_Reset(&chip, rate);
|
||||
for (const auto [r, v] : std::array<std::pair<std::uint8_t, std::uint8_t>, 7>{{
|
||||
{1, 0x20}, {8, 0}, {2, 0}, {3, 0}, {4, 0x60}, {4, 0x80}, {0xbd, 0}}}) write(r, v);
|
||||
}
|
||||
static Bank read_bank(Bytes raw, const Container& container) {
|
||||
Bank bank;
|
||||
const auto inst = chunk(raw, container, "INST");
|
||||
const auto count = word(inst, 2);
|
||||
if (word(inst, 0) != 0 || count > 128 || inst.size() != 4u + 32u * count)
|
||||
throw std::runtime_error("invalid Original INST table");
|
||||
bank.instruments.resize(count);
|
||||
for (unsigned i = 0; i < count; ++i)
|
||||
std::copy_n(inst.begin() + 4 + i * 32, 32, bank.instruments[i].begin());
|
||||
const auto samp = chunk(raw, container, "SAMP");
|
||||
const auto n = word(samp, 2);
|
||||
if (word(samp, 0) != 0 || n > 16 || !room(samp, 4, std::size_t(n) * 16))
|
||||
throw std::runtime_error("invalid Original SAMP table");
|
||||
const auto data = samp.subspan(4 + n * 16);
|
||||
for (unsigned i = 0; i < n; ++i) {
|
||||
const auto desc = samp.subspan(4 + i * 16, 16);
|
||||
const auto begin = word(desc, 0), length = word(desc, 2);
|
||||
if (!length || !room(data, begin, length)) throw std::runtime_error("invalid Original sample span");
|
||||
Sample s{data.subspan(begin, length), {}, desc[11]};
|
||||
if (desc[10]) {
|
||||
const auto start = word(desc, 4), size = word(desc, 6);
|
||||
if (!size || !room(data, start, size)) throw std::runtime_error("invalid Original sample loop");
|
||||
s.loop = data.subspan(start, size);
|
||||
}
|
||||
bank.samples.push_back(s);
|
||||
}
|
||||
return bank;
|
||||
}
|
||||
bool parse(std::string& error) {
|
||||
for (unsigned i = 0; i < 4; ++i) {
|
||||
const Bytes raw = assets.containers[i];
|
||||
Container container;
|
||||
if (!parse_container(raw, container, error)) return false;
|
||||
const auto header = chunk(raw, container, "HEDR");
|
||||
if (header.size() != 8 || word(header, 0) != 1 || word(header, 2) != 0 ||
|
||||
word(header, 4) != 1 || word(header, 6) != 1)
|
||||
throw std::runtime_error("unsupported Original sound driver variant");
|
||||
auto bank = read_bank(raw, container);
|
||||
if (i == 3) {
|
||||
effects = std::move(bank);
|
||||
const auto fx = chunk(raw, container, "SEFX");
|
||||
if (fx.size() != 4 + sfx.size() * 16) throw std::runtime_error("invalid Original SEFX table");
|
||||
for (unsigned n = 0; n < sfx.size(); ++n) {
|
||||
std::copy_n(fx.begin() + 4 + n * 16, 16, sfx[n].begin());
|
||||
const auto& f = sfx[n];
|
||||
if (f[1] == 9) {
|
||||
if (f[0] < 16 || f[0] - 16 >= effects.samples.size())
|
||||
throw std::runtime_error("SEFX sample outside bank");
|
||||
} else if (f[1] >= 9 || !(f[0] & 128) || (f[0] & 127) >= effects.instruments.size() ||
|
||||
f[2] >= assets.tables.frequencies.size() || f[4] > 63)
|
||||
throw std::runtime_error("SEFX instrument, channel, note or level outside bank");
|
||||
}
|
||||
continue;
|
||||
}
|
||||
Song& song = songs[i];
|
||||
static_cast<Bank&>(song) = std::move(bank);
|
||||
const auto info = chunk(raw, container, "SONG");
|
||||
if (info.size() != 10 || word(info, 0) != 0) throw std::runtime_error("invalid Original SONG header");
|
||||
song.tempo = word(info, 4); song.end = word(info, 6); song.repeat = word(info, 8);
|
||||
if (!song.tempo || song.tempo > 1024 || !song.end || song.end > 8192 || song.repeat > song.end)
|
||||
throw std::runtime_error("invalid Original song timing");
|
||||
const auto tr = chunk(raw, container, "TRCK");
|
||||
if (word(tr, 0) != 0 || word(tr, 2) != 16 || tr.size() < 132)
|
||||
throw std::runtime_error("invalid Original TRCK table");
|
||||
song.tracks = tr.subspan(132);
|
||||
for (unsigned t = 0; t < 16; ++t) {
|
||||
song.start[t] = dword(tr, 4 + 4 * t); song.loop[t] = dword(tr, 68 + 4 * t);
|
||||
if (!room(song.tracks, song.start[t], 8) || !room(song.tracks, song.loop[t], 8))
|
||||
throw std::runtime_error("Original track pointer outside table");
|
||||
}
|
||||
const auto part = chunk(raw, container, "PART");
|
||||
const auto patterns = word(part, 2);
|
||||
if (word(part, 0) != 0 || !patterns || patterns > 256 || !room(part, 4, patterns * 4))
|
||||
throw std::runtime_error("invalid Original PART table");
|
||||
song.parts = part.subspan(4 + patterns * 4);
|
||||
for (unsigned p = 0; p < patterns; ++p) {
|
||||
const auto start = dword(part, 4 + p * 4);
|
||||
if (start >= song.parts.size()) throw std::runtime_error("Original pattern pointer outside table");
|
||||
song.patterns.push_back(start);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
void fail() noexcept { stats.failed = true; stats.playing = false; dma = {}; }
|
||||
void level(unsigned c, std::uint8_t value) noexcept {
|
||||
if (c >= 9 || value > 63) { fail(); return; }
|
||||
auto& ch = channels[c];
|
||||
if (ch.level == value) return;
|
||||
ch.level = value;
|
||||
// Uint8T5's 64x64 table, generated there at runtime.
|
||||
const auto scale = [value](std::uint8_t tl) {
|
||||
return std::uint8_t((tl & 0xc0) | (63 - (unsigned(value) * (64 - (tl & 63)) >> 6)));
|
||||
};
|
||||
write(assets.tables.operators[c] + 0x20, scale(ch.modulator));
|
||||
write(assets.tables.operators[c] + 0x23, scale(ch.carrier));
|
||||
}
|
||||
void instrument(unsigned c, std::uint8_t id) noexcept {
|
||||
if (c >= 9) { fail(); return; }
|
||||
const Bank& bank = id & 128 ? effects : songs[stats.song];
|
||||
if ((id & 127) >= bank.instruments.size()) { fail(); return; }
|
||||
auto& ch = channels[c]; ch.instrument = id;
|
||||
const auto& in = bank.instruments[id & 127];
|
||||
ch.modulator = in[2]; ch.carrier = in[3]; ch.level = 255;
|
||||
const unsigned op = assets.tables.operators[c];
|
||||
write(op, in[0]); write(op + 3, in[1]);
|
||||
write(op + 0x40, in[4]); write(op + 0x43, in[5]);
|
||||
write(op + 0x60, in[6]); write(op + 0x63, in[7]);
|
||||
write(op + 0xc0, in[8]); write(op + 0xc3, in[9]);
|
||||
write(0xc0 + c, in[10]);
|
||||
}
|
||||
void note(unsigned c, unsigned pitch, std::uint8_t volume) noexcept {
|
||||
if (c >= 9 || pitch >= assets.tables.frequencies.size()) { fail(); return; }
|
||||
write(0xb0 + c, 0);
|
||||
level(c, volume);
|
||||
const auto frequency = assets.tables.frequencies[pitch];
|
||||
channels[c].high = std::uint8_t(frequency >> 8);
|
||||
write(0xa0 + c, std::uint8_t(frequency)); write(0xb0 + c, std::uint8_t(frequency >> 8));
|
||||
}
|
||||
void start_sample(std::uint8_t slot, bool is_effect, std::uint8_t priority = 0) noexcept {
|
||||
const Bank* bank = nullptr;
|
||||
unsigned index = slot;
|
||||
if (slot >= 16) { bank = &effects; index -= 16; }
|
||||
else if (stats.song < 3) bank = &songs[stats.song];
|
||||
if (!bank || index >= bank->samples.size()) { fail(); return; }
|
||||
const auto& s = bank->samples[index];
|
||||
dma = s.loop.empty() ? s.data : s.loop;
|
||||
dma_loop = !s.loop.empty(); dma_cursor = 0; dma_phase = 0;
|
||||
dma_constant = s.time_constant; dma_effect = is_effect; dma_priority = priority; dma_slot = slot;
|
||||
if (dma_loop && is_effect) ambient_slot = slot;
|
||||
if (!dry) { ++stats.sample_starts; if (sample_observer) sample_observer(slot); }
|
||||
}
|
||||
void stop_effects() noexcept {
|
||||
for (unsigned c = 0; c < 9; ++c) if (channels[c].reserved) {
|
||||
level(c, 0); channels[c].reserved = 0;
|
||||
}
|
||||
dma = {}; dma_effect = false; ambient_slot = 255; stats.ambient = false;
|
||||
}
|
||||
void pause_music() noexcept {
|
||||
for (unsigned c = 0; c < 9; ++c) level(c, 0);
|
||||
stats.playing = false;
|
||||
dma = {};
|
||||
}
|
||||
void start_song(unsigned i, bool restart = false) noexcept {
|
||||
if (i >= 3) return;
|
||||
if (stats.song == i && !restart) { stats.playing = options.music; return; }
|
||||
pause_music(); stop_effects();
|
||||
// Effect resets only OriginalRuntimeField(duration)=0, a5540(instrument)=FF,
|
||||
// a5544(level)=FF and a5546(reserved)=0 at stride16. The cached high
|
||||
// frequency byte, release/priority and instrument levels survive.
|
||||
// Clearing high changes the first pending key-off after a song switch.
|
||||
for (auto& c : channels) {
|
||||
c.duration = 0; c.instrument = 255; c.level = 255; c.reserved = 0;
|
||||
}
|
||||
stats.song = i; stats.bar = 0; stats.step = 0; tempo_tick = 0;
|
||||
for (unsigned t = 0; t < 16; ++t) {
|
||||
tracks[t].active = false; tracks[t].next = songs[i].start[t]; tracks[t].loop = songs[i].loop[t];
|
||||
}
|
||||
stats.playing = options.music;
|
||||
}
|
||||
bool effect(std::uint8_t id) noexcept {
|
||||
if (id < 10 || id > 22 || !options.effects || (id <= 15 && !options.clicks)) return false;
|
||||
const auto& f = sfx[id - 10];
|
||||
if (f[1] == 9) {
|
||||
if (dma_effect && !dma.empty() && f[3] < dma_priority) return true;
|
||||
start_sample(f[0], true, f[3]);
|
||||
} else {
|
||||
auto& c = channels[f[1]];
|
||||
if (c.reserved && f[3] < c.priority) return true;
|
||||
c.reserved = f[5]; c.release = f[6]; c.priority = f[3];
|
||||
instrument(f[1], f[0]); note(f[1], f[2], f[4]);
|
||||
}
|
||||
return !stats.failed;
|
||||
}
|
||||
std::uint8_t song_level(std::uint8_t value) noexcept {
|
||||
// Source OriginalRuntimeField2=0x3f80 selects master127 in the 128x128 table.
|
||||
if (value > 127) { fail(); return 0; }
|
||||
return std::uint8_t((127u * (unsigned(value) + 1) >> 7) >> 1);
|
||||
}
|
||||
void music_step() noexcept {
|
||||
if (!stats.playing || stats.failed) return;
|
||||
const auto& song = songs[stats.song];
|
||||
if (stats.step == 0) {
|
||||
if (stats.bar == song.end) {
|
||||
if (song.end == song.repeat) { stats.playing = false; return; }
|
||||
for (auto& t : tracks) t.next = t.loop;
|
||||
stats.bar = song.repeat;
|
||||
}
|
||||
for (auto& t : tracks) {
|
||||
if (!room(song.tracks, t.next, 8)) { fail(); return; }
|
||||
const auto row = song.tracks.subspan(t.next, 8);
|
||||
const auto bar = unsigned(row[0]) | (unsigned(row[1]) << 8);
|
||||
if (bar != stats.bar) continue;
|
||||
t.active = true; t.tick = 0;
|
||||
if (row[2] != 255) t.instrument = row[2];
|
||||
if (row[3] != 255) t.volume = row[3];
|
||||
t.transpose = row[4]; t.first = row[6]; t.channel = t.first;
|
||||
t.end = std::uint8_t(t.first + row[7]);
|
||||
if (row[5] >= song.patterns.size() || (unsigned(&t - tracks.data()) != 9 &&
|
||||
(t.first >= 9 || t.end > 9 || t.end <= t.first))) { fail(); return; }
|
||||
t.cursor = song.patterns[row[5]]; t.next += 8;
|
||||
}
|
||||
}
|
||||
for (unsigned index = 0; index < tracks.size(); ++index) {
|
||||
auto& t = tracks[index];
|
||||
if (!t.active) continue;
|
||||
if (!room(song.parts, t.cursor, 1)) { fail(); return; }
|
||||
const auto time = song.parts[t.cursor];
|
||||
if (time == 255) { t.active = false; continue; }
|
||||
if (time == t.tick) {
|
||||
if (!room(song.parts, t.cursor, 2)) { fail(); return; }
|
||||
auto cursor = t.cursor + 2;
|
||||
const auto code = song.parts[t.cursor + 1];
|
||||
unsigned count = 1;
|
||||
if (code >= 128) {
|
||||
if (code & 0x40) {
|
||||
if (!room(song.parts, cursor, 1)) { fail(); return; }
|
||||
t.instrument = song.parts[cursor++];
|
||||
}
|
||||
if (code & 0x20) {
|
||||
if (!room(song.parts, cursor, 1)) { fail(); return; }
|
||||
t.volume = song.parts[cursor++];
|
||||
const auto value = song_level(t.volume);
|
||||
for (unsigned c = t.first; c < t.end; ++c) level(c, value);
|
||||
}
|
||||
count = code & 7;
|
||||
}
|
||||
for (unsigned n = 0; n < count; ++n) {
|
||||
if (!room(song.parts, cursor, code < 128 ? 1 : 2)) { fail(); return; }
|
||||
const auto pitch = code < 128 ? code : song.parts[cursor++];
|
||||
const auto duration = song.parts[cursor++];
|
||||
if (index == 9 && code < 128) {
|
||||
if (!dma_effect) start_sample(pitch, false);
|
||||
} else if (t.channel < 9) {
|
||||
auto& c = channels[t.channel];
|
||||
if (!c.reserved) {
|
||||
if (c.instrument != t.instrument) instrument(t.channel, t.instrument);
|
||||
c.duration = duration;
|
||||
note(t.channel, std::uint8_t(pitch + t.transpose), song_level(t.volume));
|
||||
}
|
||||
if (++t.channel == t.end) t.channel = t.first;
|
||||
} else { fail(); return; }
|
||||
}
|
||||
t.cursor = cursor;
|
||||
}
|
||||
++t.tick;
|
||||
}
|
||||
if (++stats.step == 16) { stats.step = 0; ++stats.bar; }
|
||||
}
|
||||
void tick() noexcept {
|
||||
++stats.ticks;
|
||||
if (stats.failed) return;
|
||||
// IRQ0 calls Write2 before Write/Write3.
|
||||
for (unsigned n = 0; n < 9; ++n) {
|
||||
auto& c = channels[n];
|
||||
if (c.reserved) {
|
||||
--c.reserved;
|
||||
if (c.release != 255 && --c.release == 255) write(0xb0 + n, c.high & 31);
|
||||
}
|
||||
}
|
||||
if (!stats.playing) return;
|
||||
if (tempo_tick == 0) {
|
||||
music_step();
|
||||
for (unsigned n = 0; n < 9; ++n) {
|
||||
auto& c = channels[n];
|
||||
if (c.duration != 255 && --c.duration == 255) write(0xb0 + n, c.high & 31);
|
||||
}
|
||||
}
|
||||
if (++tempo_tick == songs[stats.song].tempo) tempo_tick = 0;
|
||||
}
|
||||
};
|
||||
|
||||
OriginalSynth::OriginalSynth() = default;
|
||||
OriginalSynth::~OriginalSynth() = default;
|
||||
bool OriginalSynth::load(OriginalAssets assets, std::uint32_t rate, std::string& error) {
|
||||
error.clear();
|
||||
if (rate < 8000 || rate > 192000) { error = "invalid Original output rate"; return false; }
|
||||
std::array<bool, 256> used{};
|
||||
for (auto op : assets.tables.operators) {
|
||||
const bool valid = (op >= 0x20 && op <= 0x22) || (op >= 0x28 && op <= 0x2a) ||
|
||||
(op >= 0x30 && op <= 0x32);
|
||||
if (!valid || used[op]) { error = "invalid Original OPL operator table"; return false; }
|
||||
used[op] = true;
|
||||
}
|
||||
for (auto frequency : assets.tables.frequencies)
|
||||
if (!(frequency & 0x2000) || (frequency & 0xc000) || !(frequency & 0x3ff)) {
|
||||
error = "invalid Original OPL note table"; return false;
|
||||
}
|
||||
try {
|
||||
auto candidate = std::make_unique<State>();
|
||||
candidate->assets = std::move(assets); candidate->rate = rate;
|
||||
if (!candidate->parse(error)) return false;
|
||||
// Interpret two full passes before making foreign data visible to the
|
||||
// real-time callback. All runtime table accesses remain checked as well.
|
||||
candidate->dry = true;
|
||||
for (unsigned i = 0; i < 3; ++i) {
|
||||
candidate->start_song(i, true);
|
||||
const auto steps = unsigned(candidate->songs[i].end) * 32 + 1;
|
||||
for (unsigned n = 0; n < steps && candidate->stats.playing; ++n) candidate->music_step();
|
||||
if (candidate->stats.failed) throw std::runtime_error("invalid Original track/pattern event");
|
||||
}
|
||||
candidate->dry = false; candidate->stop_effects(); candidate->stats = {};
|
||||
candidate->tracks = {}; candidate->channels = {}; candidate->tempo_tick = 0;
|
||||
candidate->reset_chip();
|
||||
state_ = std::move(candidate);
|
||||
return true;
|
||||
} catch (const std::exception& e) { error = e.what(); return false; }
|
||||
}
|
||||
bool OriginalSynth::ready() const noexcept { return state_ && !state_->stats.failed; }
|
||||
void OriginalSynth::set_options(OriginalAudioOptions options) noexcept {
|
||||
if (!state_) return;
|
||||
auto& s = *state_;
|
||||
if (s.options.music && !options.music && s.stats.playing) s.pause_music();
|
||||
const bool resume = !s.options.music && options.music && s.stats.song < 3 && !s.stats.ambient;
|
||||
if (s.options.effects && !options.effects) s.stop_effects();
|
||||
s.options = options;
|
||||
if (resume) s.stats.playing = true;
|
||||
}
|
||||
bool OriginalSynth::command(std::uint8_t id) noexcept {
|
||||
if (!ready()) return false;
|
||||
auto& s = *state_;
|
||||
if (id < 3) {
|
||||
// PauseMusic -> PauseMusic2 pauses music/effects before either loading a
|
||||
// different song or PauseMusic3's same-song resume. Track cursors and
|
||||
// retained instrument/volume stay intact on the latter path.
|
||||
s.pause_music(); s.stop_effects(); s.start_song(id); return true;
|
||||
}
|
||||
if (id == 3) {
|
||||
if (s.stats.ambient) return true;
|
||||
s.pause_music(); s.stop_effects(); s.stats.ambient = true;
|
||||
if (s.options.effects) s.effect(22);
|
||||
return true;
|
||||
}
|
||||
if (id == 8) { stop(); return true; }
|
||||
if (id < 10 || id > 22) return false;
|
||||
// Source suppresses effects over the title song. The standalone direct
|
||||
// effect entry remains available for isolated decoding and verification.
|
||||
if (s.stats.song == 0) return true;
|
||||
return s.effect(id);
|
||||
}
|
||||
bool OriginalSynth::effect(std::uint8_t id) noexcept { return ready() && state_->effect(id); }
|
||||
void OriginalSynth::stop() noexcept {
|
||||
if (!state_) return;
|
||||
state_->pause_music(); state_->stop_effects();
|
||||
}
|
||||
void OriginalSynth::tick() noexcept { if (state_) state_->tick(); }
|
||||
void OriginalSynth::render(std::span<std::int16_t> output, float volume) noexcept {
|
||||
std::fill(output.begin(), output.end(), 0);
|
||||
if (!state_ || state_->stats.failed) return;
|
||||
auto& s = *state_;
|
||||
const auto gain = std::isfinite(volume) ? std::clamp(volume, 0.0F, 1.0F) : 0.0F;
|
||||
for (auto& value : output) {
|
||||
if (s.stats.failed) break;
|
||||
s.pit_phase += 1193180;
|
||||
const std::uint64_t period = std::uint64_t(s.rate) * 6554;
|
||||
if (s.pit_phase >= period) { s.pit_phase -= period; s.tick(); }
|
||||
std::int16_t pair[2]{};
|
||||
OPL3_GenerateResampled(&s.chip, pair);
|
||||
std::int32_t mixed = (std::int32_t(pair[0]) + pair[1]) / 2;
|
||||
if (!s.dma.empty()) {
|
||||
mixed += (int(s.dma[s.dma_cursor]) - 128) * 256;
|
||||
s.dma_phase += 1000000;
|
||||
const auto divisor = std::uint64_t(s.rate) * (256 - unsigned(s.dma_constant));
|
||||
while (s.dma_phase >= divisor && !s.dma.empty()) {
|
||||
s.dma_phase -= divisor;
|
||||
if (++s.dma_cursor == s.dma.size()) {
|
||||
if (s.dma_loop) s.dma_cursor = 0;
|
||||
else if (s.ambient_slot != 255) s.start_sample(s.ambient_slot, true, 64);
|
||||
else { s.dma = {}; s.dma_effect = false; }
|
||||
}
|
||||
}
|
||||
}
|
||||
value = std::int16_t(std::clamp<long>(std::lround(mixed * gain), -32768, 32767));
|
||||
++s.stats.frames;
|
||||
}
|
||||
}
|
||||
OriginalAudioStats OriginalSynth::stats() const noexcept { return state_ ? state_->stats : OriginalAudioStats{}; }
|
||||
void OriginalSynth::set_register_observer(std::function<void(std::uint8_t, std::uint8_t)> f) {
|
||||
if (state_) state_->register_observer = std::move(f);
|
||||
}
|
||||
void OriginalSynth::set_sample_observer(std::function<void(std::uint8_t)> f) {
|
||||
if (state_) state_->sample_observer = std::move(f);
|
||||
}
|
||||
|
||||
} // namespace openbmh::audio
|
||||
@@ -0,0 +1,66 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#pragma once
|
||||
|
||||
#include <array>
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <span>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace openbmh::audio {
|
||||
|
||||
// Read from the user's executable by the application. Audio does not know the
|
||||
// game state, filesystem layout, simulation clock, or random generators.
|
||||
struct OriginalTables {
|
||||
std::array<std::uint16_t, 96> frequencies{}; // Audio_OriginalAudioAssets_RuntimeField2, including key-on bits
|
||||
std::array<std::uint8_t, 9> operators{}; // Audio_OriginalAudioAssets_RuntimeField, stride16
|
||||
};
|
||||
struct OriginalAssets {
|
||||
std::array<std::vector<std::uint8_t>, 4> containers; // S/2000..2003
|
||||
OriginalTables tables;
|
||||
};
|
||||
struct OriginalAudioOptions {
|
||||
bool music = true;
|
||||
bool effects = true;
|
||||
bool clicks = true;
|
||||
};
|
||||
struct OriginalAudioStats {
|
||||
std::uint64_t ticks{}, register_writes{}, sample_starts{}, frames{};
|
||||
std::uint32_t bar{}, step{}, song = 255;
|
||||
bool playing{}, ambient{}, failed{};
|
||||
};
|
||||
|
||||
// The Original MIDILINK sequencer and one Sound Blaster PCM channel. IRQ0 uses
|
||||
// PIT divisor0x199a. SONG/TRCK/PART, OPL instruments, SFX priorities/lifetimes,
|
||||
// note durations, sample interruption and the looping crowd are Source-derived.
|
||||
// Loading owns/validates its inputs. render() allocates nothing and never blocks.
|
||||
class OriginalSynth {
|
||||
public:
|
||||
OriginalSynth();
|
||||
~OriginalSynth();
|
||||
OriginalSynth(const OriginalSynth&) = delete;
|
||||
OriginalSynth& operator=(const OriginalSynth&) = delete;
|
||||
bool load(OriginalAssets assets, std::uint32_t output_rate, std::string& error);
|
||||
bool ready() const noexcept;
|
||||
void set_options(OriginalAudioOptions options) noexcept;
|
||||
// Source dispatch IDs:0 title,1 desk,2 intro,3 crowd,8 stop,10..22 effects.
|
||||
bool command(std::uint8_t id) noexcept;
|
||||
// Direct SFX entry, also used by the standalone driver/oracle.
|
||||
bool effect(std::uint8_t id) noexcept;
|
||||
void stop() noexcept;
|
||||
void render(std::span<std::int16_t> output, float volume = 1.0F) noexcept;
|
||||
OriginalAudioStats stats() const noexcept;
|
||||
|
||||
// Deterministic hardware-independent probe: one Original IRQ0, not one game
|
||||
// tick. Optional observers are installed only by offline validation tools.
|
||||
void tick() noexcept;
|
||||
void set_register_observer(std::function<void(std::uint8_t, std::uint8_t)> observer);
|
||||
void set_sample_observer(std::function<void(std::uint8_t)> observer);
|
||||
private:
|
||||
struct State;
|
||||
std::unique_ptr<State> state_;
|
||||
};
|
||||
|
||||
} // namespace openbmh::audio
|
||||
@@ -0,0 +1,378 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#include "formats/executable_layout.hpp"
|
||||
#include "original.hpp"
|
||||
#include "playback.hpp"
|
||||
#include "container.hpp"
|
||||
#include "formats/le.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cstdint>
|
||||
#include <cstdlib>
|
||||
#include <filesystem>
|
||||
#include <functional>
|
||||
#include <iomanip>
|
||||
#include <iostream>
|
||||
#include <limits>
|
||||
#include <span>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
using namespace openbmh::audio;
|
||||
constexpr std::uint64_t kFnvOffset = 14695981039346656037ull;
|
||||
void require(bool value, const std::string& reason) {
|
||||
if (!value) throw std::runtime_error(reason);
|
||||
}
|
||||
OriginalAssets assets_from(const std::filesystem::path& data) {
|
||||
OriginalAssets assets;
|
||||
const auto exe = bmh::load_le(data / "BMH.exe");
|
||||
for (unsigned i = 0; i < 4; ++i)
|
||||
assets.containers[i] = bmh::read_file(data / "S" / std::to_string(2000 + i));
|
||||
for (unsigned i = 0; i < assets.tables.frequencies.size(); ++i)
|
||||
assets.tables.frequencies[i] = exe.u16(::bmh::layout::Audio_OriginalAudioAssets_RuntimeField2 + 2 * i);
|
||||
for (unsigned i = 0; i < assets.tables.operators.size(); ++i)
|
||||
assets.tables.operators[i] = exe.u8(::bmh::layout::Audio_OriginalAudioAssets_RuntimeField + 16 * i);
|
||||
return assets;
|
||||
}
|
||||
void load(OriginalSynth& synth, const OriginalAssets& assets) {
|
||||
std::string error;
|
||||
require(synth.load(assets, 22050, error), "load external Original audio: " + error);
|
||||
}
|
||||
struct TraceHash {
|
||||
std::uint64_t count{}, hash = kFnvOffset;
|
||||
void word(std::uint32_t value) {
|
||||
for (unsigned shift = 0; shift < 32; shift += 8)
|
||||
hash = (hash ^ ((value >> shift) & 255u)) * 1099511628211ull;
|
||||
}
|
||||
void sample(std::uint32_t tick, std::uint8_t slot) { ++count; word(tick); word(slot); }
|
||||
void reg(std::uint32_t tick, std::uint8_t index, std::uint8_t value) {
|
||||
++count; word(tick); word(index); word(value);
|
||||
}
|
||||
};
|
||||
struct Oracle {
|
||||
std::uint8_t id;
|
||||
unsigned ticks;
|
||||
std::uint64_t writes, register_hash, samples, sample_hash;
|
||||
};
|
||||
// Counts and FNV-1a hashes from the executed, unmodified Original x86 driver.
|
||||
// Canonical hash input: each observed column as little-endian u32, in order.
|
||||
// No Original audio bytes or register/sample sequences are embedded here.
|
||||
constexpr std::array<Oracle, 16> kOracle{{
|
||||
{0,60000,32348,0xcbca207bfd99aeb0ull,3266,0xadad438156972aa9ull},
|
||||
{1,70000,12223,0xa0fe3a8b449c366bull,3163,0x31cd0db01f7a3ed2ull},
|
||||
{2,2000,386,0x52ce4acd30052d42ull,21,0xed4a856bd0b5d9bbull},
|
||||
{10,100,15,0xa38ea2831340e69eull,0,kFnvOffset},
|
||||
{11,100,15,0x6842cc45dcb290c5ull,0,kFnvOffset},
|
||||
{12,100,15,0x2ad007b26f4116b8ull,0,kFnvOffset},
|
||||
{13,100,15,0xaa5fff83f44303f5ull,0,kFnvOffset},
|
||||
{14,100,15,0xea8efbf8811746beull,0,kFnvOffset},
|
||||
{15,100,15,0x89a307eb865aa83full,0,kFnvOffset},
|
||||
{16,100,15,0x23a80f34bb743d13ull,0,kFnvOffset},
|
||||
{17,100,0,kFnvOffset,1,0xa91d37acc4be70b5ull},
|
||||
{18,100,0,kFnvOffset,1,0x09228ba46e88b424ull},
|
||||
{19,100,0,kFnvOffset,1,0xe9128fbd7129e9d7ull},
|
||||
{20,100,0,kFnvOffset,1,0x4917e3b51af42d46ull},
|
||||
{21,100,0,kFnvOffset,1,0x2932878b6be77e71ull},
|
||||
{22,100,0,kFnvOffset,1,0x8937db8315b1c1e0ull},
|
||||
}};
|
||||
|
||||
void original_oracle(const OriginalAssets& assets) {
|
||||
for (const auto& expected : kOracle) {
|
||||
OriginalSynth synth; load(synth, assets);
|
||||
const bool song = expected.id < 3;
|
||||
if (song) require(synth.command(expected.id), "Original song command");
|
||||
TraceHash registers, samples;
|
||||
unsigned tick = 0, wraps = 0;
|
||||
auto previous_bar = synth.stats().bar;
|
||||
synth.set_register_observer([&](auto reg, auto value) { registers.reg(tick, reg, value); });
|
||||
synth.set_sample_observer([&](auto slot) { samples.sample(tick, slot); });
|
||||
if (!song) require(synth.effect(expected.id), "Original effect command");
|
||||
for (; tick < expected.ticks; ++tick) {
|
||||
synth.tick();
|
||||
const auto stats = synth.stats();
|
||||
if (stats.bar < previous_bar) ++wraps;
|
||||
previous_bar = stats.bar;
|
||||
}
|
||||
require(!synth.stats().failed && registers.count == expected.writes &&
|
||||
registers.hash == expected.register_hash && samples.count == expected.samples &&
|
||||
samples.hash == expected.sample_hash,
|
||||
"executed Original driver oracle mismatch for ID " + std::to_string(expected.id));
|
||||
if (expected.id < 2) require(wraps > 0, "looping Original song must traverse its repeat boundary");
|
||||
if (expected.id == 2) require(!synth.stats().playing, "finite intro must stop at its Original end");
|
||||
std::cout << (song ? "song " : "effect ") << unsigned(expected.id)
|
||||
<< " ticks=" << expected.ticks << " registers=" << registers.count
|
||||
<< " fnv=" << std::hex << registers.hash << std::dec
|
||||
<< " samples=" << samples.count << " fnv=" << std::hex << samples.hash << std::dec << '\n';
|
||||
}
|
||||
}
|
||||
|
||||
void transition_oracle(const OriginalAssets& assets) {
|
||||
// Executed Original x86: warm up 1000 IRQs, start direct effect16, switch
|
||||
// through legacy routine/legacy routine (different song), or legacy routine/721d9/72199
|
||||
// (same song); observe the following5000 IRQs. Only digests are retained.
|
||||
constexpr std::array<std::uint64_t, 9> writes{2469,364,386,1922,446,386,1922,364,0};
|
||||
constexpr std::array<std::uint64_t, 9> hashes{
|
||||
0xe0e4d6a8ce302b09ull,0xa7c86105f1e09e74ull,0x52ce4acd30052d42ull,
|
||||
0x2157ea8cf3b1f61eull,0x4d37e6aa0de33d57ull,0x52ce4acd30052d42ull,
|
||||
0x22ad1211c726b767ull,0x5ebdbbd8e9af9298ull,kFnvOffset};
|
||||
constexpr std::array<std::uint64_t, 9> starts{276,218,21,277,231,21,277,218,0};
|
||||
constexpr std::array<std::uint64_t, 9> sample_hashes{
|
||||
0x781b9195a1b85333ull,0x24d2a97d1a8511f9ull,0xed4a856bd0b5d9bbull,
|
||||
0x23b9f58978f6f974ull,0x7d674e527408da4dull,0xed4a856bd0b5d9bbull,
|
||||
0x23b9f58978f6f974ull,0x24d2a97d1a8511f9ull,kFnvOffset};
|
||||
for (unsigned previous = 0; previous < 3; ++previous) for (unsigned target = 0; target < 3; ++target) {
|
||||
OriginalSynth synth; load(synth, assets);
|
||||
require(synth.command(std::uint8_t(previous)), "transition warmup song");
|
||||
for (unsigned n = 0; n < 1000; ++n) synth.tick();
|
||||
require(synth.effect(16) && synth.command(std::uint8_t(target)), "transition effect and target");
|
||||
TraceHash registers, samples; unsigned tick = 0;
|
||||
synth.set_register_observer([&](auto reg, auto value) { registers.reg(tick, reg, value); });
|
||||
synth.set_sample_observer([&](auto slot) { samples.sample(tick, slot); });
|
||||
for (; tick < 5000; ++tick) synth.tick();
|
||||
const auto index = previous * 3 + target;
|
||||
require(!synth.stats().failed && registers.count == writes[index] && registers.hash == hashes[index] &&
|
||||
samples.count == starts[index] && samples.hash == sample_hashes[index],
|
||||
"Original song transition mismatch " + std::to_string(previous) + "->" + std::to_string(target));
|
||||
}
|
||||
std::cout << "transitions: all9 cross/same-song executed Original digests, including finite intro resume\n";
|
||||
}
|
||||
|
||||
std::size_t payload(const OriginalAssets& assets, unsigned bank, const char* name) {
|
||||
Container container; std::string error;
|
||||
require(parse_container(assets.containers[bank], container, error), "parse external chunk: " + error);
|
||||
for (const auto& chunk : container.chunks) if (chunk.id == name) return chunk.payload_offset;
|
||||
throw std::runtime_error("missing external chunk");
|
||||
}
|
||||
void put16(std::vector<std::uint8_t>& bytes, std::size_t at, unsigned value) {
|
||||
bytes.at(at) = std::uint8_t(value); bytes.at(at + 1) = std::uint8_t(value >> 8);
|
||||
}
|
||||
void malformed_inputs(const OriginalAssets& assets) {
|
||||
unsigned cases = 0;
|
||||
const auto rejected = [&](const std::function<void(OriginalAssets&)>& mutation) {
|
||||
auto malformed = assets; mutation(malformed);
|
||||
OriginalSynth synth; std::string error;
|
||||
require(!synth.load(std::move(malformed), 22050, error) && !error.empty() && !synth.ready(),
|
||||
"malformed Original asset must fail before callback exposure: case " + std::to_string(cases));
|
||||
++cases;
|
||||
};
|
||||
rejected([](auto& a) { a.containers[0].clear(); });
|
||||
rejected([](auto& a) { a.containers[1].pop_back(); });
|
||||
rejected([](auto& a) { a.tables.operators[0] = 255; });
|
||||
rejected([](auto& a) { a.tables.operators[1] = a.tables.operators[0]; });
|
||||
rejected([](auto& a) { a.tables.frequencies[0] = 0; });
|
||||
rejected([](auto& a) { a.tables.frequencies[1] &= ~0x2000u; });
|
||||
const auto song = payload(assets, 0, "SONG"), track = payload(assets, 0, "TRCK");
|
||||
const auto part = payload(assets, 0, "PART"), sample = payload(assets, 3, "SAMP");
|
||||
const auto effect = payload(assets, 3, "SEFX");
|
||||
rejected([&](auto& a) { put16(a.containers[0], song + 4, 0); });
|
||||
rejected([&](auto& a) { put16(a.containers[0], song + 8, 0xffff); });
|
||||
rejected([&](auto& a) { std::fill_n(a.containers[0].begin() + std::ptrdiff_t(track + 4), 4, 255); });
|
||||
rejected([&](auto& a) { std::fill_n(a.containers[0].begin() + std::ptrdiff_t(part + 4), 4, 255); });
|
||||
rejected([&](auto& a) {
|
||||
a.containers[3].at(sample + 4 + 10) = 1;
|
||||
put16(a.containers[3], sample + 4 + 4, 0xffff);
|
||||
put16(a.containers[3], sample + 4 + 6, 0xffff);
|
||||
});
|
||||
rejected([&](auto& a) { a.containers[3].at(effect + 4 + 2) = 255; });
|
||||
rejected([&](auto& a) { a.containers[3].at(effect + 4 + 1) = 10; });
|
||||
OriginalSynth synth; std::string error;
|
||||
require(!synth.load(assets, 7999, error) && !synth.load(assets, 192001, error), "output rate bounds");
|
||||
load(synth, assets);
|
||||
require(synth.command(1), "valid song after malformed cases");
|
||||
const auto before = synth.stats();
|
||||
auto malformed = assets; malformed.containers[0].clear();
|
||||
require(!synth.load(std::move(malformed), 22050, error) && synth.ready() &&
|
||||
synth.stats().register_writes == before.register_writes && synth.stats().song == before.song,
|
||||
"failed reload must retain the previous validated synthesizer");
|
||||
std::cout << "malformed: " << cases << " asset/table/span/loop cases plus rate and failed-reload bounds\n";
|
||||
}
|
||||
|
||||
bool nonzero(std::span<const std::int16_t> samples) {
|
||||
return std::any_of(samples.begin(), samples.end(), [](auto value) { return value != 0; });
|
||||
}
|
||||
void render_and_options(const OriginalAssets& assets) {
|
||||
for (unsigned id = 0; id <= 22; ++id) {
|
||||
if (id > 2 && id < 10) continue;
|
||||
OriginalSynth synth; load(synth, assets);
|
||||
require(id < 3 ? synth.command(std::uint8_t(id)) : synth.effect(std::uint8_t(id)), "render command");
|
||||
std::array<std::int16_t, 8192> pcm{}; synth.render(pcm);
|
||||
require(!synth.stats().failed && synth.stats().frames == pcm.size() && nonzero(pcm),
|
||||
"all Original songs/effects must produce bounded audible PCM: " + std::to_string(id));
|
||||
}
|
||||
OriginalSynth first, second, silent;
|
||||
load(first, assets); load(second, assets); load(silent, assets);
|
||||
require(first.command(1) && second.command(1) && silent.command(1), "streaming song setup");
|
||||
std::array<std::int16_t, 16384> a{}, b{}, zero{};
|
||||
first.render(a);
|
||||
for (std::size_t at = 0; at < b.size(); at += 97)
|
||||
second.render(std::span(b).subspan(at, std::min<std::size_t>(97, b.size() - at)));
|
||||
silent.render(zero, 0);
|
||||
require(a == b && nonzero(a) && !nonzero(zero) &&
|
||||
silent.stats().ticks == first.stats().ticks && silent.stats().frames == a.size(),
|
||||
"PCM continuation is callback-block independent; zero volume preserves sequencing");
|
||||
require(!first.command(255) && !first.effect(9) && !first.effect(23), "invalid command/effect bounds");
|
||||
require(first.command(0) && !first.command(255), "title suppression cannot accept invalid IDs");
|
||||
auto writes = first.stats().register_writes;
|
||||
require(first.command(16) && first.stats().register_writes == writes, "Source title suppresses game effects");
|
||||
first.stop();
|
||||
first.set_options({false, true, false});
|
||||
require(first.command(1) && !first.stats().playing, "music disabled independently");
|
||||
writes = first.stats().register_writes;
|
||||
require(!first.effect(10) && first.stats().register_writes == writes && first.effect(16),
|
||||
"click switch disables click ID10 while retaining non-click ID16");
|
||||
first.set_options({false, false, false});
|
||||
require(!first.effect(17), "effect option independently disabled");
|
||||
first.set_options({false, true, true});
|
||||
require(first.command(3) && first.stats().ambient, "Original crowd command starts loop");
|
||||
const auto starts = first.stats().sample_starts;
|
||||
first.set_options({true, true, true}); first.set_options({false, true, true});
|
||||
require(first.stats().ambient && first.stats().sample_starts == starts,
|
||||
"music option toggles cannot erase the Original crowd");
|
||||
first.render(a); require(nonzero(a) && first.stats().ambient, "bounded crowd render continues");
|
||||
first.stop(); require(!first.stats().playing && !first.stats().ambient, "stop clears all playback owners");
|
||||
std::cout << "render: 3 songs/13 effects, chunk continuity, volume0, switches, title gate and crowd loop\n";
|
||||
}
|
||||
|
||||
void pause_and_crowd_transitions(const OriginalAssets& assets) {
|
||||
OriginalSynth reference, paused; load(reference, assets); load(paused, assets);
|
||||
require(reference.command(1) && paused.command(1), "pause/resume desk setup");
|
||||
for (unsigned n = 0; n < 233; ++n) { reference.tick(); paused.tick(); }
|
||||
const auto cursor = paused.stats();
|
||||
paused.set_options({false, true, true});
|
||||
require(!paused.stats().playing, "music option pauses current song");
|
||||
for (unsigned n = 0; n < 71; ++n) paused.tick();
|
||||
require(paused.stats().bar == cursor.bar && paused.stats().step == cursor.step,
|
||||
"disabled music retains its bar/step cursor");
|
||||
paused.set_options({true, true, true});
|
||||
require(paused.stats().playing, "music option resumes current song");
|
||||
for (unsigned n = 0; n < 257; ++n) { reference.tick(); paused.tick(); }
|
||||
require(paused.stats().bar == reference.stats().bar && paused.stats().step == reference.stats().step,
|
||||
"music option resumes retained tempo phase and cursors");
|
||||
|
||||
OriginalSynth desk, crowd; load(desk, assets); load(crowd, assets);
|
||||
require(desk.command(1) && crowd.command(1), "crowd/desk setup");
|
||||
for (unsigned n = 0; n < 233; ++n) { desk.tick(); crowd.tick(); }
|
||||
require(crowd.command(3) && crowd.stats().ambient && !crowd.stats().playing, "crowd pauses desk");
|
||||
const auto before = crowd.stats();
|
||||
require(crowd.command(3) && crowd.stats().sample_starts == before.sample_starts,
|
||||
"same crowd command retains existing owner without restarting sample");
|
||||
for (unsigned n = 0; n < 71; ++n) crowd.tick();
|
||||
require(crowd.stats().bar == before.bar && crowd.stats().step == before.step,
|
||||
"crowd retains the paused song cursor");
|
||||
require(crowd.command(1) && !crowd.stats().ambient && crowd.stats().playing,
|
||||
"return to same desk song stops crowd and resumes music");
|
||||
for (unsigned n = 0; n < 257; ++n) { desk.tick(); crowd.tick(); }
|
||||
require(crowd.stats().bar == desk.stats().bar && crowd.stats().step == desk.stats().step &&
|
||||
crowd.stats().song == 1 && !crowd.stats().failed,
|
||||
"crowd to desk retains song/tempo cursor rather than restarting");
|
||||
std::cout << "pause/crowd: music off/on and crowd-to-desk retain song and tempo cursors\n";
|
||||
}
|
||||
|
||||
void effect_priorities(const OriginalAssets& assets) {
|
||||
const auto at = payload(assets, 3, "SEFX") + 4;
|
||||
const auto& bytes = assets.containers[3];
|
||||
unsigned pairs = 0;
|
||||
for (unsigned high = 0; high < 13; ++high) for (unsigned low = 0; low < 13; ++low) {
|
||||
const auto h = at + high * 16, l = at + low * 16;
|
||||
if (bytes[h + 1] != bytes[l + 1] || bytes[h + 3] <= bytes[l + 3] ||
|
||||
(bytes[h + 1] != 9 && bytes[h + 5] == 0)) continue;
|
||||
OriginalSynth synth; load(synth, assets);
|
||||
require(synth.effect(std::uint8_t(high + 10)), "start higher-priority Original effect");
|
||||
const auto before = synth.stats();
|
||||
require(synth.effect(std::uint8_t(low + 10)) &&
|
||||
synth.stats().register_writes == before.register_writes &&
|
||||
synth.stats().sample_starts == before.sample_starts,
|
||||
"lower-priority effect must not interrupt the active Original channel");
|
||||
OriginalSynth replacement; load(replacement, assets);
|
||||
require(replacement.effect(std::uint8_t(low + 10)), "start lower-priority Original effect");
|
||||
const auto old = replacement.stats();
|
||||
require(replacement.effect(std::uint8_t(high + 10)) &&
|
||||
(replacement.stats().register_writes > old.register_writes ||
|
||||
replacement.stats().sample_starts > old.sample_starts),
|
||||
"higher-priority effect must replace the active lower-priority channel");
|
||||
++pairs;
|
||||
}
|
||||
require(pairs != 0, "external bank must exercise actual priority pairs");
|
||||
std::cout << "priority: " << pairs << " actual competing high/low pairs retained correctly\n";
|
||||
}
|
||||
|
||||
void callback_and_lifecycle(const OriginalAssets& assets) {
|
||||
std::string error;
|
||||
{
|
||||
Playback playback;
|
||||
require(playback.initialize_original(assets, error), "SDL Original initialization: " + error);
|
||||
require(playback.available() && playback.original_ready() && !playback.needs_pump(), "callback mode owns audio");
|
||||
playback.reset_session(42);
|
||||
require(playback.play_original_id(1, error), "callback desk song");
|
||||
const auto initial = playback.original_stats();
|
||||
SDL_Delay(120); // Deliberately no pump, render, GUI step or simulation callback.
|
||||
const auto advanced = playback.original_stats();
|
||||
require(advanced.frames > initial.frames + 512 && advanced.ticks > initial.ticks &&
|
||||
advanced.playing && !advanced.failed && playback.queued_bytes() == 0,
|
||||
"SDL callback must continue throughout a blocked main thread");
|
||||
playback.set_volume(0);
|
||||
const auto quiet = playback.original_stats().frames; SDL_Delay(40);
|
||||
require(playback.original_stats().frames > quiet && playback.volume() == 0, "zero volume retains callback clock");
|
||||
playback.set_volume(1);
|
||||
playback.set_original_options({false, false, false});
|
||||
require(!playback.original_stats().playing, "saved music option reaches callback");
|
||||
const auto stopped = playback.original_stats().sample_starts;
|
||||
require(playback.play_original_id(17, error) && playback.original_stats().sample_starts == stopped,
|
||||
"disabled effects are a normal consumed refusal");
|
||||
playback.set_original_options({true, true, true});
|
||||
playback.set_muted(true);
|
||||
const auto muted = playback.original_stats().frames; SDL_Delay(40);
|
||||
require(playback.original_stats().frames == muted && !playback.original_stats().playing,
|
||||
"mute stops and freezes Original sequencing");
|
||||
require(playback.submit(CueRequest{42, 1, 17}, error) == CueStatus::muted, "muted event consumed");
|
||||
playback.set_muted(false);
|
||||
require(playback.submit(CueRequest{42, 1, 17}, error) == CueStatus::duplicate,
|
||||
"unmute cannot replay a consumed event");
|
||||
require(playback.submit(CueRequest{41, 2, 17}, error) == CueStatus::invalid, "stale session refused");
|
||||
require(playback.submit(CueRequest{42, 2, 17}, error) == CueStatus::queued, "real effect submitted");
|
||||
require(playback.submit(CueRequest{42, 3, 255}, error) == CueStatus::unsupported &&
|
||||
playback.submit(CueRequest{42, 3, 255}, error) == CueStatus::duplicate,
|
||||
"invalid command is rejected and its envelope remains consumed");
|
||||
playback.stop(); playback.reset_session(43);
|
||||
require(playback.submit(CueRequest{43, 1, 16}, error) == CueStatus::queued, "new session starts independent event sequence");
|
||||
playback.shutdown();
|
||||
require(!playback.available() && playback.submit(CueRequest{43, 2, 16}, error) == CueStatus::disabled,
|
||||
"shutdown closes device and consumes no-device events safely");
|
||||
require(playback.initialize_original(assets, error), "reinitialize after shutdown: " + error);
|
||||
require(playback.play_original_id(2, error), "reinitialized finite song");
|
||||
}
|
||||
const char* old = SDL_getenv("SDL_AUDIODRIVER");
|
||||
const std::string previous = old ? old : "dummy";
|
||||
SDL_setenv("SDL_AUDIODRIVER", "openbmh_intentionally_missing_driver", 1);
|
||||
Playback unavailable;
|
||||
const bool initialized = unavailable.initialize_original(assets, error);
|
||||
SDL_setenv("SDL_AUDIODRIVER", previous.c_str(), 1);
|
||||
require(!initialized && !unavailable.available() && !error.empty(), "unavailable device fails without crashing");
|
||||
require(unavailable.initialize_original(assets, error), "retry after no-device failure: " + error);
|
||||
unavailable.shutdown();
|
||||
std::cout << "callback: blocked-main continuity, volume0/mute/options, dedup, no-device, reinitialize/lifecycle\n";
|
||||
}
|
||||
}
|
||||
|
||||
int main(int argc, char** argv) try {
|
||||
if (argc != 2) return 2;
|
||||
if (!*argv[1]) {
|
||||
std::cout << "SKIP: external game audio not configured\n";
|
||||
return 77;
|
||||
}
|
||||
if (!*argv[1]) { std::cout << "SKIP: Original BMH_DATA not configured\n"; return 77; }
|
||||
const auto assets = assets_from(argv[1]);
|
||||
original_oracle(assets);
|
||||
transition_oracle(assets);
|
||||
malformed_inputs(assets);
|
||||
render_and_options(assets);
|
||||
pause_and_crowd_transitions(assets);
|
||||
effect_priorities(assets);
|
||||
callback_and_lifecycle(assets);
|
||||
return 0;
|
||||
} catch (const std::exception& error) {
|
||||
std::cerr << "Original audio validation: " << error.what() << '\n';
|
||||
return 1;
|
||||
}
|
||||
@@ -0,0 +1,318 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#include "playback.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <limits>
|
||||
#include <vector>
|
||||
|
||||
namespace openbmh::audio {
|
||||
namespace {
|
||||
struct AudioLock {
|
||||
SDL_AudioDeviceID device;
|
||||
explicit AudioLock(SDL_AudioDeviceID id) : device(id) { if (device) SDL_LockAudioDevice(device); }
|
||||
~AudioLock() { if (device) SDL_UnlockAudioDevice(device); }
|
||||
};
|
||||
constexpr std::uint32_t kQueueLimitBytes = 2U * 1024U * 1024U;
|
||||
constexpr std::uint32_t kOutputRate = 22050;
|
||||
constexpr std::size_t kPumpFrames = kOutputRate / 50; // 20 ms.
|
||||
constexpr std::uint32_t kPumpBlockBytes = static_cast<std::uint32_t>(kPumpFrames * 2);
|
||||
constexpr std::uint32_t kQueueHighWaterBytes = kPumpBlockBytes * 2; // 40 ms.
|
||||
}
|
||||
|
||||
Playback::~Playback() { shutdown(); }
|
||||
|
||||
bool Playback::initialize(std::string& error) {
|
||||
error.clear();
|
||||
if (device_) return true;
|
||||
if (!initialized_audio_ && SDL_InitSubSystem(SDL_INIT_AUDIO) != 0) {
|
||||
error = SDL_GetError();
|
||||
return false;
|
||||
}
|
||||
initialized_audio_ = true;
|
||||
SDL_AudioSpec wanted{};
|
||||
wanted.freq = static_cast<int>(kOutputRate);
|
||||
wanted.format = AUDIO_S16SYS;
|
||||
wanted.channels = 1;
|
||||
// 1024 frames at 22050 Hz exceed the entire 40 ms music queue. A small
|
||||
// device block lets the bounded queue cover 17/33 ms app pump intervals.
|
||||
wanted.samples = 256;
|
||||
if (original_mode_) {
|
||||
wanted.callback = original_callback;
|
||||
wanted.userdata = this;
|
||||
}
|
||||
device_ = SDL_OpenAudioDevice(nullptr, 0, &wanted, &obtained_, 0);
|
||||
if (!device_) {
|
||||
error = SDL_GetError();
|
||||
SDL_QuitSubSystem(SDL_INIT_AUDIO);
|
||||
initialized_audio_ = false;
|
||||
return false;
|
||||
}
|
||||
if (obtained_.format != AUDIO_S16SYS || obtained_.channels != 1) {
|
||||
error = "audio device did not provide mono S16 output";
|
||||
SDL_CloseAudioDevice(device_);
|
||||
device_ = 0;
|
||||
SDL_QuitSubSystem(SDL_INIT_AUDIO);
|
||||
initialized_audio_ = false;
|
||||
return false;
|
||||
}
|
||||
SDL_PauseAudioDevice(device_, 0);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool Playback::initialize_original(OriginalAssets assets, std::string& error) {
|
||||
// Asset parsing/preflight never runs inside a live audio callback.
|
||||
if (device_) {
|
||||
SDL_CloseAudioDevice(device_);
|
||||
device_ = 0;
|
||||
}
|
||||
mixer_.clear();
|
||||
if (!original_.load(std::move(assets), kOutputRate, error)) return false;
|
||||
original_.set_options(original_options_);
|
||||
original_mode_ = true;
|
||||
return initialize(error);
|
||||
}
|
||||
|
||||
void Playback::original_callback(void* userdata, Uint8* stream, int length) {
|
||||
auto& self = *static_cast<Playback*>(userdata);
|
||||
SDL_memset(stream, 0, size_t(length));
|
||||
if (length <= 0 || self.muted_) return;
|
||||
self.original_.render(std::span<std::int16_t>(reinterpret_cast<std::int16_t*>(stream),
|
||||
size_t(length) / sizeof(std::int16_t)), self.volume_);
|
||||
}
|
||||
|
||||
void Playback::set_original_options(OriginalAudioOptions options) noexcept {
|
||||
if (!original_mode_) return;
|
||||
AudioLock lock(device_);
|
||||
original_options_ = options;
|
||||
original_.set_options(options);
|
||||
}
|
||||
|
||||
bool Playback::original_ready() const noexcept {
|
||||
if (!original_mode_) return false;
|
||||
AudioLock lock(device_);
|
||||
return original_.ready();
|
||||
}
|
||||
|
||||
OriginalAudioStats Playback::original_stats() const noexcept {
|
||||
AudioLock lock(original_mode_ ? device_ : 0);
|
||||
return original_.stats();
|
||||
}
|
||||
|
||||
void Playback::shutdown() {
|
||||
stop();
|
||||
if (device_) {
|
||||
SDL_CloseAudioDevice(device_);
|
||||
device_ = 0;
|
||||
}
|
||||
if (initialized_audio_) {
|
||||
SDL_QuitSubSystem(SDL_INIT_AUDIO);
|
||||
initialized_audio_ = false;
|
||||
}
|
||||
}
|
||||
|
||||
void Playback::set_volume(float volume) noexcept {
|
||||
AudioLock lock(original_mode_ ? device_ : 0);
|
||||
if (std::isfinite(volume)) volume_ = std::clamp(volume, 0.0F, 1.0F);
|
||||
}
|
||||
|
||||
void Playback::set_muted(bool muted) noexcept {
|
||||
if (original_mode_) {
|
||||
AudioLock lock(device_);
|
||||
muted_ = muted;
|
||||
if (muted) original_.stop();
|
||||
return;
|
||||
}
|
||||
muted_ = muted;
|
||||
if (muted_) stop();
|
||||
}
|
||||
|
||||
std::uint32_t Playback::queued_bytes() const noexcept {
|
||||
if (original_mode_) return 0;
|
||||
return device_ ? SDL_GetQueuedAudioSize(device_) : 0;
|
||||
}
|
||||
|
||||
void Playback::stop() {
|
||||
if (original_mode_) {
|
||||
AudioLock lock(device_);
|
||||
original_.stop();
|
||||
return;
|
||||
}
|
||||
if (device_) SDL_ClearQueuedAudio(device_);
|
||||
mixer_.clear();
|
||||
}
|
||||
|
||||
bool Playback::start_music_loop(const PcmSample& loop, std::string& error) {
|
||||
error.clear();
|
||||
if (original_mode_) { error = "Original driver owns music playback"; return false; }
|
||||
if (!device_) { error = "audio device is unavailable"; return false; }
|
||||
if (obtained_.freq != static_cast<int>(kOutputRate) || obtained_.samples > 256) {
|
||||
error = "audio device block does not support the bounded music pump cadence";
|
||||
return false;
|
||||
}
|
||||
if (SDL_GetQueuedAudioSize(device_) > kQueueHighWaterBytes) {
|
||||
error = "cannot start music while the existing cue queue exceeds 40 ms";
|
||||
return false;
|
||||
}
|
||||
return mixer_.start_music_loop(loop, static_cast<std::uint32_t>(obtained_.freq), error);
|
||||
}
|
||||
|
||||
void Playback::stop_music() noexcept {
|
||||
if (original_mode_) {
|
||||
AudioLock lock(device_);
|
||||
original_options_.music = false;
|
||||
original_.set_options(original_options_);
|
||||
return;
|
||||
}
|
||||
mixer_.stop_music();
|
||||
}
|
||||
|
||||
bool Playback::pump(std::string& error) {
|
||||
error.clear();
|
||||
if (original_mode_) return available();
|
||||
if (!device_) { error = "audio device is unavailable"; return false; }
|
||||
if (muted_ || !mixer_.active()) return false;
|
||||
|
||||
std::array<std::int16_t, kPumpFrames> block{};
|
||||
auto enqueue_up_to_20ms = [&]() {
|
||||
const auto queued = SDL_GetQueuedAudioSize(device_);
|
||||
if (queued >= kQueueHighWaterBytes) return false;
|
||||
const auto room_frames = (kQueueHighWaterBytes - queued) / sizeof(std::int16_t);
|
||||
const auto frames = std::min<std::size_t>(kPumpFrames, room_frames);
|
||||
if (!frames || !mixer_.mix_block(std::span<std::int16_t>(block.data(), frames), volume_))
|
||||
return false;
|
||||
const auto bytes = static_cast<std::uint32_t>(frames * sizeof(std::int16_t));
|
||||
if (SDL_QueueAudio(device_, block.data(), bytes) != 0) {
|
||||
error = SDL_GetError();
|
||||
mixer_.clear();
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
// Fill toward the 40 ms high-water mark. Two fixed, bounded calls let a
|
||||
// 30 Hz main loop catch up without busy waiting or allocating in pump().
|
||||
const bool first = enqueue_up_to_20ms();
|
||||
if (!first || !mixer_.active()) return first;
|
||||
enqueue_up_to_20ms();
|
||||
return error.empty();
|
||||
}
|
||||
|
||||
void Playback::reset_session(std::uint64_t session_id) noexcept {
|
||||
if (session_id == session_id_) return;
|
||||
stop();
|
||||
session_id_ = session_id;
|
||||
last_event_id_ = 0;
|
||||
}
|
||||
|
||||
CueStatus Playback::consume_event(std::uint64_t session_id, std::uint64_t event_id,
|
||||
std::string& detail) {
|
||||
detail.clear();
|
||||
if (!session_id_ || session_id != session_id_ || event_id == 0) {
|
||||
detail = "invalid or stale audio event envelope";
|
||||
return CueStatus::invalid;
|
||||
}
|
||||
if (event_id <= last_event_id_) return CueStatus::duplicate;
|
||||
last_event_id_ = event_id;
|
||||
if (muted_) return CueStatus::muted;
|
||||
if (!device_) return CueStatus::disabled;
|
||||
return CueStatus::queued;
|
||||
}
|
||||
|
||||
CueStatus Playback::submit(CueRequest request, std::string& detail) {
|
||||
const auto gate = consume_event(request.session_id, request.event_id, detail);
|
||||
if (gate != CueStatus::queued) return gate;
|
||||
if (!play_original_id(request.original_id, detail)) return CueStatus::unsupported;
|
||||
return CueStatus::queued;
|
||||
}
|
||||
|
||||
CueStatus Playback::submit(SemanticCueRequest request, std::string& detail) {
|
||||
const auto gate = consume_event(request.session_id, request.event_id, detail);
|
||||
if (gate != CueStatus::queued) return gate;
|
||||
if (!play_semantic_cue(request.cue, detail)) return CueStatus::unsupported;
|
||||
return CueStatus::queued;
|
||||
}
|
||||
|
||||
bool Playback::load_original_bank(std::span<const std::uint8_t> bytes,
|
||||
std::string& error) {
|
||||
std::array<std::optional<PcmSample>, 13> decoded{};
|
||||
for (std::uint8_t id = 17; id <= 22; ++id) {
|
||||
OriginalCue cue;
|
||||
if (!decode_original_cue(bytes, id, cue, error)) return false;
|
||||
decoded[static_cast<std::size_t>(id - 10)] = std::move(cue.pcm);
|
||||
}
|
||||
stop();
|
||||
original_cues_ = std::move(decoded);
|
||||
error.clear();
|
||||
return true;
|
||||
}
|
||||
|
||||
bool Playback::play_pcm(const std::int16_t* samples, std::size_t count,
|
||||
std::uint32_t sample_rate, std::string& error) {
|
||||
error.clear();
|
||||
if (original_mode_) { error = "Original driver does not queue synthetic PCM"; return false; }
|
||||
if (!device_) { error = "audio device is unavailable"; return false; }
|
||||
if (muted_ || volume_ == 0.0F) return true;
|
||||
if (!samples || !count || sample_rate < 4000 || sample_rate > 192000) {
|
||||
error = "invalid PCM input"; return false;
|
||||
}
|
||||
if (mixer_.active()) {
|
||||
return mixer_.add_voice(std::span<const std::int16_t>(samples, count), sample_rate,
|
||||
static_cast<std::uint32_t>(obtained_.freq), error);
|
||||
}
|
||||
if (count > std::numeric_limits<std::uint32_t>::max() / sizeof(std::int16_t)) {
|
||||
error = "PCM input is too large"; return false;
|
||||
}
|
||||
const std::uint64_t output_count64 =
|
||||
(static_cast<std::uint64_t>(count) * obtained_.freq + sample_rate / 2) / sample_rate;
|
||||
if (output_count64 == 0 || output_count64 > kQueueLimitBytes / sizeof(std::int16_t)) {
|
||||
error = "PCM input exceeds the bounded playback buffer"; return false;
|
||||
}
|
||||
const auto output_count = static_cast<std::size_t>(output_count64);
|
||||
const auto queued = SDL_GetQueuedAudioSize(device_);
|
||||
if (queued > kQueueLimitBytes - output_count * sizeof(std::int16_t)) {
|
||||
error = "playback queue is full"; return false;
|
||||
}
|
||||
std::vector<std::int16_t> converted(output_count);
|
||||
for (std::size_t i = 0; i < output_count; ++i) {
|
||||
const std::uint64_t numerator = static_cast<std::uint64_t>(i) * sample_rate;
|
||||
const auto source_index = std::min<std::size_t>(count - 1,
|
||||
static_cast<std::size_t>((numerator + obtained_.freq / 2) / obtained_.freq));
|
||||
const auto scaled = std::lround(static_cast<float>(samples[source_index]) * volume_);
|
||||
converted[i] = static_cast<std::int16_t>(std::clamp<long>(scaled, -32768, 32767));
|
||||
}
|
||||
const auto bytes = static_cast<std::uint32_t>(converted.size() * sizeof(std::int16_t));
|
||||
if (SDL_QueueAudio(device_, converted.data(), bytes) != 0) {
|
||||
error = SDL_GetError(); return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool Playback::play_original_id(std::uint8_t id, std::string& error) {
|
||||
if (original_mode_) {
|
||||
error.clear();
|
||||
if (!device_) { error = "audio device is unavailable"; return false; }
|
||||
AudioLock lock(device_);
|
||||
if (muted_) return true;
|
||||
if (original_.command(id)) return true;
|
||||
// Disabled Original options are normal refusals, not decoder errors.
|
||||
if (id >= 10 && id <= 22 && original_.ready()) return true;
|
||||
error = "invalid Original sound command or failed sound driver";
|
||||
return false;
|
||||
}
|
||||
error.clear();
|
||||
if (id < 10 || id > 22 || !original_cues_[static_cast<std::size_t>(id - 10)]) {
|
||||
error = "original Sound ID has no decoded PCM cue (IDs 10..16 use unsupported instruments)";
|
||||
return false;
|
||||
}
|
||||
const auto& pcm = *original_cues_[static_cast<std::size_t>(id - 10)];
|
||||
return play_pcm(pcm.mono.data(), pcm.mono.size(), pcm.sample_rate, error);
|
||||
}
|
||||
|
||||
bool Playback::play_semantic_cue(SemanticCue cue, std::string& error) {
|
||||
PcmSample pcm;
|
||||
if (!synthesize_semantic_cue(cue, pcm, error)) return false;
|
||||
return play_pcm(pcm.mono.data(), pcm.mono.size(), pcm.sample_rate, error);
|
||||
}
|
||||
|
||||
} // namespace openbmh::audio
|
||||
@@ -0,0 +1,100 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#pragma once
|
||||
|
||||
#include "container.hpp"
|
||||
#include "mixer.hpp"
|
||||
#include "semantic_cues.hpp"
|
||||
#include "original.hpp"
|
||||
|
||||
#include <SDL.h>
|
||||
#include <array>
|
||||
#include <cstdint>
|
||||
#include <optional>
|
||||
#include <span>
|
||||
#include <string>
|
||||
|
||||
namespace openbmh::audio {
|
||||
|
||||
struct CueRequest {
|
||||
std::uint64_t session_id{};
|
||||
std::uint64_t event_id{};
|
||||
std::uint8_t original_id{};
|
||||
};
|
||||
|
||||
struct SemanticCueRequest {
|
||||
std::uint64_t session_id{};
|
||||
std::uint64_t event_id{};
|
||||
SemanticCue cue{};
|
||||
};
|
||||
|
||||
enum class CueStatus { queued, muted, disabled, duplicate, unsupported, invalid };
|
||||
|
||||
class Playback {
|
||||
public:
|
||||
Playback() = default;
|
||||
~Playback();
|
||||
Playback(const Playback&) = delete;
|
||||
Playback& operator=(const Playback&) = delete;
|
||||
|
||||
bool initialize(std::string& error);
|
||||
// Full Original driver, streamed by SDL's audio callback so synchronous
|
||||
// simulation and modal windows cannot starve music or the crowd loop.
|
||||
bool initialize_original(OriginalAssets assets, std::string& error);
|
||||
bool original_ready() const noexcept;
|
||||
void set_original_options(OriginalAudioOptions options) noexcept;
|
||||
OriginalAudioStats original_stats() const noexcept;
|
||||
void shutdown();
|
||||
bool available() const noexcept { return device_ != 0; }
|
||||
void set_muted(bool muted) noexcept;
|
||||
bool muted() const noexcept { return muted_; }
|
||||
std::uint32_t queued_bytes() const noexcept;
|
||||
void set_volume(float volume) noexcept;
|
||||
float volume() const noexcept { return volume_; }
|
||||
void stop();
|
||||
|
||||
// Optional software music. It is off by default. pump() adds at most two
|
||||
// bounded blocks of up to 20 ms; total queued audio stays at or below 40 ms.
|
||||
// Music requires 22050 Hz and a device block no larger than 256 frames.
|
||||
bool start_music_loop(const PcmSample& loop, std::string& error);
|
||||
void stop_music() noexcept;
|
||||
bool music_active() const noexcept { return mixer_.has_music(); }
|
||||
bool needs_pump() const noexcept { return !original_mode_ && mixer_.active(); }
|
||||
bool pump(std::string& error);
|
||||
|
||||
// The controller supplies stable session/event identities. IDs are not
|
||||
// generated by audio; requests are consumed once in increasing event order.
|
||||
void reset_session(std::uint64_t session_id) noexcept;
|
||||
CueStatus submit(CueRequest request, std::string& detail);
|
||||
CueStatus submit(SemanticCueRequest request, std::string& detail);
|
||||
|
||||
// Legacy PCM-only bank loader. initialize_original provides the complete
|
||||
// sequencer and instrument path for songs and all effects 10..22.
|
||||
bool load_original_bank(std::span<const std::uint8_t> bytes, std::string& error);
|
||||
|
||||
// Plays caller-supplied mono S16 native-endian PCM. A 2 MiB queue ceiling
|
||||
// prevents a caller from accumulating unbounded playback. This is a backend
|
||||
// primitive, not an original Sound ID mapping.
|
||||
bool play_pcm(const std::int16_t* samples, std::size_t count,
|
||||
std::uint32_t sample_rate, std::string& error);
|
||||
bool play_original_id(std::uint8_t id, std::string& error);
|
||||
bool play_semantic_cue(SemanticCue cue, std::string& error);
|
||||
|
||||
private:
|
||||
static void original_callback(void* userdata, Uint8* stream, int length);
|
||||
CueStatus consume_event(std::uint64_t session_id, std::uint64_t event_id,
|
||||
std::string& detail);
|
||||
SDL_AudioDeviceID device_{};
|
||||
SDL_AudioSpec obtained_{};
|
||||
bool initialized_audio_{};
|
||||
bool muted_{};
|
||||
float volume_{1.0F};
|
||||
std::uint64_t session_id_{};
|
||||
std::uint64_t last_event_id_{};
|
||||
std::array<std::optional<PcmSample>, 13> original_cues_{};
|
||||
Mixer mixer_;
|
||||
OriginalSynth original_;
|
||||
bool original_mode_{};
|
||||
OriginalAudioOptions original_options_;
|
||||
};
|
||||
|
||||
} // namespace openbmh::audio
|
||||
@@ -0,0 +1,78 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#include "semantic_cues.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
|
||||
namespace openbmh::audio {
|
||||
namespace {
|
||||
constexpr std::uint32_t kSampleRate = 22050;
|
||||
constexpr double kPi = 3.14159265358979323846;
|
||||
|
||||
std::int16_t clamp_pcm(double value) {
|
||||
const auto rounded = static_cast<long>(std::lround(value));
|
||||
return static_cast<std::int16_t>(std::clamp(rounded, -32768L, 32767L));
|
||||
}
|
||||
|
||||
void append_whistle(std::vector<std::int16_t>& pcm, std::size_t frames,
|
||||
double start_hz, double end_hz) {
|
||||
double phase = 0.0;
|
||||
const std::size_t attack = kSampleRate / 80;
|
||||
const std::size_t release = kSampleRate / 14;
|
||||
for (std::size_t i = 0; i < frames; ++i) {
|
||||
const double t = static_cast<double>(i) / static_cast<double>(frames);
|
||||
const double frequency = start_hz + (end_hz - start_hz) * t;
|
||||
phase += 2.0 * kPi * frequency / kSampleRate;
|
||||
const double in = std::min(1.0, static_cast<double>(i) / attack);
|
||||
const double out = std::min(1.0, static_cast<double>(frames - 1 - i) / release);
|
||||
const double envelope = std::min(in, out);
|
||||
const double tone = std::sin(phase) + 0.16 * std::sin(phase * 2.01);
|
||||
pcm.push_back(clamp_pcm(14500.0 * envelope * tone));
|
||||
}
|
||||
}
|
||||
|
||||
void append_fanfare_note(std::vector<std::int16_t>& pcm, std::size_t frames,
|
||||
double frequency) {
|
||||
double phase = 0.0;
|
||||
const std::size_t attack = kSampleRate / 90;
|
||||
const std::size_t release = kSampleRate / 9;
|
||||
for (std::size_t i = 0; i < frames; ++i) {
|
||||
phase += 2.0 * kPi * frequency / kSampleRate;
|
||||
const double in = std::min(1.0, static_cast<double>(i) / attack);
|
||||
const double out = std::min(1.0, static_cast<double>(frames - 1 - i) / release);
|
||||
const double envelope = std::min(in, out);
|
||||
const double brass = std::sin(phase) + 0.38 * std::sin(phase * 2.0) +
|
||||
0.14 * std::sin(phase * 3.0);
|
||||
pcm.push_back(clamp_pcm(10500.0 * envelope * brass));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool synthesize_semantic_cue(SemanticCue cue, PcmSample& out, std::string& error) {
|
||||
out = {};
|
||||
error.clear();
|
||||
out.sample_rate = kSampleRate;
|
||||
switch (cue) {
|
||||
case SemanticCue::kickoff_whistle:
|
||||
append_whistle(out.mono, kSampleRate * 42 / 100, 2050.0, 1880.0);
|
||||
break;
|
||||
case SemanticCue::goal:
|
||||
append_fanfare_note(out.mono, kSampleRate * 15 / 100, 659.25);
|
||||
append_fanfare_note(out.mono, kSampleRate * 15 / 100, 783.99);
|
||||
append_fanfare_note(out.mono, kSampleRate * 34 / 100, 987.77);
|
||||
break;
|
||||
case SemanticCue::full_time_whistle:
|
||||
append_whistle(out.mono, kSampleRate * 32 / 100, 1940.0, 1840.0);
|
||||
out.mono.insert(out.mono.end(), kSampleRate * 9 / 100, 0);
|
||||
append_whistle(out.mono, kSampleRate * 42 / 100, 2110.0, 1910.0);
|
||||
break;
|
||||
default:
|
||||
out = {};
|
||||
error = "unknown semantic audio cue";
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace openbmh::audio
|
||||
@@ -0,0 +1,23 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#pragma once
|
||||
|
||||
#include "container.hpp"
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
|
||||
namespace openbmh::audio {
|
||||
|
||||
// Presentation cues used when no verified original PCM effect is available.
|
||||
// These are intentionally semantic labels, never fabricated original Sound IDs.
|
||||
enum class SemanticCue : std::uint8_t {
|
||||
kickoff_whistle = 1,
|
||||
goal = 2,
|
||||
full_time_whistle = 3,
|
||||
};
|
||||
|
||||
// Generates deterministic mono PCM16 cues at 22050 Hz. The synthesizer has no
|
||||
// game state, random source, or renderer dependency.
|
||||
bool synthesize_semantic_cue(SemanticCue cue, PcmSample& out, std::string& error);
|
||||
|
||||
} // namespace openbmh::audio
|
||||
@@ -0,0 +1,373 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#include "formats/executable_layout.hpp"
|
||||
#include "container.hpp"
|
||||
#include "music_fallback.hpp"
|
||||
#include "playback.hpp"
|
||||
#include "formats/le.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cmath>
|
||||
#include <cstdlib>
|
||||
#include <cstdio>
|
||||
#include <fstream>
|
||||
#include <limits>
|
||||
#include <cstdint>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <charconv>
|
||||
#include <filesystem>
|
||||
#include <span>
|
||||
#include <string_view>
|
||||
|
||||
namespace {
|
||||
bool parse_semantic_cue(const std::string& name, openbmh::audio::SemanticCue& cue) {
|
||||
using openbmh::audio::SemanticCue;
|
||||
if (name == "kickoff_whistle") cue = SemanticCue::kickoff_whistle;
|
||||
else if (name == "goal") cue = SemanticCue::goal;
|
||||
else if (name == "full_time_whistle") cue = SemanticCue::full_time_whistle;
|
||||
else return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool write_wav(const openbmh::audio::PcmSample& decoded, const char* path,
|
||||
std::string& error) {
|
||||
if (decoded.mono.size() > (std::numeric_limits<std::uint32_t>::max() - 36u) / 2u ||
|
||||
decoded.sample_rate == 0 || decoded.sample_rate > 192000) {
|
||||
error = "WAV output exceeds format bounds"; return false;
|
||||
}
|
||||
const std::uint32_t data_bytes = static_cast<std::uint32_t>(decoded.mono.size() * 2);
|
||||
std::ofstream wav(path, std::ios::binary);
|
||||
if (!wav) { error = "cannot create WAV output"; return false; }
|
||||
const auto put16 = [&wav](std::uint16_t v) {
|
||||
const char b[] = {static_cast<char>(v), static_cast<char>(v >> 8)};
|
||||
wav.write(b, 2);
|
||||
};
|
||||
const auto put32 = [&wav](std::uint32_t v) {
|
||||
const char b[] = {static_cast<char>(v), static_cast<char>(v >> 8),
|
||||
static_cast<char>(v >> 16), static_cast<char>(v >> 24)};
|
||||
wav.write(b, 4);
|
||||
};
|
||||
wav.write("RIFF", 4); put32(36 + data_bytes); wav.write("WAVEfmt ", 8);
|
||||
put32(16); put16(1); put16(1); put32(decoded.sample_rate);
|
||||
put32(decoded.sample_rate * 2); put16(2); put16(16); wav.write("data", 4);
|
||||
put32(data_bytes);
|
||||
for (const auto value : decoded.mono) put16(static_cast<std::uint16_t>(value));
|
||||
if (!wav) { error = "failed while writing WAV output"; return false; }
|
||||
error.clear();
|
||||
return true;
|
||||
}
|
||||
|
||||
bool bounded_number(const char* value, unsigned minimum, unsigned maximum, unsigned& out) {
|
||||
const std::string_view text(value);
|
||||
const auto [end, error] = std::from_chars(text.data(), text.data() + text.size(), out);
|
||||
return error == std::errc{} && end == text.data() + text.size() && out >= minimum && out <= maximum;
|
||||
}
|
||||
|
||||
openbmh::audio::OriginalAssets load_original_assets(const std::filesystem::path& directory) {
|
||||
openbmh::audio::OriginalAssets assets;
|
||||
const auto exe = bmh::load_le(directory / "BMH.exe");
|
||||
for (unsigned i = 0; i < 4; ++i)
|
||||
assets.containers[i] = bmh::read_file(directory / "S" / std::to_string(2000 + i));
|
||||
for (unsigned i = 0; i < assets.tables.frequencies.size(); ++i)
|
||||
assets.tables.frequencies[i] = exe.u16(::bmh::layout::Audio_OriginalAudioAssets_RuntimeField2 + 2 * i);
|
||||
for (unsigned i = 0; i < assets.tables.operators.size(); ++i)
|
||||
assets.tables.operators[i] = exe.u8(::bmh::layout::Audio_OriginalAudioAssets_RuntimeField + 16 * i);
|
||||
return assets;
|
||||
}
|
||||
|
||||
int original_driver(int argc, char** argv) {
|
||||
using namespace openbmh::audio;
|
||||
const auto usage = [] {
|
||||
std::cerr << "usage: openbmh_sound --original DATA_DIR --export-song 0..2 OUTPUT.wav [--seconds 1..600] [--loops 1..16]\n"
|
||||
" openbmh_sound --original DATA_DIR --export-id 10..22 OUTPUT.wav [--seconds 1..600]\n"
|
||||
" openbmh_sound --original DATA_DIR --play-id ID [--seconds 1..600]\n"
|
||||
" openbmh_sound --original DATA_DIR --play-all [--seconds 1..600]\n";
|
||||
return 2;
|
||||
};
|
||||
if (argc < 4) return usage();
|
||||
const std::string action = argv[3];
|
||||
const bool song = action == "--export-song";
|
||||
const bool export_id = action == "--export-id";
|
||||
const bool play = action == "--play-id";
|
||||
const bool all = action == "--play-all";
|
||||
if (!song && !export_id && !play && !all) return usage();
|
||||
const int required = all ? 4 : play ? 5 : 6;
|
||||
if (argc < required) return usage();
|
||||
unsigned id = 0, seconds = song || all ? 10 : 2, loops = 1;
|
||||
if (!all && !bounded_number(argv[4], 0, 255, id)) return usage();
|
||||
if ((song && id > 2) || (export_id && (id < 10 || id > 22)) ||
|
||||
(play && !(id <= 3 || id == 8 || (id >= 10 && id <= 22)))) return usage();
|
||||
for (int at = required; at < argc; at += 2) {
|
||||
if (at + 1 >= argc) return usage();
|
||||
const std::string option = argv[at];
|
||||
if (option == "--seconds") {
|
||||
if (!bounded_number(argv[at + 1], 1, 600, seconds)) return usage();
|
||||
} else if (song && option == "--loops") {
|
||||
if (!bounded_number(argv[at + 1], 1, 16, loops)) return usage();
|
||||
} else return usage();
|
||||
}
|
||||
try {
|
||||
auto assets = load_original_assets(argv[2]);
|
||||
std::string error;
|
||||
if (song || export_id) {
|
||||
OriginalSynth synth;
|
||||
if (!synth.load(std::move(assets), 22050, error)) {
|
||||
std::cerr << "Original audio rejected: " << error << '\n'; return 1;
|
||||
}
|
||||
if (!(song ? synth.command(std::uint8_t(id)) : synth.effect(std::uint8_t(id)))) {
|
||||
std::cerr << "Original command rejected\n"; return 1;
|
||||
}
|
||||
PcmSample pcm; pcm.sample_rate = 22050;
|
||||
const std::size_t limit = std::size_t(seconds) * pcm.sample_rate;
|
||||
pcm.mono.reserve(limit);
|
||||
std::array<std::int16_t, 128> block{};
|
||||
unsigned completed_loops = 0;
|
||||
auto previous_bar = synth.stats().bar;
|
||||
bool completed = false;
|
||||
while (pcm.mono.size() < limit) {
|
||||
const auto count = std::min(block.size(), limit - pcm.mono.size());
|
||||
synth.render(std::span(block).first(count));
|
||||
pcm.mono.insert(pcm.mono.end(), block.begin(), block.begin() + std::ptrdiff_t(count));
|
||||
const auto stats = synth.stats();
|
||||
if (stats.failed) { std::cerr << "Original decoder failed during export\n"; return 1; }
|
||||
if (song) {
|
||||
if (stats.bar < previous_bar) ++completed_loops;
|
||||
previous_bar = stats.bar;
|
||||
if (!stats.playing || completed_loops >= loops) { completed = true; break; }
|
||||
}
|
||||
}
|
||||
if (!write_wav(pcm, argv[5], error)) { std::cerr << error << '\n'; return 1; }
|
||||
const auto stats = synth.stats();
|
||||
std::cout << "exported Original " << (song ? "song=" : "effect=") << id
|
||||
<< " rate=22050 channels=1 bits=16 frames=" << pcm.mono.size()
|
||||
<< " ticks=" << stats.ticks << " loops=" << completed_loops
|
||||
<< " stop=" << (completed ? "song-or-loop-complete" : "duration-bound") << '\n';
|
||||
return 0;
|
||||
}
|
||||
Playback playback;
|
||||
if (!playback.initialize_original(std::move(assets), error)) {
|
||||
std::cerr << "Original playback unavailable: " << error << '\n'; return 1;
|
||||
}
|
||||
const auto audition = [&](unsigned command, unsigned duration) {
|
||||
if (!playback.play_original_id(std::uint8_t(command), error)) return false;
|
||||
// The actual callback must continue while the main thread is blocked.
|
||||
SDL_Delay(duration * 1000);
|
||||
const auto stats = playback.original_stats();
|
||||
std::cout << "played Original command=" << command << " frames=" << stats.frames
|
||||
<< " ticks=" << stats.ticks << " failed=" << stats.failed << '\n';
|
||||
playback.stop();
|
||||
return !stats.failed;
|
||||
};
|
||||
if (all) {
|
||||
for (unsigned command = 0; command < 3; ++command)
|
||||
if (!audition(command, seconds)) { std::cerr << error << '\n'; return 1; }
|
||||
for (unsigned command = 10; command <= 22; ++command)
|
||||
if (!audition(command, seconds)) { std::cerr << error << '\n'; return 1; }
|
||||
return 0;
|
||||
}
|
||||
if (!audition(id, seconds)) { std::cerr << error << '\n'; return 1; }
|
||||
return 0;
|
||||
} catch (const std::exception& error) {
|
||||
std::cerr << "Original audio input: " << error.what() << '\n'; return 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
if (argc >= 2 && std::string(argv[1]) == "--original") return original_driver(argc, argv);
|
||||
if (argc < 2) {
|
||||
std::cerr << "usage: openbmh_sound <container-file> [--play-test-tone | --play-sample INDEX | --export-sample INDEX OUTPUT.wav | --play-id ID | --export-id ID OUTPUT.wav]\n"
|
||||
" openbmh_sound --original DATA_DIR --export-song 0..2 OUTPUT.wav [--seconds N] [--loops N]\n"
|
||||
" openbmh_sound --original DATA_DIR --export-id 10..22 OUTPUT.wav [--seconds N]\n"
|
||||
" openbmh_sound --original DATA_DIR --play-id ID | --play-all [--seconds N]\n"
|
||||
" openbmh_sound --play-cue NAME | --export-cue NAME OUTPUT.wav\n"
|
||||
" openbmh_sound --export-music-loop OUTPUT.wav\n";
|
||||
return 2;
|
||||
}
|
||||
if (argc == 4 && std::string(argv[1]) == "--export-cue") {
|
||||
openbmh::audio::SemanticCue cue;
|
||||
const std::string name = argv[2];
|
||||
if (!parse_semantic_cue(name, cue)) {
|
||||
std::cerr << "unknown semantic cue\n"; return 2;
|
||||
}
|
||||
openbmh::audio::PcmSample pcm;
|
||||
std::string error;
|
||||
if (!openbmh::audio::synthesize_semantic_cue(cue, pcm, error) ||
|
||||
!write_wav(pcm, argv[3], error)) {
|
||||
std::cerr << "semantic cue export failed: " << error << '\n'; return 1;
|
||||
}
|
||||
std::cout << "exported synthetic semantic cue=" << name << " rate=" << pcm.sample_rate
|
||||
<< " Hz channels=1 bits=16 frames=" << pcm.mono.size()
|
||||
<< " (not an original Sound ID)\n";
|
||||
return 0;
|
||||
}
|
||||
if (argc == 3 && std::string(argv[1]) == "--export-music-loop") {
|
||||
openbmh::audio::PcmSample pcm;
|
||||
std::string error;
|
||||
if (!openbmh::audio::synthesize_matchday_music_loop(pcm, error) ||
|
||||
!write_wav(pcm, argv[2], error)) {
|
||||
std::cerr << "synthetic music export failed: " << error << '\n'; return 1;
|
||||
}
|
||||
std::cout << "exported synthetic 8-bar matchday loop rate=" << pcm.sample_rate
|
||||
<< " Hz channels=1 bits=16 frames=" << pcm.mono.size()
|
||||
<< " (not original music or a Sound ID)\n";
|
||||
return 0;
|
||||
}
|
||||
if (argc == 3 && std::string(argv[1]) == "--play-cue") {
|
||||
openbmh::audio::SemanticCue cue;
|
||||
std::uint32_t wait_ms;
|
||||
const std::string name = argv[2];
|
||||
if (!parse_semantic_cue(name, cue)) { std::cerr << "unknown semantic cue\n"; return 2; }
|
||||
if (cue == openbmh::audio::SemanticCue::kickoff_whistle) wait_ms = 500;
|
||||
else if (cue == openbmh::audio::SemanticCue::goal) wait_ms = 750;
|
||||
else wait_ms = 1000;
|
||||
openbmh::audio::Playback playback;
|
||||
std::string cue_error;
|
||||
if (!playback.initialize(cue_error)) {
|
||||
std::cerr << "audio unavailable: " << cue_error << '\n'; return 0;
|
||||
}
|
||||
if (!playback.play_semantic_cue(cue, cue_error)) {
|
||||
std::cerr << "semantic cue playback failed: " << cue_error << '\n'; return 1;
|
||||
}
|
||||
SDL_Delay(wait_ms);
|
||||
playback.stop();
|
||||
std::cout << "played synthetic semantic cue=" << name << " (not an original Sound ID)\n";
|
||||
return 0;
|
||||
}
|
||||
std::vector<std::uint8_t> bytes;
|
||||
FILE* f = std::fopen(argv[1], "rb");
|
||||
if (!f) { std::cerr << "cannot open input\n"; return 2; }
|
||||
if (std::fseek(f, 0, SEEK_END) != 0) { std::fclose(f); return 2; }
|
||||
const long n = std::ftell(f);
|
||||
if (n < 0 || n > 64L * 1024 * 1024 || std::fseek(f, 0, SEEK_SET) != 0) {
|
||||
std::fclose(f); std::cerr << "input size rejected\n"; return 2;
|
||||
}
|
||||
bytes.resize(static_cast<std::size_t>(n));
|
||||
const auto got = std::fread(bytes.data(), 1, bytes.size(), f);
|
||||
std::fclose(f);
|
||||
if (got != bytes.size()) { std::cerr << "short read\n"; return 2; }
|
||||
|
||||
openbmh::audio::Container container;
|
||||
std::string error;
|
||||
if (!openbmh::audio::parse_container(bytes, container, error)) {
|
||||
std::cerr << "container rejected: " << error << '\n'; return 1;
|
||||
}
|
||||
for (const auto& c : container.chunks)
|
||||
std::cout << c.id << " offset=" << c.payload_offset << " length=" << c.payload_size << '\n';
|
||||
|
||||
if ((argc >= 4 && std::string(argv[2]) == "--play-id") ||
|
||||
(argc >= 5 && std::string(argv[2]) == "--export-id")) {
|
||||
const bool do_play = std::string(argv[2]) == "--play-id";
|
||||
char* end = nullptr;
|
||||
const unsigned long id = std::strtoul(argv[3], &end, 10);
|
||||
if (!end || *end != '\0' || id > 255) {
|
||||
std::cerr << "invalid original Sound ID\n"; return 2;
|
||||
}
|
||||
openbmh::audio::OriginalCue cue;
|
||||
if (!openbmh::audio::decode_original_cue(bytes, static_cast<std::uint8_t>(id), cue, error)) {
|
||||
std::cerr << "original cue rejected: " << error << '\n'; return 1;
|
||||
}
|
||||
if (do_play) {
|
||||
openbmh::audio::Playback playback;
|
||||
if (!playback.initialize(error)) {
|
||||
std::cerr << "audio unavailable: " << error << '\n'; return 0;
|
||||
}
|
||||
if (!playback.load_original_bank(bytes, error) ||
|
||||
!playback.play_original_id(cue.original_id, error)) {
|
||||
std::cerr << "original cue playback rejected: " << error << '\n'; return 1;
|
||||
}
|
||||
const auto milliseconds = static_cast<std::uint32_t>(
|
||||
cue.pcm.mono.size() * 1000 / cue.pcm.sample_rate);
|
||||
SDL_Delay(milliseconds + 25);
|
||||
playback.stop();
|
||||
std::cout << "played original_id=" << static_cast<unsigned>(cue.original_id)
|
||||
<< " sefx_index=" << static_cast<unsigned>(cue.sefx_index)
|
||||
<< " samp_index=" << static_cast<unsigned>(cue.sample_index)
|
||||
<< " frames=" << cue.pcm.mono.size() << " rate="
|
||||
<< cue.pcm.sample_rate << " Hz\n";
|
||||
} else {
|
||||
if (!write_wav(cue.pcm, argv[4], error)) {
|
||||
std::cerr << error << '\n'; return 2;
|
||||
}
|
||||
std::cout << "original_id=" << static_cast<unsigned>(cue.original_id)
|
||||
<< " sefx_index=" << static_cast<unsigned>(cue.sefx_index)
|
||||
<< " samp_index=" << static_cast<unsigned>(cue.sample_index)
|
||||
<< " rate=" << cue.pcm.sample_rate << " Hz channels=1 bits=16 frames="
|
||||
<< cue.pcm.mono.size() << '\n';
|
||||
}
|
||||
}
|
||||
|
||||
if ((argc >= 4 && std::string(argv[2]) == "--play-sample") ||
|
||||
(argc >= 5 && std::string(argv[2]) == "--export-sample")) {
|
||||
const bool do_play = std::string(argv[2]) == "--play-sample";
|
||||
char* end = nullptr;
|
||||
const unsigned long index = std::strtoul(argv[3], &end, 10);
|
||||
if (!end || *end != '\0' || index > 255) {
|
||||
std::cerr << "invalid sample index\n"; return 2;
|
||||
}
|
||||
const auto samp = std::find_if(container.chunks.begin(), container.chunks.end(),
|
||||
[](const auto& c) { return c.id == "SAMP"; });
|
||||
if (samp == container.chunks.end()) { std::cerr << "no SAMP chunk\n"; return 1; }
|
||||
openbmh::audio::PcmSample decoded;
|
||||
if (!openbmh::audio::decode_sample(
|
||||
std::span<const std::uint8_t>(bytes).subspan(samp->payload_offset, samp->payload_size),
|
||||
index, decoded, error)) {
|
||||
std::cerr << "sample rejected: " << error << '\n'; return 1;
|
||||
}
|
||||
if (do_play) {
|
||||
openbmh::audio::Playback playback;
|
||||
if (!playback.initialize(error)) {
|
||||
std::cerr << "audio unavailable: " << error << '\n'; return 0;
|
||||
}
|
||||
if (!playback.play_pcm(decoded.mono.data(), decoded.mono.size(), decoded.sample_rate, error)) {
|
||||
std::cerr << "sample playback rejected: " << error << '\n'; return 1;
|
||||
}
|
||||
const auto milliseconds = static_cast<std::uint32_t>(
|
||||
decoded.mono.size() * 1000 / decoded.sample_rate);
|
||||
SDL_Delay(milliseconds + 25);
|
||||
playback.stop();
|
||||
std::cout << "played SAMP sample=" << index << " frames=" << decoded.mono.size()
|
||||
<< " rate=" << decoded.sample_rate << " Hz\n";
|
||||
} else {
|
||||
const std::uint32_t data_bytes = static_cast<std::uint32_t>(decoded.mono.size() * 2);
|
||||
std::ofstream wav(argv[4], std::ios::binary);
|
||||
if (!wav) { std::cerr << "cannot create WAV output\n"; return 2; }
|
||||
const auto put16 = [&wav](std::uint16_t v) {
|
||||
const char b[] = {static_cast<char>(v), static_cast<char>(v >> 8)};
|
||||
wav.write(b, 2);
|
||||
};
|
||||
const auto put32 = [&wav](std::uint32_t v) {
|
||||
const char b[] = {static_cast<char>(v), static_cast<char>(v >> 8),
|
||||
static_cast<char>(v >> 16), static_cast<char>(v >> 24)};
|
||||
wav.write(b, 4);
|
||||
};
|
||||
wav.write("RIFF", 4); put32(36 + data_bytes); wav.write("WAVEfmt ", 8);
|
||||
put32(16); put16(1); put16(1); put32(decoded.sample_rate);
|
||||
put32(decoded.sample_rate * 2); put16(2); put16(16); wav.write("data", 4);
|
||||
put32(data_bytes);
|
||||
for (const auto value : decoded.mono) put16(static_cast<std::uint16_t>(value));
|
||||
if (!wav) { std::cerr << "failed while writing WAV\n"; return 2; }
|
||||
std::cout << "sample=" << index << " rate=" << decoded.sample_rate
|
||||
<< " Hz channels=1 bits=16 frames=" << decoded.mono.size() << '\n';
|
||||
}
|
||||
}
|
||||
|
||||
if (argc >= 3 && std::string(argv[2]) == "--play-test-tone") {
|
||||
openbmh::audio::Playback playback;
|
||||
if (!playback.initialize(error)) {
|
||||
std::cerr << "audio unavailable: " << error << '\n'; return 0;
|
||||
}
|
||||
constexpr std::uint32_t rate = 22050;
|
||||
std::vector<std::int16_t> tone(rate / 5);
|
||||
for (std::size_t i = 0; i < tone.size(); ++i)
|
||||
tone[i] = static_cast<std::int16_t>(6000.0 * std::sin(2.0 * 3.141592653589793 * 440.0 * i / rate));
|
||||
if (!playback.play_pcm(tone.data(), tone.size(), rate, error)) {
|
||||
std::cerr << "test tone rejected: " << error << '\n'; return 1;
|
||||
}
|
||||
SDL_Delay(250);
|
||||
playback.stop();
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
+504
@@ -0,0 +1,504 @@
|
||||
GNU LESSER GENERAL PUBLIC LICENSE
|
||||
Version 2.1, February 1999
|
||||
|
||||
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
|
||||
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
[This is the first released version of the Lesser GPL. It also counts
|
||||
as the successor of the GNU Library Public License, version 2, hence
|
||||
the version number 2.1.]
|
||||
|
||||
Preamble
|
||||
|
||||
The licenses for most software are designed to take away your
|
||||
freedom to share and change it. By contrast, the GNU General Public
|
||||
Licenses are intended to guarantee your freedom to share and change
|
||||
free software--to make sure the software is free for all its users.
|
||||
|
||||
This license, the Lesser General Public License, applies to some
|
||||
specially designated software packages--typically libraries--of the
|
||||
Free Software Foundation and other authors who decide to use it. You
|
||||
can use it too, but we suggest you first think carefully about whether
|
||||
this license or the ordinary General Public License is the better
|
||||
strategy to use in any particular case, based on the explanations below.
|
||||
|
||||
When we speak of free software, we are referring to freedom of use,
|
||||
not price. Our General Public Licenses are designed to make sure that
|
||||
you have the freedom to distribute copies of free software (and charge
|
||||
for this service if you wish); that you receive source code or can get
|
||||
it if you want it; that you can change the software and use pieces of
|
||||
it in new free programs; and that you are informed that you can do
|
||||
these things.
|
||||
|
||||
To protect your rights, we need to make restrictions that forbid
|
||||
distributors to deny you these rights or to ask you to surrender these
|
||||
rights. These restrictions translate to certain responsibilities for
|
||||
you if you distribute copies of the library or if you modify it.
|
||||
|
||||
For example, if you distribute copies of the library, whether gratis
|
||||
or for a fee, you must give the recipients all the rights that we gave
|
||||
you. You must make sure that they, too, receive or can get the source
|
||||
code. If you link other code with the library, you must provide
|
||||
complete object files to the recipients, so that they can relink them
|
||||
with the library after making changes to the library and recompiling
|
||||
it. And you must show them these terms so they know their rights.
|
||||
|
||||
We protect your rights with a two-step method: (1) we copyright the
|
||||
library, and (2) we offer you this license, which gives you legal
|
||||
permission to copy, distribute and/or modify the library.
|
||||
|
||||
To protect each distributor, we want to make it very clear that
|
||||
there is no warranty for the free library. Also, if the library is
|
||||
modified by someone else and passed on, the recipients should know
|
||||
that what they have is not the original version, so that the original
|
||||
author's reputation will not be affected by problems that might be
|
||||
introduced by others.
|
||||
|
||||
Finally, software patents pose a constant threat to the existence of
|
||||
any free program. We wish to make sure that a company cannot
|
||||
effectively restrict the users of a free program by obtaining a
|
||||
restrictive license from a patent holder. Therefore, we insist that
|
||||
any patent license obtained for a version of the library must be
|
||||
consistent with the full freedom of use specified in this license.
|
||||
|
||||
Most GNU software, including some libraries, is covered by the
|
||||
ordinary GNU General Public License. This license, the GNU Lesser
|
||||
General Public License, applies to certain designated libraries, and
|
||||
is quite different from the ordinary General Public License. We use
|
||||
this license for certain libraries in order to permit linking those
|
||||
libraries into non-free programs.
|
||||
|
||||
When a program is linked with a library, whether statically or using
|
||||
a shared library, the combination of the two is legally speaking a
|
||||
combined work, a derivative of the original library. The ordinary
|
||||
General Public License therefore permits such linking only if the
|
||||
entire combination fits its criteria of freedom. The Lesser General
|
||||
Public License permits more lax criteria for linking other code with
|
||||
the library.
|
||||
|
||||
We call this license the "Lesser" General Public License because it
|
||||
does Less to protect the user's freedom than the ordinary General
|
||||
Public License. It also provides other free software developers Less
|
||||
of an advantage over competing non-free programs. These disadvantages
|
||||
are the reason we use the ordinary General Public License for many
|
||||
libraries. However, the Lesser license provides advantages in certain
|
||||
special circumstances.
|
||||
|
||||
For example, on rare occasions, there may be a special need to
|
||||
encourage the widest possible use of a certain library, so that it becomes
|
||||
a de-facto standard. To achieve this, non-free programs must be
|
||||
allowed to use the library. A more frequent case is that a free
|
||||
library does the same job as widely used non-free libraries. In this
|
||||
case, there is little to gain by limiting the free library to free
|
||||
software only, so we use the Lesser General Public License.
|
||||
|
||||
In other cases, permission to use a particular library in non-free
|
||||
programs enables a greater number of people to use a large body of
|
||||
free software. For example, permission to use the GNU C Library in
|
||||
non-free programs enables many more people to use the whole GNU
|
||||
operating system, as well as its variant, the GNU/Linux operating
|
||||
system.
|
||||
|
||||
Although the Lesser General Public License is Less protective of the
|
||||
users' freedom, it does ensure that the user of a program that is
|
||||
linked with the Library has the freedom and the wherewithal to run
|
||||
that program using a modified version of the Library.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow. Pay close attention to the difference between a
|
||||
"work based on the library" and a "work that uses the library". The
|
||||
former contains code derived from the library, whereas the latter must
|
||||
be combined with the library in order to run.
|
||||
|
||||
GNU LESSER GENERAL PUBLIC LICENSE
|
||||
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
|
||||
|
||||
0. This License Agreement applies to any software library or other
|
||||
program which contains a notice placed by the copyright holder or
|
||||
other authorized party saying it may be distributed under the terms of
|
||||
this Lesser General Public License (also called "this License").
|
||||
Each licensee is addressed as "you".
|
||||
|
||||
A "library" means a collection of software functions and/or data
|
||||
prepared so as to be conveniently linked with application programs
|
||||
(which use some of those functions and data) to form executables.
|
||||
|
||||
The "Library", below, refers to any such software library or work
|
||||
which has been distributed under these terms. A "work based on the
|
||||
Library" means either the Library or any derivative work under
|
||||
copyright law: that is to say, a work containing the Library or a
|
||||
portion of it, either verbatim or with modifications and/or translated
|
||||
straightforwardly into another language. (Hereinafter, translation is
|
||||
included without limitation in the term "modification".)
|
||||
|
||||
"Source code" for a work means the preferred form of the work for
|
||||
making modifications to it. For a library, complete source code means
|
||||
all the source code for all modules it contains, plus any associated
|
||||
interface definition files, plus the scripts used to control compilation
|
||||
and installation of the library.
|
||||
|
||||
Activities other than copying, distribution and modification are not
|
||||
covered by this License; they are outside its scope. The act of
|
||||
running a program using the Library is not restricted, and output from
|
||||
such a program is covered only if its contents constitute a work based
|
||||
on the Library (independent of the use of the Library in a tool for
|
||||
writing it). Whether that is true depends on what the Library does
|
||||
and what the program that uses the Library does.
|
||||
|
||||
1. You may copy and distribute verbatim copies of the Library's
|
||||
complete source code as you receive it, in any medium, provided that
|
||||
you conspicuously and appropriately publish on each copy an
|
||||
appropriate copyright notice and disclaimer of warranty; keep intact
|
||||
all the notices that refer to this License and to the absence of any
|
||||
warranty; and distribute a copy of this License along with the
|
||||
Library.
|
||||
|
||||
You may charge a fee for the physical act of transferring a copy,
|
||||
and you may at your option offer warranty protection in exchange for a
|
||||
fee.
|
||||
|
||||
2. You may modify your copy or copies of the Library or any portion
|
||||
of it, thus forming a work based on the Library, and copy and
|
||||
distribute such modifications or work under the terms of Section 1
|
||||
above, provided that you also meet all of these conditions:
|
||||
|
||||
a) The modified work must itself be a software library.
|
||||
|
||||
b) You must cause the files modified to carry prominent notices
|
||||
stating that you changed the files and the date of any change.
|
||||
|
||||
c) You must cause the whole of the work to be licensed at no
|
||||
charge to all third parties under the terms of this License.
|
||||
|
||||
d) If a facility in the modified Library refers to a function or a
|
||||
table of data to be supplied by an application program that uses
|
||||
the facility, other than as an argument passed when the facility
|
||||
is invoked, then you must make a good faith effort to ensure that,
|
||||
in the event an application does not supply such function or
|
||||
table, the facility still operates, and performs whatever part of
|
||||
its purpose remains meaningful.
|
||||
|
||||
(For example, a function in a library to compute square roots has
|
||||
a purpose that is entirely well-defined independent of the
|
||||
application. Therefore, Subsection 2d requires that any
|
||||
application-supplied function or table used by this function must
|
||||
be optional: if the application does not supply it, the square
|
||||
root function must still compute square roots.)
|
||||
|
||||
These requirements apply to the modified work as a whole. If
|
||||
identifiable sections of that work are not derived from the Library,
|
||||
and can be reasonably considered independent and separate works in
|
||||
themselves, then this License, and its terms, do not apply to those
|
||||
sections when you distribute them as separate works. But when you
|
||||
distribute the same sections as part of a whole which is a work based
|
||||
on the Library, the distribution of the whole must be on the terms of
|
||||
this License, whose permissions for other licensees extend to the
|
||||
entire whole, and thus to each and every part regardless of who wrote
|
||||
it.
|
||||
|
||||
Thus, it is not the intent of this section to claim rights or contest
|
||||
your rights to work written entirely by you; rather, the intent is to
|
||||
exercise the right to control the distribution of derivative or
|
||||
collective works based on the Library.
|
||||
|
||||
In addition, mere aggregation of another work not based on the Library
|
||||
with the Library (or with a work based on the Library) on a volume of
|
||||
a storage or distribution medium does not bring the other work under
|
||||
the scope of this License.
|
||||
|
||||
3. You may opt to apply the terms of the ordinary GNU General Public
|
||||
License instead of this License to a given copy of the Library. To do
|
||||
this, you must alter all the notices that refer to this License, so
|
||||
that they refer to the ordinary GNU General Public License, version 2,
|
||||
instead of to this License. (If a newer version than version 2 of the
|
||||
ordinary GNU General Public License has appeared, then you can specify
|
||||
that version instead if you wish.) Do not make any other change in
|
||||
these notices.
|
||||
|
||||
Once this change is made in a given copy, it is irreversible for
|
||||
that copy, so the ordinary GNU General Public License applies to all
|
||||
subsequent copies and derivative works made from that copy.
|
||||
|
||||
This option is useful when you wish to copy part of the code of
|
||||
the Library into a program that is not a library.
|
||||
|
||||
4. You may copy and distribute the Library (or a portion or
|
||||
derivative of it, under Section 2) in object code or executable form
|
||||
under the terms of Sections 1 and 2 above provided that you accompany
|
||||
it with the complete corresponding machine-readable source code, which
|
||||
must be distributed under the terms of Sections 1 and 2 above on a
|
||||
medium customarily used for software interchange.
|
||||
|
||||
If distribution of object code is made by offering access to copy
|
||||
from a designated place, then offering equivalent access to copy the
|
||||
source code from the same place satisfies the requirement to
|
||||
distribute the source code, even though third parties are not
|
||||
compelled to copy the source along with the object code.
|
||||
|
||||
5. A program that contains no derivative of any portion of the
|
||||
Library, but is designed to work with the Library by being compiled or
|
||||
linked with it, is called a "work that uses the Library". Such a
|
||||
work, in isolation, is not a derivative work of the Library, and
|
||||
therefore falls outside the scope of this License.
|
||||
|
||||
However, linking a "work that uses the Library" with the Library
|
||||
creates an executable that is a derivative of the Library (because it
|
||||
contains portions of the Library), rather than a "work that uses the
|
||||
library". The executable is therefore covered by this License.
|
||||
Section 6 states terms for distribution of such executables.
|
||||
|
||||
When a "work that uses the Library" uses material from a header file
|
||||
that is part of the Library, the object code for the work may be a
|
||||
derivative work of the Library even though the source code is not.
|
||||
Whether this is true is especially significant if the work can be
|
||||
linked without the Library, or if the work is itself a library. The
|
||||
threshold for this to be true is not precisely defined by law.
|
||||
|
||||
If such an object file uses only numerical parameters, data
|
||||
structure layouts and accessors, and small macros and small inline
|
||||
functions (ten lines or less in length), then the use of the object
|
||||
file is unrestricted, regardless of whether it is legally a derivative
|
||||
work. (Executables containing this object code plus portions of the
|
||||
Library will still fall under Section 6.)
|
||||
|
||||
Otherwise, if the work is a derivative of the Library, you may
|
||||
distribute the object code for the work under the terms of Section 6.
|
||||
Any executables containing that work also fall under Section 6,
|
||||
whether or not they are linked directly with the Library itself.
|
||||
|
||||
6. As an exception to the Sections above, you may also combine or
|
||||
link a "work that uses the Library" with the Library to produce a
|
||||
work containing portions of the Library, and distribute that work
|
||||
under terms of your choice, provided that the terms permit
|
||||
modification of the work for the customer's own use and reverse
|
||||
engineering for debugging such modifications.
|
||||
|
||||
You must give prominent notice with each copy of the work that the
|
||||
Library is used in it and that the Library and its use are covered by
|
||||
this License. You must supply a copy of this License. If the work
|
||||
during execution displays copyright notices, you must include the
|
||||
copyright notice for the Library among them, as well as a reference
|
||||
directing the user to the copy of this License. Also, you must do one
|
||||
of these things:
|
||||
|
||||
a) Accompany the work with the complete corresponding
|
||||
machine-readable source code for the Library including whatever
|
||||
changes were used in the work (which must be distributed under
|
||||
Sections 1 and 2 above); and, if the work is an executable linked
|
||||
with the Library, with the complete machine-readable "work that
|
||||
uses the Library", as object code and/or source code, so that the
|
||||
user can modify the Library and then relink to produce a modified
|
||||
executable containing the modified Library. (It is understood
|
||||
that the user who changes the contents of definitions files in the
|
||||
Library will not necessarily be able to recompile the application
|
||||
to use the modified definitions.)
|
||||
|
||||
b) Use a suitable shared library mechanism for linking with the
|
||||
Library. A suitable mechanism is one that (1) uses at run time a
|
||||
copy of the library already present on the user's computer system,
|
||||
rather than copying library functions into the executable, and (2)
|
||||
will operate properly with a modified version of the library, if
|
||||
the user installs one, as long as the modified version is
|
||||
interface-compatible with the version that the work was made with.
|
||||
|
||||
c) Accompany the work with a written offer, valid for at
|
||||
least three years, to give the same user the materials
|
||||
specified in Subsection 6a, above, for a charge no more
|
||||
than the cost of performing this distribution.
|
||||
|
||||
d) If distribution of the work is made by offering access to copy
|
||||
from a designated place, offer equivalent access to copy the above
|
||||
specified materials from the same place.
|
||||
|
||||
e) Verify that the user has already received a copy of these
|
||||
materials or that you have already sent this user a copy.
|
||||
|
||||
For an executable, the required form of the "work that uses the
|
||||
Library" must include any data and utility programs needed for
|
||||
reproducing the executable from it. However, as a special exception,
|
||||
the materials to be distributed need not include anything that is
|
||||
normally distributed (in either source or binary form) with the major
|
||||
components (compiler, kernel, and so on) of the operating system on
|
||||
which the executable runs, unless that component itself accompanies
|
||||
the executable.
|
||||
|
||||
It may happen that this requirement contradicts the license
|
||||
restrictions of other proprietary libraries that do not normally
|
||||
accompany the operating system. Such a contradiction means you cannot
|
||||
use both them and the Library together in an executable that you
|
||||
distribute.
|
||||
|
||||
7. You may place library facilities that are a work based on the
|
||||
Library side-by-side in a single library together with other library
|
||||
facilities not covered by this License, and distribute such a combined
|
||||
library, provided that the separate distribution of the work based on
|
||||
the Library and of the other library facilities is otherwise
|
||||
permitted, and provided that you do these two things:
|
||||
|
||||
a) Accompany the combined library with a copy of the same work
|
||||
based on the Library, uncombined with any other library
|
||||
facilities. This must be distributed under the terms of the
|
||||
Sections above.
|
||||
|
||||
b) Give prominent notice with the combined library of the fact
|
||||
that part of it is a work based on the Library, and explaining
|
||||
where to find the accompanying uncombined form of the same work.
|
||||
|
||||
8. You may not copy, modify, sublicense, link with, or distribute
|
||||
the Library except as expressly provided under this License. Any
|
||||
attempt otherwise to copy, modify, sublicense, link with, or
|
||||
distribute the Library is void, and will automatically terminate your
|
||||
rights under this License. However, parties who have received copies,
|
||||
or rights, from you under this License will not have their licenses
|
||||
terminated so long as such parties remain in full compliance.
|
||||
|
||||
9. You are not required to accept this License, since you have not
|
||||
signed it. However, nothing else grants you permission to modify or
|
||||
distribute the Library or its derivative works. These actions are
|
||||
prohibited by law if you do not accept this License. Therefore, by
|
||||
modifying or distributing the Library (or any work based on the
|
||||
Library), you indicate your acceptance of this License to do so, and
|
||||
all its terms and conditions for copying, distributing or modifying
|
||||
the Library or works based on it.
|
||||
|
||||
10. Each time you redistribute the Library (or any work based on the
|
||||
Library), the recipient automatically receives a license from the
|
||||
original licensor to copy, distribute, link with or modify the Library
|
||||
subject to these terms and conditions. You may not impose any further
|
||||
restrictions on the recipients' exercise of the rights granted herein.
|
||||
You are not responsible for enforcing compliance by third parties with
|
||||
this License.
|
||||
|
||||
11. If, as a consequence of a court judgment or allegation of patent
|
||||
infringement or for any other reason (not limited to patent issues),
|
||||
conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot
|
||||
distribute so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you
|
||||
may not distribute the Library at all. For example, if a patent
|
||||
license would not permit royalty-free redistribution of the Library by
|
||||
all those who receive copies directly or indirectly through you, then
|
||||
the only way you could satisfy both it and this License would be to
|
||||
refrain entirely from distribution of the Library.
|
||||
|
||||
If any portion of this section is held invalid or unenforceable under any
|
||||
particular circumstance, the balance of the section is intended to apply,
|
||||
and the section as a whole is intended to apply in other circumstances.
|
||||
|
||||
It is not the purpose of this section to induce you to infringe any
|
||||
patents or other property right claims or to contest validity of any
|
||||
such claims; this section has the sole purpose of protecting the
|
||||
integrity of the free software distribution system which is
|
||||
implemented by public license practices. Many people have made
|
||||
generous contributions to the wide range of software distributed
|
||||
through that system in reliance on consistent application of that
|
||||
system; it is up to the author/donor to decide if he or she is willing
|
||||
to distribute software through any other system and a licensee cannot
|
||||
impose that choice.
|
||||
|
||||
This section is intended to make thoroughly clear what is believed to
|
||||
be a consequence of the rest of this License.
|
||||
|
||||
12. If the distribution and/or use of the Library is restricted in
|
||||
certain countries either by patents or by copyrighted interfaces, the
|
||||
original copyright holder who places the Library under this License may add
|
||||
an explicit geographical distribution limitation excluding those countries,
|
||||
so that distribution is permitted only in or among countries not thus
|
||||
excluded. In such case, this License incorporates the limitation as if
|
||||
written in the body of this License.
|
||||
|
||||
13. The Free Software Foundation may publish revised and/or new
|
||||
versions of the Lesser General Public License from time to time.
|
||||
Such new versions will be similar in spirit to the present version,
|
||||
but may differ in detail to address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the Library
|
||||
specifies a version number of this License which applies to it and
|
||||
"any later version", you have the option of following the terms and
|
||||
conditions either of that version or of any later version published by
|
||||
the Free Software Foundation. If the Library does not specify a
|
||||
license version number, you may choose any version ever published by
|
||||
the Free Software Foundation.
|
||||
|
||||
14. If you wish to incorporate parts of the Library into other free
|
||||
programs whose distribution conditions are incompatible with these,
|
||||
write to the author to ask for permission. For software which is
|
||||
copyrighted by the Free Software Foundation, write to the Free
|
||||
Software Foundation; we sometimes make exceptions for this. Our
|
||||
decision will be guided by the two goals of preserving the free status
|
||||
of all derivatives of our free software and of promoting the sharing
|
||||
and reuse of software generally.
|
||||
|
||||
NO WARRANTY
|
||||
|
||||
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
|
||||
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
|
||||
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
|
||||
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
|
||||
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
|
||||
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
|
||||
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
|
||||
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
|
||||
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
|
||||
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
|
||||
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
|
||||
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
|
||||
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
|
||||
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
|
||||
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
|
||||
DAMAGES.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Libraries
|
||||
|
||||
If you develop a new library, and you want it to be of the greatest
|
||||
possible use to the public, we recommend making it free software that
|
||||
everyone can redistribute and change. You can do so by permitting
|
||||
redistribution under these terms (or, alternatively, under the terms of the
|
||||
ordinary General Public License).
|
||||
|
||||
To apply these terms, attach the following notices to the library. It is
|
||||
safest to attach them to the start of each source file to most effectively
|
||||
convey the exclusion of warranty; and each file should have at least the
|
||||
"copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the library's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This library is free software; you can redistribute it and/or
|
||||
modify it under the terms of the GNU Lesser General Public
|
||||
License as published by the Free Software Foundation; either
|
||||
version 2.1 of the License, or (at your option) any later version.
|
||||
|
||||
This library 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. See the GNU
|
||||
Lesser General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Lesser General Public
|
||||
License along with this library; if not, write to the Free Software
|
||||
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
|
||||
USA
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or your
|
||||
school, if any, to sign a "copyright disclaimer" for the library, if
|
||||
necessary. Here is a sample; alter the names:
|
||||
|
||||
Yoyodyne, Inc., hereby disclaims all copyright interest in the
|
||||
library `Frob' (a library for tweaking knobs) written by James Random
|
||||
Hacker.
|
||||
|
||||
<signature of Ty Coon>, 1 April 1990
|
||||
Ty Coon, President of Vice
|
||||
|
||||
That's all there is to it!
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
Nuked OPL3 by Nuke.YKT, unmodified upstream source.
|
||||
|
||||
Upstream: https://github.com/nukeykt/Nuked-OPL3
|
||||
Commit: 765ec962e473aeb767e4cba74ffdc8f588ffbfe8
|
||||
License: LGPL-2.1-or-later (see LICENSE and source notices).
|
||||
|
||||
Used in OPL2 compatibility mode for the Original MIDILINK register stream.
|
||||
No Original music, instruments, samples or executable bytes are distributed.
|
||||
+1517
File diff suppressed because it is too large.
Load diff
+175
@@ -0,0 +1,175 @@
|
||||
/* Nuked OPL3
|
||||
* Copyright (C) 2013-2020 Nuke.YKT
|
||||
*
|
||||
* This file is part of Nuked OPL3.
|
||||
*
|
||||
* Nuked OPL3 is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Lesser General Public License as
|
||||
* published by the Free Software Foundation, either version 2.1
|
||||
* of the License, or (at your option) any later version.
|
||||
*
|
||||
* Nuked OPL3 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. See the
|
||||
* GNU Lesser General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Lesser General Public License
|
||||
* along with Nuked OPL3. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
* Nuked OPL3 emulator.
|
||||
* Thanks:
|
||||
* MAME Development Team(Jarek Burczynski, Tatsuyuki Satoh):
|
||||
* Feedback and Rhythm part calculation information.
|
||||
* forums.submarine.org.uk(carbon14, opl3):
|
||||
* Tremolo and phase generator calculation information.
|
||||
* OPLx decapsulated(Matthew Gambrell, Olli Niemitalo):
|
||||
* OPL2 ROMs.
|
||||
* siliconpr0n.org(John McMaster, digshadow):
|
||||
* YMF262 and VRC VII decaps and die shots.
|
||||
*
|
||||
* version: 1.8
|
||||
*/
|
||||
|
||||
#ifndef OPL_OPL3_H
|
||||
#define OPL_OPL3_H
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#include <inttypes.h>
|
||||
|
||||
#ifndef OPL_ENABLE_STEREOEXT
|
||||
#define OPL_ENABLE_STEREOEXT 0
|
||||
#endif
|
||||
|
||||
#define OPL_WRITEBUF_SIZE 1024
|
||||
#define OPL_WRITEBUF_DELAY 2
|
||||
|
||||
typedef struct _opl3_slot opl3_slot;
|
||||
typedef struct _opl3_channel opl3_channel;
|
||||
typedef struct _opl3_chip opl3_chip;
|
||||
|
||||
struct _opl3_slot {
|
||||
opl3_channel *channel;
|
||||
opl3_chip *chip;
|
||||
int16_t out;
|
||||
int16_t fbmod;
|
||||
int16_t *mod;
|
||||
int16_t prout;
|
||||
uint16_t eg_rout;
|
||||
uint16_t eg_out;
|
||||
uint8_t eg_inc;
|
||||
uint8_t eg_gen;
|
||||
uint8_t eg_rate;
|
||||
uint8_t eg_ksl;
|
||||
uint8_t *trem;
|
||||
uint8_t reg_vib;
|
||||
uint8_t reg_type;
|
||||
uint8_t reg_ksr;
|
||||
uint8_t reg_mult;
|
||||
uint8_t reg_ksl;
|
||||
uint8_t reg_tl;
|
||||
uint8_t reg_ar;
|
||||
uint8_t reg_dr;
|
||||
uint8_t reg_sl;
|
||||
uint8_t reg_rr;
|
||||
uint8_t reg_wf;
|
||||
uint8_t key;
|
||||
uint32_t pg_reset;
|
||||
uint32_t pg_phase;
|
||||
uint16_t pg_phase_out;
|
||||
uint8_t slot_num;
|
||||
};
|
||||
|
||||
struct _opl3_channel {
|
||||
opl3_slot *slotz[2];/*Don't use "slots" keyword to avoid conflict with Qt applications*/
|
||||
opl3_channel *pair;
|
||||
opl3_chip *chip;
|
||||
int16_t *out[4];
|
||||
|
||||
#if OPL_ENABLE_STEREOEXT
|
||||
int32_t leftpan;
|
||||
int32_t rightpan;
|
||||
#endif
|
||||
|
||||
uint8_t chtype;
|
||||
uint16_t f_num;
|
||||
uint16_t f_num_reg;
|
||||
uint8_t block;
|
||||
uint8_t block_reg;
|
||||
uint8_t fb;
|
||||
uint8_t con;
|
||||
uint8_t alg;
|
||||
uint8_t ksv;
|
||||
uint16_t cha, chb;
|
||||
uint16_t chc, chd;
|
||||
uint8_t ch_num;
|
||||
};
|
||||
|
||||
typedef struct _opl3_writebuf {
|
||||
uint64_t time;
|
||||
uint16_t reg;
|
||||
uint8_t data;
|
||||
} opl3_writebuf;
|
||||
|
||||
struct _opl3_chip {
|
||||
opl3_channel channel[18];
|
||||
opl3_slot slot[36];
|
||||
uint16_t timer;
|
||||
uint64_t eg_timer;
|
||||
uint8_t eg_timerrem;
|
||||
uint8_t eg_state;
|
||||
uint8_t eg_add;
|
||||
uint8_t eg_timer_lo;
|
||||
uint8_t newm;
|
||||
uint8_t nts;
|
||||
uint8_t rhy;
|
||||
uint8_t vibpos;
|
||||
uint8_t vibshift;
|
||||
uint8_t tremolo;
|
||||
uint8_t tremolopos;
|
||||
uint8_t tremoloshift;
|
||||
uint32_t noise;
|
||||
int16_t zeromod;
|
||||
int32_t mixbuff[4];
|
||||
uint8_t rm_hh_bit2;
|
||||
uint8_t rm_hh_bit3;
|
||||
uint8_t rm_hh_bit7;
|
||||
uint8_t rm_hh_bit8;
|
||||
uint8_t rm_tc_bit3;
|
||||
uint8_t rm_tc_bit5;
|
||||
|
||||
#if OPL_ENABLE_STEREOEXT
|
||||
uint8_t stereoext;
|
||||
#endif
|
||||
|
||||
/* OPL3L */
|
||||
int32_t rateratio;
|
||||
int32_t samplecnt;
|
||||
int16_t oldsamples[4];
|
||||
int16_t samples[4];
|
||||
|
||||
uint64_t writebuf_samplecnt;
|
||||
uint32_t writebuf_cur;
|
||||
uint32_t writebuf_last;
|
||||
uint64_t writebuf_lasttime;
|
||||
opl3_writebuf writebuf[OPL_WRITEBUF_SIZE];
|
||||
};
|
||||
|
||||
void OPL3_Generate(opl3_chip *chip, int16_t *buf);
|
||||
void OPL3_GenerateResampled(opl3_chip *chip, int16_t *buf);
|
||||
void OPL3_Reset(opl3_chip *chip, uint32_t samplerate);
|
||||
void OPL3_WriteReg(opl3_chip *chip, uint16_t reg, uint8_t v);
|
||||
void OPL3_WriteRegBuffered(opl3_chip *chip, uint16_t reg, uint8_t v);
|
||||
void OPL3_GenerateStream(opl3_chip *chip, int16_t *sndptr, uint32_t numsamples);
|
||||
|
||||
void OPL3_Generate4Ch(opl3_chip *chip, int16_t *buf4);
|
||||
void OPL3_Generate4ChResampled(opl3_chip *chip, int16_t *buf4);
|
||||
void OPL3_Generate4ChStream(opl3_chip *chip, int16_t *sndptr1, int16_t *sndptr2, uint32_t numsamples);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,354 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
#include "container.hpp"
|
||||
#include "music_fallback.hpp"
|
||||
#include "playback.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdlib>
|
||||
#include <cstdint>
|
||||
#include <iostream>
|
||||
#include <limits>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
#define CHECK(expr) do { if (!(expr)) { \
|
||||
std::cerr << "check failed at line " << __LINE__ << ": " << #expr << '\n'; \
|
||||
return 1; \
|
||||
} } while (false)
|
||||
std::vector<std::uint8_t> fixture() {
|
||||
// Authored format header and payload, not bytes copied from a game asset.
|
||||
return {'F','O','R','M', 17,0,0,0, 'A','L','P','T','R','A','U','M',
|
||||
'H','E','D','R', 1,0,0,0, 42};
|
||||
}
|
||||
|
||||
std::vector<std::uint8_t> sfx_fixture() {
|
||||
std::vector<std::uint8_t> bytes(65380, 0);
|
||||
std::copy_n("FORM", 4, bytes.begin());
|
||||
const auto put32 = [&bytes](std::size_t at, std::uint32_t value) {
|
||||
for (unsigned i = 0; i < 4; ++i) bytes[at + i] = static_cast<std::uint8_t>(value >> (i * 8));
|
||||
};
|
||||
const auto put16 = [&bytes](std::size_t at, std::uint16_t value) {
|
||||
bytes[at] = static_cast<std::uint8_t>(value);
|
||||
bytes[at + 1] = static_cast<std::uint8_t>(value >> 8);
|
||||
};
|
||||
put32(4, static_cast<std::uint32_t>(bytes.size()));
|
||||
std::copy_n("ALPTRAUM", 8, bytes.begin() + 8);
|
||||
const auto chunk = [&bytes, &put32](std::size_t at, const char* id, std::uint32_t size) {
|
||||
std::copy_n(id, 4, bytes.begin() + static_cast<std::ptrdiff_t>(at));
|
||||
put32(at + 4, size);
|
||||
};
|
||||
chunk(16, "HEDR", 8);
|
||||
chunk(32, "SEFX", 212);
|
||||
bytes[42] = 7;
|
||||
for (std::size_t i = 7; i < 13; ++i) {
|
||||
const std::size_t row = 44 + i * 16;
|
||||
bytes[row] = static_cast<std::uint8_t>(16 + i - 7);
|
||||
bytes[row + 1] = 9;
|
||||
}
|
||||
chunk(252, "INST", 228);
|
||||
chunk(488, "SAMP", 64884);
|
||||
const std::size_t samp = 496;
|
||||
put16(samp + 2, 6);
|
||||
const std::size_t data_at = samp + 4 + 6 * 16;
|
||||
for (std::size_t i = 0; i < 6; ++i) {
|
||||
const std::size_t row = samp + 4 + i * 16;
|
||||
put16(row, static_cast<std::uint16_t>(i * 2048));
|
||||
put16(row + 2, 2048);
|
||||
put16(row + 8, 11025);
|
||||
std::fill(bytes.begin() + static_cast<std::ptrdiff_t>(data_at + i * 2048),
|
||||
bytes.begin() + static_cast<std::ptrdiff_t>(data_at + (i + 1) * 2048),
|
||||
static_cast<std::uint8_t>(128 + i));
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
}
|
||||
|
||||
int main(int, char**) { // (the SDL_main signature: SDL.h renames main on Windows)
|
||||
using namespace openbmh::audio;
|
||||
std::string error;
|
||||
Container c;
|
||||
auto good = fixture();
|
||||
CHECK(parse_container(good, c, error));
|
||||
CHECK(c.chunks.size() == 1 && c.chunks[0].id == "HEDR");
|
||||
CHECK(c.chunks[0].payload_size == 1 && good[c.chunks[0].payload_offset] == 42);
|
||||
|
||||
auto broken = good;
|
||||
broken[20] = 0xff;
|
||||
broken[21] = 0xff;
|
||||
broken[22] = 0xff;
|
||||
broken[23] = 0x7f;
|
||||
CHECK(!parse_container(broken, c, error));
|
||||
CHECK(c.chunks.empty());
|
||||
CHECK(!parse_container(std::span<const std::uint8_t>(good.data(), 15), c, error));
|
||||
|
||||
std::vector<std::uint8_t> sefx(65380, 0);
|
||||
const char form[] = "FORM";
|
||||
std::copy(form, form + 4, sefx.begin());
|
||||
sefx[4] = static_cast<std::uint8_t>(sefx.size());
|
||||
sefx[5] = static_cast<std::uint8_t>(sefx.size() >> 8);
|
||||
const char type[] = "ALPTRAUM";
|
||||
std::copy(type, type + 8, sefx.begin() + 8);
|
||||
std::size_t at = 16;
|
||||
const auto put_chunk = [&](const char* id, std::uint32_t size, std::size_t& cursor) {
|
||||
std::copy(id, id + 4, sefx.begin() + static_cast<std::ptrdiff_t>(cursor));
|
||||
sefx[cursor + 4] = static_cast<std::uint8_t>(size);
|
||||
sefx[cursor + 5] = static_cast<std::uint8_t>(size >> 8);
|
||||
cursor += 8 + size;
|
||||
};
|
||||
put_chunk("HEDR", 8, at);
|
||||
put_chunk("SEFX", 212, at);
|
||||
sefx[42] = 7; // observed 2003 SEFX record-count field
|
||||
put_chunk("INST", 228, at);
|
||||
put_chunk("SAMP", 64884, at);
|
||||
CHECK(at == sefx.size());
|
||||
CHECK(parse_container(sefx, c, error));
|
||||
CHECK(c.chunks.size() == 4 && c.chunks[1].id == "SEFX");
|
||||
auto wrong_exception = sefx;
|
||||
wrong_exception[32] = 'S'; wrong_exception[33] = 'O';
|
||||
wrong_exception[34] = 'N'; wrong_exception[35] = 'G';
|
||||
CHECK(!parse_container(wrong_exception, c, error));
|
||||
auto wrong_type = good;
|
||||
wrong_type[8] = 'X';
|
||||
CHECK(!parse_container(wrong_type, c, error));
|
||||
|
||||
std::vector<std::uint8_t> samp(24, 0);
|
||||
samp[2] = 1;
|
||||
samp[6] = 4;
|
||||
samp[12] = 0x22; samp[13] = 0x56; // 22050 Hz
|
||||
samp[20] = 0; samp[21] = 128; samp[22] = 255; samp[23] = 128;
|
||||
PcmSample pcm;
|
||||
CHECK(decode_sample(samp, 0, pcm, error));
|
||||
CHECK(pcm.sample_rate == 22050 && pcm.mono.size() == 4);
|
||||
CHECK(pcm.mono[0] == -32768 && pcm.mono[1] == 0 && pcm.mono[2] == 32512);
|
||||
samp[6] = 0xff; samp[7] = 0xff;
|
||||
CHECK(!decode_sample(samp, 0, pcm, error));
|
||||
CHECK(!decode_sample(samp, 1, pcm, error));
|
||||
|
||||
auto bank = sfx_fixture();
|
||||
OriginalCue original;
|
||||
CHECK(decode_original_cue(bank, 17, original, error));
|
||||
CHECK(original.original_id == 17 && original.sefx_index == 7 && original.sample_index == 0);
|
||||
CHECK(original.pcm.sample_rate == 11025 && original.pcm.mono.size() == 2048);
|
||||
CHECK(original.pcm.mono.front() == 0);
|
||||
CHECK(decode_original_cue(bank, 22, original, error));
|
||||
CHECK(original.sefx_index == 12 && original.sample_index == 5);
|
||||
CHECK(!decode_original_cue(bank, 16, original, error));
|
||||
|
||||
CHECK(SDL_InitSubSystem(SDL_INIT_VIDEO) == 0);
|
||||
Playback playback;
|
||||
CHECK(playback.initialize(error));
|
||||
CHECK(playback.available());
|
||||
CHECK(!playback.music_active() && !playback.needs_pump());
|
||||
CHECK(!playback.pump(error)); // The optional music path is inactive by default.
|
||||
playback.set_volume(2.0F);
|
||||
CHECK(playback.volume() == 1.0F);
|
||||
playback.set_volume(-1.0F);
|
||||
CHECK(playback.volume() == 0.0F);
|
||||
playback.set_volume(1.0F);
|
||||
playback.set_volume(std::numeric_limits<float>::quiet_NaN());
|
||||
CHECK(playback.volume() == 1.0F);
|
||||
playback.set_volume(std::numeric_limits<float>::infinity());
|
||||
CHECK(playback.volume() == 1.0F);
|
||||
playback.set_muted(true);
|
||||
CHECK(playback.muted());
|
||||
CHECK(playback.play_pcm(nullptr, 0, 22050, error)); // mute drops without queueing
|
||||
playback.set_muted(false);
|
||||
const std::int16_t sample[] = {0, 1000, -1000, 0};
|
||||
CHECK(playback.play_pcm(sample, 4, 22050, error));
|
||||
std::vector<std::int16_t> long_sample(22050, 1000);
|
||||
CHECK(playback.play_pcm(long_sample.data(), long_sample.size(), 22050, error));
|
||||
CHECK(playback.queued_bytes() > 0);
|
||||
playback.set_muted(true);
|
||||
CHECK(playback.queued_bytes() == 0);
|
||||
playback.set_muted(false);
|
||||
CHECK(playback.play_pcm(long_sample.data(), long_sample.size(), 22050, error));
|
||||
CHECK(playback.queued_bytes() > 0);
|
||||
|
||||
playback.reset_session(7);
|
||||
CHECK(playback.queued_bytes() == 0);
|
||||
playback.reset_session(7); // same session preserves the event watermark
|
||||
CHECK(playback.load_original_bank(bank, error));
|
||||
|
||||
const CueRequest cue_a{7, 1, 17};
|
||||
CHECK(playback.submit(cue_a, error) == CueStatus::queued);
|
||||
CHECK(playback.queued_bytes() > 0);
|
||||
CHECK(playback.submit(cue_a, error) == CueStatus::duplicate);
|
||||
CHECK(playback.submit(CueRequest{7, 2, 17}, error) == CueStatus::queued);
|
||||
playback.set_muted(true);
|
||||
const CueRequest muted{7, 3, 17};
|
||||
CHECK(playback.submit(muted, error) == CueStatus::muted);
|
||||
playback.set_muted(false);
|
||||
CHECK(playback.submit(muted, error) == CueStatus::duplicate);
|
||||
playback.stop();
|
||||
CHECK(playback.submit(cue_a, error) == CueStatus::duplicate);
|
||||
playback.reset_session(8);
|
||||
CHECK(playback.submit(CueRequest{8, 1, 17}, error) == CueStatus::queued);
|
||||
CHECK(playback.submit(CueRequest{7, 4, 17}, error) == CueStatus::invalid);
|
||||
CHECK(playback.submit(CueRequest{8, 1, 17}, error) == CueStatus::duplicate);
|
||||
|
||||
PcmSample kickoff_pcm, goal_pcm, final_pcm;
|
||||
CHECK(synthesize_semantic_cue(SemanticCue::kickoff_whistle, kickoff_pcm, error));
|
||||
CHECK(synthesize_semantic_cue(SemanticCue::goal, goal_pcm, error));
|
||||
CHECK(synthesize_semantic_cue(SemanticCue::full_time_whistle, final_pcm, error));
|
||||
CHECK(kickoff_pcm.sample_rate == 22050 && goal_pcm.sample_rate == 22050 &&
|
||||
final_pcm.sample_rate == 22050);
|
||||
CHECK(!kickoff_pcm.mono.empty() && !goal_pcm.mono.empty() && !final_pcm.mono.empty());
|
||||
CHECK(kickoff_pcm.mono != goal_pcm.mono && goal_pcm.mono != final_pcm.mono &&
|
||||
kickoff_pcm.mono != final_pcm.mono);
|
||||
PcmSample matchday_loop, repeated_loop;
|
||||
CHECK(synthesize_matchday_music_loop(matchday_loop, error));
|
||||
CHECK(synthesize_matchday_music_loop(repeated_loop, error));
|
||||
CHECK(matchday_loop.sample_rate == 22050);
|
||||
CHECK(matchday_loop.mono.size() == 392000); // 8 bars, 4 beats, 108 BPM.
|
||||
CHECK(matchday_loop.mono == repeated_loop.mono); // deterministic, no RNG.
|
||||
CHECK(matchday_loop.mono.front() == 0 && matchday_loop.mono.back() == 0);
|
||||
CHECK(std::any_of(matchday_loop.mono.begin(), matchday_loop.mono.end(),
|
||||
[](std::int16_t value) { return value != 0; }));
|
||||
|
||||
Mixer mixer;
|
||||
PcmSample constant_music{22050, std::vector<std::int16_t>(8, 1000)};
|
||||
const std::int16_t voice_samples[] = {2000, 2000, 2000, 2000};
|
||||
CHECK(mixer.start_music_loop(constant_music, 22050, error));
|
||||
CHECK(mixer.add_voice(voice_samples, 22050, 22050, error));
|
||||
CHECK(mixer.active_voices() == 1);
|
||||
std::int16_t mixed_block[2]{};
|
||||
CHECK(mixer.mix_block(mixed_block, 1.0F));
|
||||
CHECK(mixed_block[0] == 3000 && mixed_block[1] == 3000); // Cue overlays the loop.
|
||||
mixer.stop_music();
|
||||
CHECK(!mixer.has_music() && mixer.active_voices() == 1);
|
||||
std::int16_t voice_tail[4]{};
|
||||
CHECK(mixer.mix_block(voice_tail, 1.0F)); // stop_music leaves the cue voice alive.
|
||||
CHECK(voice_tail[0] == 2000 && voice_tail[1] == 2000 &&
|
||||
voice_tail[2] == 0 && voice_tail[3] == 0);
|
||||
CHECK(!mixer.active());
|
||||
mixer.clear();
|
||||
CHECK(mixer.start_music_loop(constant_music, 22050, error));
|
||||
for (int i = 0; i < 8; ++i) CHECK(mixer.add_voice(voice_samples, 22050, 22050, error));
|
||||
CHECK(mixer.active_voices() == 8);
|
||||
CHECK(!mixer.add_voice(voice_samples, 22050, 22050, error));
|
||||
mixer.clear();
|
||||
static_assert(static_cast<std::uint8_t>(SemanticCue::kickoff_whistle) == 1);
|
||||
static_assert(static_cast<std::uint8_t>(SemanticCue::goal) == 2);
|
||||
static_assert(static_cast<std::uint8_t>(SemanticCue::full_time_whistle) == 3);
|
||||
playback.reset_session(9);
|
||||
const SemanticCueRequest kickoff{9, 1, SemanticCue::kickoff_whistle};
|
||||
CHECK(playback.submit(kickoff, error) == CueStatus::queued);
|
||||
CHECK(playback.queued_bytes() > 0);
|
||||
CHECK(playback.submit(kickoff, error) == CueStatus::duplicate);
|
||||
CHECK(playback.submit(SemanticCueRequest{9, 2, SemanticCue::kickoff_whistle}, error) == CueStatus::queued);
|
||||
playback.set_muted(true);
|
||||
const SemanticCueRequest muted_goal{9, 3, SemanticCue::goal};
|
||||
CHECK(playback.submit(muted_goal, error) == CueStatus::muted);
|
||||
playback.set_muted(false);
|
||||
CHECK(playback.submit(muted_goal, error) == CueStatus::duplicate);
|
||||
CHECK(playback.submit(SemanticCueRequest{9, 4, SemanticCue::goal}, error) == CueStatus::queued);
|
||||
playback.reset_session(10);
|
||||
CHECK(playback.queued_bytes() == 0);
|
||||
CHECK(playback.submit(SemanticCueRequest{10, 1, SemanticCue::full_time_whistle}, error) == CueStatus::queued);
|
||||
CHECK(playback.queued_bytes() > 0);
|
||||
|
||||
playback.reset_session(11);
|
||||
CHECK(playback.submit(CueRequest{11, 1, 17}, error) == CueStatus::queued);
|
||||
CHECK(playback.submit(SemanticCueRequest{11, 1, SemanticCue::goal}, error) == CueStatus::duplicate);
|
||||
CHECK(playback.submit(SemanticCueRequest{11, 2, SemanticCue::goal}, error) == CueStatus::queued);
|
||||
CHECK(playback.submit(CueRequest{11, 2, 17}, error) == CueStatus::duplicate);
|
||||
CHECK(playback.submit(SemanticCueRequest{10, 3, SemanticCue::goal}, error) == CueStatus::invalid);
|
||||
CHECK(playback.submit(CueRequest{11, 0, 17}, error) == CueStatus::invalid);
|
||||
CHECK(playback.submit(SemanticCueRequest{11, 3, SemanticCue::full_time_whistle}, error) == CueStatus::queued);
|
||||
|
||||
// Optional music is explicit. Cues submitted while it is active enter the
|
||||
// mixer immediately; pump emits short mixed blocks, never a whole loop.
|
||||
playback.reset_session(12);
|
||||
CHECK(playback.play_pcm(long_sample.data(), long_sample.size(), 22050, error));
|
||||
CHECK(playback.queued_bytes() > 0);
|
||||
CHECK(!playback.start_music_loop(matchday_loop, error)); // Reject >40ms legacy cue backlog.
|
||||
CHECK(!playback.music_active());
|
||||
CHECK(playback.queued_bytes() > 0); // Existing queued cue was not discarded.
|
||||
playback.stop();
|
||||
CHECK(!playback.needs_pump());
|
||||
CHECK(playback.start_music_loop(matchday_loop, error));
|
||||
CHECK(playback.pump(error));
|
||||
CHECK(playback.queued_bytes() <= 40U * 22050U * 2U / 1000U);
|
||||
// Refill after typical 60/30 Hz app ticks. This checks the bounded refill,
|
||||
// not continuous audible output: the dummy backend is not a listening test.
|
||||
for (const unsigned delay : {17U, 33U}) {
|
||||
for (unsigned tick = 0; tick < 12; ++tick) {
|
||||
SDL_Delay(delay);
|
||||
CHECK(playback.pump(error));
|
||||
CHECK(error.empty());
|
||||
CHECK(playback.queued_bytes() > 0);
|
||||
CHECK(playback.queued_bytes() <= 40U * 22050U * 2U / 1000U);
|
||||
}
|
||||
}
|
||||
CHECK(playback.submit(CueRequest{12, 1, 17}, error) == CueStatus::queued);
|
||||
bool cue_pumped = false;
|
||||
for (unsigned attempt = 0; attempt < 5 && !cue_pumped; ++attempt) {
|
||||
cue_pumped = playback.pump(error);
|
||||
if (cue_pumped)
|
||||
CHECK(playback.queued_bytes() <= 40U * 22050U * 2U / 1000U);
|
||||
if (!cue_pumped) SDL_Delay(25);
|
||||
}
|
||||
CHECK(cue_pumped);
|
||||
const SemanticCueRequest music_muted_event{12, 2, SemanticCue::goal};
|
||||
playback.set_muted(true); // Clears music and both queued and active voices.
|
||||
CHECK(!playback.music_active());
|
||||
CHECK(!playback.pump(error));
|
||||
CHECK(playback.submit(music_muted_event, error) == CueStatus::muted);
|
||||
playback.set_muted(false);
|
||||
CHECK(playback.submit(music_muted_event, error) == CueStatus::duplicate);
|
||||
CHECK(!playback.pump(error));
|
||||
|
||||
// A zero master volume still advances an already active voice silently.
|
||||
playback.reset_session(13);
|
||||
CHECK(playback.start_music_loop(matchday_loop, error));
|
||||
const std::int16_t short_voice[] = {1000, 1000, 1000, 1000};
|
||||
CHECK(playback.play_pcm(short_voice, 4, 22050, error));
|
||||
playback.set_volume(0.0F);
|
||||
playback.stop_music();
|
||||
CHECK(playback.needs_pump());
|
||||
CHECK(playback.pump(error));
|
||||
CHECK(!playback.needs_pump());
|
||||
playback.set_volume(1.0F);
|
||||
CHECK(!playback.pump(error)); // No delayed replay after restoring volume.
|
||||
|
||||
playback.reset_session(13);
|
||||
CHECK(!playback.music_active() && !playback.pump(error));
|
||||
CHECK(playback.start_music_loop(matchday_loop, error));
|
||||
CHECK(playback.needs_pump());
|
||||
playback.reset_session(14); // A real session change clears music and queue.
|
||||
CHECK(!playback.music_active() && !playback.needs_pump() && playback.queued_bytes() == 0);
|
||||
CHECK(playback.start_music_loop(matchday_loop, error));
|
||||
CHECK(playback.submit(CueRequest{14, 1, 17}, error) == CueStatus::queued);
|
||||
playback.stop_music();
|
||||
CHECK(!playback.music_active());
|
||||
CHECK(playback.needs_pump());
|
||||
CHECK(playback.pump(error)); // Stopping music alone preserves an active cue.
|
||||
playback.stop();
|
||||
CHECK(!playback.needs_pump());
|
||||
CHECK(!playback.pump(error));
|
||||
|
||||
Playback unavailable;
|
||||
unavailable.reset_session(20);
|
||||
const CueRequest unavailable_event{20, 1, 17};
|
||||
CHECK(!unavailable.available());
|
||||
CHECK(!unavailable.start_music_loop(matchday_loop, error));
|
||||
CHECK(unavailable.submit(unavailable_event, error) == CueStatus::disabled);
|
||||
playback.shutdown();
|
||||
CHECK(unavailable.initialize(error));
|
||||
CHECK(unavailable.submit(unavailable_event, error) == CueStatus::duplicate);
|
||||
CHECK(unavailable.queued_bytes() == 0); // A disabled event is not replayed after device recovery.
|
||||
unavailable.shutdown();
|
||||
CHECK(playback.initialize(error));
|
||||
playback.reset_session(15);
|
||||
CHECK(playback.start_music_loop(matchday_loop, error));
|
||||
CHECK(playback.submit(CueRequest{15, 1, 17}, error) == CueStatus::queued);
|
||||
playback.shutdown(); // Device shutdown clears the optional track and active cue.
|
||||
CHECK(!playback.available() && !playback.music_active());
|
||||
playback.shutdown();
|
||||
CHECK(!playback.available());
|
||||
CHECK((SDL_WasInit(SDL_INIT_VIDEO) & SDL_INIT_VIDEO) != 0);
|
||||
SDL_QuitSubSystem(SDL_INIT_VIDEO);
|
||||
std::cout << "checks passed: original/semantic shared event ledger; stale and zero IDs; unavailable device and no replay; deterministic eight-bar loop; PCM overlay and stop-music cue tail; fixed voice cap; mute/reset/shutdown clear music; SDL dummy lifecycle; no listening test\n";
|
||||
return 0; // (explicit: main is SDL_main here, no implicit return 0)
|
||||
}
|
||||
Reference in new issue
Block a user