diff --git a/CHANGELOG.md b/CHANGELOG.md index cbadac4..59d3f29 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,10 @@ Release versions follow the `
` format (where `2026` is `a`, - Added a Gambatte-style NeoUI-themed frontend browser when launched without arguments (scanning `/usr/share/games/j2me`, `~/Games`, `~/J2ME`, and `~/Downloads` with `MANIFEST.MF` / `.jad` metadata preview, pause menu, keypad control remapping, scaling/3D/audio toggles, and RMS save manager). - Implemented NeoUI-themed (`libneoui.so` / `PluginTheme`) high-level LCDUI components (`Form`, `List`, `TextBox`, `Alert`, `ChoiceGroup`, `Gauge`, `TextField`, `StringItem`, and `Command` bars/menus) alongside full-screen 2D `Canvas` / `GameCanvas` / `Sprite` / `TiledLayer` rendering, Nokia UI API (`com.nokia.mid.ui.*`), Adreno 304 (`FD304`) EGL + OpenGL ES 2.0 hardware-accelerated JSR-184 M3G 3D graphics (`javax.microedition.m3g.*`), HTTP/HTTPS and TCP/UDP socket networking (`javax.microedition.io.Connector`), `RecordStore` (RMS) persistence, and MMAPI (`javax.microedition.media.Manager`) ALSA audio. - Preinstalled J2ME apps and functional test suites in `/usr/share/games/j2me/` and `~/Games/`: `g2048.jar` (240x320 2048), `ReMEdy3DArena.jar` (JSR-184 3D hardware-accelerated arena), `AstroBlaster240.jar` (`GameCanvas` space shooter with RMS high score and tone audio), and `NetToolJ2ME.jar` (NeoUI-themed LCDUI + HTTP/TCP socket test suite). + - Faster bytecode interpreter: resolved field/method constant pool entries and static field slots are cached per class, virtual calls use a monomorphic inline cache, and Java threads run on a wall-clock budget per frame, so asset-heavy games (for example `Castlevania: Aria of Sorrow`) load and play at full speed. + - Fixed obfuscated MIDlets that declare several fields with the same name but different types (fields are now keyed by name and descriptor), and fixed long-running `startApp()` / `` initializers being cut short. + - Smoother MMAPI audio: a 48 kHz mixer with a 64 ms ALSA ring buffer and a table-based polyphonic MIDI synthesizer (no more stutter or tempo drag under CPU load), plus MIDP `VolumeControl` levels mapped to perceived loudness. + - ReMEdy audio now follows the system speaker volume and mute state (the xdrawer **Speaker** slider, `~/.config/sxmo/speaker_vol`, and `SPK DAC Switch`) live while a MIDlet runs. The pause menu **Audio** item changes the system speaker volume with `Left` / `Right` and toggles ReMEdy sound with `OK`. - **Adreno 304 (`FD304`) 3D GPU hardware acceleration and Xlibre Glamor offload**: - Added full Qualcomm **Adreno 304 (`0x03000400`)** GPU and `qcom,msm8909-iommu` (`gfx3d_user` / `gfx3d_priv` context banks at `0x1f08000`) support to the `6.12.1-msm8916` kernel (`drm/msm` module and MSM8905/MSM8909 device trees across `nokia-argon`, `nokia-beatles`, `nokia-tough`, `nokia-sparkler`, and `nokia-leo`), configured for Adreno 304's `96 KB` (`SZ_64K + SZ_32K`) GMEM cache, `a300_pm4.fw` / `a300_pfp.fw` microcode, VBIF/ROQ/clock-gating registers, hard-reset recovery quirk, `OXILI_GDSC` power domain, and OPP frequency scaling up to `409.6 MHz`. - Enabled headless render-only `drm/msm` initialization (`card1` / `renderD128`) alongside the SPI `panel-mipi-dbi` display (`card0`) and enabled `FD304` (`chip_id = 0x030004ff`) in Mesa Freedreno (`libgallium`) for hardware-accelerated **OpenGL 3.1** and **OpenGL ES 3.0**. diff --git a/MANUAL.md b/MANUAL.md index 71aabf4..9bbec8d 100644 --- a/MANUAL.md +++ b/MANUAL.md @@ -241,8 +241,8 @@ Two classic X11 games (`/usr/bin/snake` and `/usr/bin/tetris`), the **Gambatte ( - **ReMEdy J2ME (MIDP 2.0 / CLDC 1.1) emulator (`remedy` / `j2me`)**: - **Launch**: open **ReMEdy (J2ME)** from **System menu -> Applications** or **System menu -> Games**, open any `.jar` or `.jad` file from **Files (`xfiles`)**, or run `remedy [app.jar|app.jad]`. When launched without a file argument, opens the NeoUI-themed **ReMEdy J2ME** browser scanning `/usr/share/games/j2me`, `~/Games`, `~/J2ME`, `~/Downloads`, and user directories, displaying the selected MIDlet's `MIDlet-Name`, `MIDlet-Vendor`, `MIDlet-Version`, main class, and RMS save status. - **Full-screen `240x320` resolution and NeoUI-themed LCDUI**: runs in a full-screen `240x320` window (`X=0, Y=0, W=240, H=320`) and declares native `240x320` dimensions (`getWidth() == 240`, `getHeight() == 320`) to J2ME applications. Full-screen `Canvas` and `GameCanvas` games get the entire `240x320` display, while high-level LCDUI screens (`Form`, `List`, `TextBox`, `Alert`, `ChoiceGroup`, `Gauge`, `TextField`, `StringItem`, and `Command` bars/menus) render with `libneoui.so` (`PluginTheme`) and adapt automatically to the active `.Xresources` / `~/.xthemes/*.xth` system theme. - - **Hardware-accelerated 3D (JSR-184 M3G), networking, RMS, and audio**: accelerates JSR-184 (`javax.microedition.m3g.*`) 3D scenes on the Adreno 304 (`FD304`) GPU via EGL + OpenGL ES 2.0 (with depth-buffered software fallback), supports HTTP/HTTPS and raw TCP/UDP socket connections (`javax.microedition.io.Connector`, `HttpConnection`, `SocketConnection`, `FileConnection` JSR-75), Nokia UI API (`com.nokia.mid.ui.*`), persistent `RecordStore` (RMS) storage (`~/.local/share/sxmo/remedy/rms/`), and MMAPI (`javax.microedition.media.Manager`) tone and WAV/MIDI audio over ALSA (`hw:0,0`). - - **Keypad controls and pause menu**: maps D-Pad (`Up`/`Down`/`Left`/`Right`), `Center OK` (`FIRE`), `0`–`9`, `*`, `#`, **Left softkey** (`-6`), and **Right softkey** (`-7`) directly to MIDP 2.0 / Nokia key codes, with customizable D-Pad (`D-Pad + 2/4/6/8`, `D-Pad Only`, `2/4/6/8 Only`) and softkey modes persisted in `~/.config/sxmo/remedy.cfg`. Press **End / Power (red)** (`Escape`) during execution to open the **ReMEdy Pause Menu** (Resume, Send Left/Right Softkey Command, Screen Scaling, 3D Renderer toggle, Audio toggle, Keypad Controls remapping, Reset RMS Save Data, Load Another MIDlet, or Quit). Preinstalled MIDlets in `/usr/share/games/j2me/` and `~/Games/` include `g2048.jar`, `ReMEdy3DArena.jar` (JSR-184 3D benchmark), `AstroBlaster240.jar` (`GameCanvas` space shooter), and `NetToolJ2ME.jar` (LCDUI + HTTP/TCP socket test suite). + - **Hardware-accelerated 3D (JSR-184 M3G), networking, RMS, and audio**: accelerates JSR-184 (`javax.microedition.m3g.*`) 3D scenes on the Adreno 304 (`FD304`) GPU via EGL + OpenGL ES 2.0 (with depth-buffered software fallback), supports HTTP/HTTPS and raw TCP/UDP socket connections (`javax.microedition.io.Connector`, `HttpConnection`, `SocketConnection`, `FileConnection` JSR-75), Nokia UI API (`com.nokia.mid.ui.*`), persistent `RecordStore` (RMS) storage (`~/.local/share/sxmo/remedy/rms/`), and MMAPI (`javax.microedition.media.Manager`) tone and WAV/MIDI audio over ALSA (`hw:0,0`). Audio follows the system speaker volume and mute state (the xdrawer **Speaker** slider) live, at the same loudness as other apps. + - **Keypad controls and pause menu**: maps D-Pad (`Up`/`Down`/`Left`/`Right`), `Center OK` (`FIRE`), `0`–`9`, `*`, `#`, **Left softkey** (`-6`), and **Right softkey** (`-7`) directly to MIDP 2.0 / Nokia key codes, with customizable D-Pad (`D-Pad + 2/4/6/8`, `D-Pad Only`, `2/4/6/8 Only`) and softkey modes persisted in `~/.config/sxmo/remedy.cfg`. Press **End / Power (red)** (`Escape`) during execution to open the **ReMEdy Pause Menu** (Resume, Send Left/Right Softkey Command, Screen Scaling, 3D Renderer toggle, Audio (`Left`/`Right` change the system speaker volume, `OK` toggles ReMEdy sound), Keypad Controls remapping, Reset RMS Save Data, Load Another MIDlet, or Quit). Preinstalled MIDlets in `/usr/share/games/j2me/` and `~/Games/` include `g2048.jar`, `ReMEdy3DArena.jar` (JSR-184 3D benchmark), `AstroBlaster240.jar` (`GameCanvas` space shooter), and `NetToolJ2ME.jar` (LCDUI + HTTP/TCP socket test suite). ### 3.2 Multi-mode `fcitx5-t9` keypad reference diff --git a/overlay/rootfs/usr/bin/remedy b/overlay/rootfs/usr/bin/remedy index 71fe1ae..da2f922 100755 Binary files a/overlay/rootfs/usr/bin/remedy and b/overlay/rootfs/usr/bin/remedy differ diff --git a/prebuilt/games/usr/bin/remedy b/prebuilt/games/usr/bin/remedy index 71fe1ae..da2f922 100755 Binary files a/prebuilt/games/usr/bin/remedy and b/prebuilt/games/usr/bin/remedy differ diff --git a/src/games/remedy/remedy_cldc_net_media.hpp b/src/games/remedy/remedy_cldc_net_media.hpp index f9117b7..d43bac0 100644 --- a/src/games/remedy/remedy_cldc_net_media.hpp +++ b/src/games/remedy/remedy_cldc_net_media.hpp @@ -17,6 +17,9 @@ #include #include #include +#include +#include +#include #include #include #include @@ -24,16 +27,21 @@ namespace remedy { // --------------------------------------------------------------------------- -// ALSA Low-Latency Tone, MIDI & WAV Audio Engine (JSR-135 MMAPI) +// ALSA Low-Latency Tone, Standard MIDI (Format 0/1) & WAV Audio Engine // --------------------------------------------------------------------------- class AlsaSoundEngine { public: + static constexpr unsigned int kSampleRate = 48000; + // ReMEdy's own audio on/off toggle (pause menu "Audio" item, remedy.cfg). bool enabled = true; - int volumePct = 80; + // Mirror of the system-wide speaker volume (0..100), as set by the xdrawer + // "Speaker" slider and stored in $XDG_CONFIG_HOME/sxmo/speaker_vol. + std::atomic volumePct{100}; ~AlsaSoundEngine() { shutdown(); } void init() { + refreshSystemVolume(true); if (running_.exchange(true)) return; worker_ = std::thread([this]() { audioThreadLoop(); }); } @@ -43,14 +51,161 @@ class AlsaSoundEngine { if (worker_.joinable()) worker_.join(); } - // Play a MIDI note (0..127, 69 = A4 = 440Hz) for durationMs + void setPaused(bool p) { paused_.store(p, std::memory_order_relaxed); } + + bool isSystemMuted() const { + return sysMuted_.load(std::memory_order_relaxed); + } + + static std::string sxmoConfigDir() { + const char* xdg = std::getenv("XDG_CONFIG_HOME"); + if (xdg && *xdg) return std::string(xdg) + "/sxmo"; + const char* home = std::getenv("HOME"); + return std::string(home && *home ? home : "/home/user") + "/.config/sxmo"; + } + + // Kept for callers that re-sync after returning from xdrawer. + void loadSavedSpeakerVol() { refreshSystemVolume(true); } + + // Re-read the system speaker volume. It follows the same rules as xdrawer: + // the percentage comes from speaker_vol (falling back to the WCD9302 + // "RX3 Digital Volume" control when the file does not exist yet), and the + // speaker is muted when "SPK DAC Switch" is off or the volume is 0. + // Cheap enough to call from the mixer thread every 500 ms: it stats the + // file and only re-reads it when its mtime changes, and samples the two + // ALSA controls directly. + void refreshSystemVolume(bool force) { + std::lock_guard lk(volMu_); + std::string path = sxmoConfigDir() + "/speaker_vol"; + struct stat st {}; + bool haveFile = (::stat(path.c_str(), &st) == 0); + int64_t mtimeNs = haveFile ? (static_cast(st.st_mtim.tv_sec) * + 1000000000LL + + st.st_mtim.tv_nsec) + : -1; + if (force || mtimeNs != lastVolMtimeNs_) { + lastVolMtimeNs_ = mtimeNs; + filePct_ = -1; + if (haveFile) { + FILE* f = std::fopen(path.c_str(), "r"); + if (f) { + int v = -1; + if (std::fscanf(f, "%d", &v) == 1 && v >= 0 && v <= 100) { + filePct_ = v; + } + std::fclose(f); + } + } + } + + bool spkOn = true; + long rx3 = 92; + snd_ctl_t* ctl = nullptr; + if (snd_ctl_open(&ctl, "hw:0", 0) == 0 && ctl) { + spkOn = readCtlBool(ctl, "SPK DAC Switch", true); + rx3 = readCtlInt(ctl, "RX3 Digital Volume", 92); + snd_ctl_close(ctl); + } + + int pct = filePct_; + if (pct < 0) { + // Same RX3 -> percentage mapping as xdrawer (60..92 => 0..100%) + if (rx3 <= 0) { + pct = 0; + } else if (rx3 >= 92) { + pct = 100; + } else { + pct = std::clamp(static_cast(std::lround(((rx3 - 60) * 100.0) / + 32.0)), + 5, 100); + } + } + volumePct.store(pct, std::memory_order_relaxed); + bool muted = !spkOn || pct <= 0; + sysMuted_.store(muted, std::memory_order_relaxed); + // PipeWire clients get the sink volume applied as a cubic curve on top of + // the RX3 hardware attenuation; ReMEdy writes to hw:0,0 directly, so it + // applies the same cubic software gain to sound exactly as loud as every + // other application at the same system volume. + float lin = pct / 100.0f; + sysGain_.store(muted ? 0.0f : lin * lin * lin, std::memory_order_relaxed); + } + + // Change the system-wide speaker volume exactly like the xdrawer "Speaker" + // slider does: persist speaker_vol, program the WCD9302 RX3 digital gain + // (60..92), unmute the speaker DAC, and mirror the level into the PipeWire + // default sink so every application follows the same setting. + void setSystemVolume(int pct) { + pct = std::clamp(pct, 0, 100); + std::string dir = sxmoConfigDir(); + ::mkdir(dir.c_str(), 0755); + { + FILE* f = std::fopen((dir + "/speaker_vol").c_str(), "w"); + if (f) { + std::fprintf(f, "%d\n", pct); + std::fclose(f); + } + } + snd_ctl_t* ctl = nullptr; + if (snd_ctl_open(&ctl, "hw:0", 0) == 0 && ctl) { + long hw = (pct <= 0) ? 0 : (60 + std::lround((pct * 32.0) / 100.0)); + if (pct > 0) { + writeCtlBool(ctl, "SPK DAC Switch", true); + writeCtlEnum(ctl, "RX3 MIX1 INP1", 3); + } + writeCtlInt(ctl, "RX3 Digital Volume", hw); + snd_ctl_close(ctl); + } + char cmd[200]; + std::snprintf(cmd, sizeof(cmd), + "(wpctl set-mute @DEFAULT_AUDIO_SINK@ %d; " + "wpctl set-volume @DEFAULT_AUDIO_SINK@ %d%%; " + "sxmo_hook_statusbar.sh volume) >/dev/null 2>&1 &", + (pct <= 0) ? 1 : 0, pct); + std::thread([c = std::string(cmd)]() { (void)std::system(c.c_str()); }) + .detach(); + refreshSystemVolume(true); + } + + // Backwards-compatible name used by the pause menu / volume keys. + void setHardwareVolume(int pct) { setSystemVolume(pct); } + + static float perceptualGain(int levelPct) { + if (levelPct <= 0) return 0.0f; + if (levelPct >= 100) return 1.0f; + // MIDP VolumeControl levels are meant to be linear in perceived loudness. + // Loudness grows roughly with amplitude^0.6, so map level -> amplitude + // with an exponent of ~1.5 (level 50 -> ~35%, 25 -> ~13%, 80 -> ~72%). + return std::pow(std::clamp(levelPct, 0, 100) / 100.0f, 1.5f); + } + + // 4096-entry sine table shared by the synth voices (avoids libm sin() + // calls in the per-sample hot loop on Cortex-A7). + static float fastSin01(float phase01) { + static const std::vector kTable = []() { + std::vector t(4097); + for (int i = 0; i <= 4096; ++i) { + t[i] = static_cast(std::sin(i * 6.283185307179586 / 4096.0)); + } + return t; + }(); + float pos = phase01 * 4096.0f; + int idx = static_cast(pos); + if (idx < 0) idx = 0; + if (idx > 4095) idx = 4095; + float frac = pos - static_cast(idx); + return kTable[idx] + (kTable[idx + 1] - kTable[idx]) * frac; + } + + // Play a standalone MIDI note (0..127, 69 = A4 = 440Hz) for durationMs void playTone(int note, int durationMs, int vol) { if (!enabled || durationMs <= 0 || vol <= 0) return; float freq = 440.0f * std::pow(2.0f, (note - 69) / 12.0f); - freq = std::clamp(freq, 55.0f, 8000.0f); - int samples = std::clamp((durationMs * 24000) / 1000, 120, 24000 * 10); - float amp = std::clamp(vol / 100.0f, 0.05f, 1.0f) * - (volumePct / 100.0f) * 0.35f; + freq = std::clamp(freq, 45.0f, 8000.0f); + int samples = + std::clamp(static_cast((durationMs * int64_t(kSampleRate)) / 1000), + 240, static_cast(kSampleRate * 10)); + float amp = perceptualGain(vol) * 0.28f; std::lock_guard lk(mu_); ActiveVoice v; v.freq = freq; @@ -58,73 +213,109 @@ class AlsaSoundEngine { v.remainingSamples = samples; v.totalSamples = samples; v.amp = amp; - if (voices_.size() < 8) { + if (voices_.size() < 12) { voices_.push_back(v); } else { voices_[0] = v; } + lastActiveMs_ = nowMs(); + } + + // Play or start a player buffer (WAV, Standard MIDI Format 0/1, or Tone sequence) + void startPlayerBytes(int playerId, const std::vector& rawData, + bool loop, int playerVolPct = 80) { + if (rawData.empty()) { + playTone(69, 90, playerVolPct); + return; + } + // Check for Standard MIDI ("MThd") + if (rawData.size() >= 14 && std::memcmp(rawData.data(), "MThd", 4) == 0) { + startMidiBytes(playerId, rawData, loop, playerVolPct); + return; + } + // Check for RIFF WAVE ("RIFF" ... "WAVE") + if (rawData.size() >= 44 && std::memcmp(rawData.data(), "RIFF", 4) == 0 && + std::memcmp(rawData.data() + 8, "WAVE", 4) == 0) { + startWavBytes(playerId, rawData, loop, playerVolPct); + return; + } + // Check for JSR-135 ToneControl sequence or Nokia Smart Messaging / OTA tone + if (startToneSequenceBytes(playerId, rawData, loop, playerVolPct)) { + return; + } + // Fallback brief pleasant chime + if (playerVolPct > 0) { + playTone(64, 90, playerVolPct); + playTone(71, 110, playerVolPct); + } } void playWavBytes(const std::vector& wavData, bool loop = false) { - if (!enabled || wavData.size() < 44) return; - if (std::memcmp(wavData.data(), "RIFF", 4) != 0 || - std::memcmp(wavData.data() + 8, "WAVE", 4) != 0) { - // Fallback: play a pleasant chord if non-WAV (e.g. MIDI header) - playTone(60, 120, 80); - playTone(64, 140, 80); - playTone(67, 180, 80); - return; - } - uint16_t channels = readLe16(wavData.data() + 22); - uint32_t sampleRate = readLe32(wavData.data() + 24); - uint16_t bitsPerSample = readLe16(wavData.data() + 34); - if (channels == 0 || sampleRate == 0) return; + startPlayerBytes(0, wavData, loop, 85); + } - size_t pos = 12; - const uint8_t* pcmPtr = nullptr; - size_t pcmBytes = 0; - while (pos + 8 <= wavData.size()) { - uint32_t chunkSz = readLe32(wavData.data() + pos + 4); - if (std::memcmp(wavData.data() + pos, "data", 4) == 0) { - pcmPtr = wavData.data() + pos + 8; - pcmBytes = std::min(chunkSz, wavData.size() - (pos + 8)); - break; - } - pos += 8 + chunkSz + (chunkSz & 1u); - } - if (!pcmPtr || pcmBytes == 0) return; - - std::vector resampled; - size_t frameSize = channels * (bitsPerSample / 8); - if (frameSize == 0) return; - size_t totalFrames = pcmBytes / frameSize; - size_t outFrames = (totalFrames * 24000ULL) / sampleRate; - outFrames = std::min(outFrames, 24000 * 30); - resampled.resize(outFrames); - for (size_t i = 0; i < outFrames; ++i) { - size_t srcIdx = (i * sampleRate) / 24000ULL; - if (srcIdx >= totalFrames) srcIdx = totalFrames - 1; - const uint8_t* fptr = pcmPtr + srcIdx * frameSize; - int16_t s = 0; - if (bitsPerSample == 16) { - s = static_cast(readLe16(fptr)); - } else if (bitsPerSample == 8) { - s = static_cast((static_cast(fptr[0]) - 128) << 8); - } - resampled[i] = s; - } + void setPlayerVolume(int playerId, int volPct) { + float g = perceptualGain(volPct); std::lock_guard lk(mu_); - pcmVoice_ = std::move(resampled); - pcmPos_ = 0; - pcmLoop_ = loop; + playerGains_[playerId] = g; + if (midiSeq_.active && midiSeq_.playerId == playerId) { + midiSeq_.gain = g; + } + for (auto& s : pcmStreams_) { + if (s.playerId == playerId) { + s.gain = g; + } + } + } + + void stopPlayer(int playerId) { + std::lock_guard lk(mu_); + if (midiSeq_.active && midiSeq_.playerId == playerId) { + midiSeq_.active = false; + for (auto& mv : midiVoices_) { + if (mv.active && !mv.releasing) { + mv.releasing = true; + mv.releaseRemaining = 480; + } + } + } + for (auto it = pcmStreams_.begin(); it != pcmStreams_.end();) { + if (it->playerId == playerId) { + it = pcmStreams_.erase(it); + } else { + ++it; + } + } + } + + void rewindPlayer(int playerId) { + std::lock_guard lk(mu_); + if (midiSeq_.playerId == playerId) { + midiSeq_.currentFrame = 0; + midiSeq_.eventIdx = 0; + } + for (auto& s : pcmStreams_) { + if (s.playerId == playerId) { + s.pos = 0; + } + } + } + + bool isPlayerActive(int playerId) { + std::lock_guard lk(mu_); + if (midiSeq_.active && midiSeq_.playerId == playerId) return true; + for (const auto& s : pcmStreams_) { + if (s.playerId == playerId && s.pos < s.samples.size()) return true; + } + return false; } void stopAll() { std::lock_guard lk(mu_); voices_.clear(); - pcmVoice_.clear(); - pcmPos_ = 0; - pcmLoop_ = false; + pcmStreams_.clear(); + midiSeq_.active = false; + midiVoices_.clear(); } private: @@ -136,87 +327,940 @@ class AlsaSoundEngine { float amp = 0.2f; }; + struct ActivePcmStream { + int playerId = 0; + std::vector samples; + size_t pos = 0; + bool loop = false; + float gain = 0.8f; + }; + + struct MidiEvent { + uint64_t frame = 0; + uint8_t type = 0; // 0x80 NoteOff, 0x90 NoteOn, 0xB0 CC, 0xC0 Prog, 0xE0 Bend + uint8_t channel = 0; + uint8_t data1 = 0; + uint8_t data2 = 0; + }; + + struct MidiSequence { + int playerId = -1; + bool active = false; + bool loop = false; + float gain = 0.8f; + std::vector events; + size_t eventIdx = 0; + uint64_t currentFrame = 0; + uint64_t totalFrames = 0; + uint8_t chProgram[16] = {0}; + uint8_t chVolume[16] = {100, 100, 100, 100, 100, 100, 100, 100, + 100, 100, 100, 100, 100, 100, 100, 100}; + uint8_t chExpr[16] = {127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 127, 127, 127, 127}; + float chPitchBend[16] = {0.0f}; + }; + + struct MidiVoice { + bool active = false; + bool isDrum = false; + uint8_t channel = 0; + uint8_t note = 60; + uint8_t program = 0; + float baseFreq = 440.0f; + float phase = 0.0f; + float subPhase = 0.0f; + float velocityGain = 0.5f; + float env = 0.0f; + float sustainLevel = 0.45f; + float decayRate = 0.00004f; + bool releasing = false; + int releaseRemaining = 0; + int ageSamples = 0; + int maxSamples = 48000 * 6; + }; + std::atomic running_{false}; + std::atomic paused_{false}; std::thread worker_; std::mutex mu_; + + // System speaker volume tracking (see refreshSystemVolume) + std::mutex volMu_; + int64_t lastVolMtimeNs_ = -2; + int filePct_ = -1; + std::atomic sysMuted_{false}; + std::atomic sysGain_{1.0f}; + int64_t lastVolPollMs_ = 0; + + static snd_ctl_elem_value_t* prepCtlValue(snd_ctl_elem_value_t* val, + snd_ctl_elem_id_t* id, + const char* name) { + snd_ctl_elem_id_set_interface(id, SND_CTL_ELEM_IFACE_MIXER); + snd_ctl_elem_id_set_name(id, name); + snd_ctl_elem_value_set_id(val, id); + return val; + } + + static long readCtlInt(snd_ctl_t* ctl, const char* name, long fallback) { + snd_ctl_elem_id_t* id = nullptr; + snd_ctl_elem_value_t* val = nullptr; + snd_ctl_elem_id_alloca(&id); + snd_ctl_elem_value_alloca(&val); + prepCtlValue(val, id, name); + if (snd_ctl_elem_read(ctl, val) < 0) return fallback; + return snd_ctl_elem_value_get_integer(val, 0); + } + + static bool readCtlBool(snd_ctl_t* ctl, const char* name, bool fallback) { + snd_ctl_elem_id_t* id = nullptr; + snd_ctl_elem_value_t* val = nullptr; + snd_ctl_elem_id_alloca(&id); + snd_ctl_elem_value_alloca(&val); + prepCtlValue(val, id, name); + if (snd_ctl_elem_read(ctl, val) < 0) return fallback; + return snd_ctl_elem_value_get_boolean(val, 0) != 0; + } + + static void writeCtlInt(snd_ctl_t* ctl, const char* name, long v) { + snd_ctl_elem_id_t* id = nullptr; + snd_ctl_elem_value_t* val = nullptr; + snd_ctl_elem_id_alloca(&id); + snd_ctl_elem_value_alloca(&val); + prepCtlValue(val, id, name); + snd_ctl_elem_value_set_integer(val, 0, v); + (void)snd_ctl_elem_write(ctl, val); + } + + static void writeCtlBool(snd_ctl_t* ctl, const char* name, bool v) { + snd_ctl_elem_id_t* id = nullptr; + snd_ctl_elem_value_t* val = nullptr; + snd_ctl_elem_id_alloca(&id); + snd_ctl_elem_value_alloca(&val); + prepCtlValue(val, id, name); + snd_ctl_elem_value_set_boolean(val, 0, v ? 1 : 0); + (void)snd_ctl_elem_write(ctl, val); + } + + static void writeCtlEnum(snd_ctl_t* ctl, const char* name, unsigned int v) { + snd_ctl_elem_id_t* id = nullptr; + snd_ctl_elem_value_t* val = nullptr; + snd_ctl_elem_id_alloca(&id); + snd_ctl_elem_value_alloca(&val); + prepCtlValue(val, id, name); + snd_ctl_elem_value_set_enumerated(val, 0, v); + (void)snd_ctl_elem_write(ctl, val); + } + std::unordered_map playerGains_; std::vector voices_; - std::vector pcmVoice_; - size_t pcmPos_ = 0; - bool pcmLoop_ = false; + std::vector pcmStreams_; + MidiSequence midiSeq_; + std::vector midiVoices_; + uint32_t noiseLfsr_ = 0xACE1u; + int64_t lastActiveMs_ = 0; + float lpStage1L_ = 0.0f; + float lpStage2L_ = 0.0f; + int16_t lastSample_ = 0; + + static uint16_t readBe16(const uint8_t* p) { + return static_cast((static_cast(p[0]) << 8) | p[1]); + } + + static uint32_t readBe32(const uint8_t* p) { + return (static_cast(p[0]) << 24) | + (static_cast(p[1]) << 16) | + (static_cast(p[2]) << 8) | + static_cast(p[3]); + } + + static uint32_t readMidiVarLen(const uint8_t* data, size_t len, size_t& pos) { + uint32_t val = 0; + for (int i = 0; i < 4 && pos < len; ++i) { + uint8_t b = data[pos++]; + val = (val << 7) | (b & 0x7Fu); + if ((b & 0x80u) == 0) break; + } + return val; + } + + void startWavBytes(int playerId, const std::vector& wavData, + bool loop, int playerVolPct) { + uint16_t audioFmt = readLe16(wavData.data() + 20); + uint16_t channels = readLe16(wavData.data() + 22); + uint32_t sampleRate = readLe32(wavData.data() + 24); + uint16_t blockAlign = readLe16(wavData.data() + 32); + uint16_t bitsPerSample = readLe16(wavData.data() + 34); + if (channels == 0 || sampleRate == 0) return; + + size_t pos = 12; + const uint8_t* pcmPtr = nullptr; + size_t pcmBytes = 0; + while (pos + 8 <= wavData.size()) { + uint32_t chunkSz = readLe32(wavData.data() + pos + 4); + if (std::memcmp(wavData.data() + pos, "fmt ", 4) == 0 && + pos + 8 + 16 <= wavData.size()) { + audioFmt = readLe16(wavData.data() + pos + 8); + channels = readLe16(wavData.data() + pos + 10); + sampleRate = readLe32(wavData.data() + pos + 12); + blockAlign = readLe16(wavData.data() + pos + 20); + bitsPerSample = readLe16(wavData.data() + pos + 22); + } else if (std::memcmp(wavData.data() + pos, "data", 4) == 0) { + pcmPtr = wavData.data() + pos + 8; + pcmBytes = std::min(chunkSz, wavData.size() - (pos + 8)); + break; + } + pos += 8 + chunkSz + (chunkSz & 1u); + } + if (!pcmPtr || pcmBytes == 0 || channels == 0 || sampleRate == 0) return; + + std::vector srcMono; + if (audioFmt == 1 && (bitsPerSample == 8 || bitsPerSample == 16)) { + size_t frameSize = channels * (bitsPerSample / 8); + if (frameSize == 0) return; + size_t totalFrames = pcmBytes / frameSize; + srcMono.resize(totalFrames); + for (size_t i = 0; i < totalFrames; ++i) { + const uint8_t* fptr = pcmPtr + i * frameSize; + int32_t sum = 0; + for (uint16_t ch = 0; ch < channels; ++ch) { + if (bitsPerSample == 16) { + sum += static_cast(readLe16(fptr + ch * 2)); + } else { + sum += (static_cast(fptr[ch]) - 128) << 8; + } + } + srcMono[i] = static_cast(sum / channels); + } + } else if (audioFmt == 17 && blockAlign > 0) { + // IMA ADPCM mono/stereo fallback decoding + static const int kIndexTable[16] = {-1, -1, -1, -1, 2, 4, 6, 8, + -1, -1, -1, -1, 2, 4, 6, 8}; + static const int kStepTable[89] = { + 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, + 19, 21, 23, 25, 28, 31, 34, 37, 41, 45, + 50, 55, 60, 66, 73, 80, 88, 97, 107, 118, + 130, 143, 157, 173, 190, 209, 230, 253, 279, 307, + 337, 371, 408, 449, 494, 544, 598, 658, 724, 796, + 876, 963, 1060, 1166, 1282, 1411, 1552, 1707, 1878, 2066, + 2272, 2499, 2749, 3024, 3327, 3660, 4026, 4428, 4871, 5358, + 5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899, + 15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767}; + size_t offset = 0; + while (offset + 4 <= pcmBytes) { + size_t blkLen = std::min(blockAlign, pcmBytes - offset); + const uint8_t* blk = pcmPtr + offset; + int predictor = static_cast(readLe16(blk)); + int stepIdx = std::clamp(blk[2], 0, 88); + srcMono.push_back(static_cast(predictor)); + for (size_t b = 4 * channels; b < blkLen; ++b) { + uint8_t byteVal = blk[b]; + for (int nibShift = 0; nibShift <= 4; nibShift += 4) { + int nib = (byteVal >> nibShift) & 0x0F; + int step = kStepTable[stepIdx]; + int diff = step >> 3; + if (nib & 4) diff += step; + if (nib & 2) diff += step >> 1; + if (nib & 1) diff += step >> 2; + if (nib & 8) + predictor -= diff; + else + predictor += diff; + predictor = std::clamp(predictor, -32768, 32767); + stepIdx = std::clamp(stepIdx + kIndexTable[nib], 0, 88); + srcMono.push_back(static_cast(predictor)); + } + } + offset += blkLen; + } + } + if (srcMono.empty()) return; + + // Gentle pre-smoothing on 8-bit low-rate WAVs to remove quantization harshness + if (bitsPerSample == 8 && sampleRate <= 16000 && srcMono.size() >= 4) { + int32_t prev = srcMono[0]; + for (size_t i = 0; i < srcMono.size(); ++i) { + int32_t cur = srcMono[i]; + prev = (prev * 3 + cur * 5) >> 3; + srcMono[i] = static_cast(prev); + } + } + + size_t totalFrames = srcMono.size(); + size_t outFrames = + (totalFrames * static_cast(kSampleRate)) / sampleRate; + outFrames = std::clamp(outFrames, 1, kSampleRate * 30); + std::vector resampled(outFrames); + double step = static_cast(sampleRate) / static_cast(kSampleRate); + for (size_t i = 0; i < outFrames; ++i) { + double srcPos = i * step; + size_t idx0 = static_cast(srcPos); + if (idx0 >= totalFrames) idx0 = totalFrames - 1; + size_t idx1 = std::min(idx0 + 1, totalFrames - 1); + double frac = srcPos - static_cast(idx0); + double interp = + srcMono[idx0] * (1.0 - frac) + srcMono[idx1] * frac; + // Short fade-in/fade-out (2 ms = 96 samples) to prevent edge clicks + double env = 1.0; + if (i < 96) env = static_cast(i) / 96.0; + if (outFrames - i < 96) env = std::min(env, static_cast(outFrames - i) / 96.0); + resampled[i] = static_cast( + std::clamp(interp * env, -32768.0, 32767.0)); + } + + std::lock_guard lk(mu_); + float g = perceptualGain(playerVolPct); + auto it = playerGains_.find(playerId); + if (it != playerGains_.end()) g = it->second; + + for (auto& s : pcmStreams_) { + if (s.playerId == playerId) { + s.samples = std::move(resampled); + s.pos = 0; + s.loop = loop; + s.gain = g; + lastActiveMs_ = nowMs(); + return; + } + } + ActivePcmStream stream; + stream.playerId = playerId; + stream.samples = std::move(resampled); + stream.pos = 0; + stream.loop = loop; + stream.gain = g; + if (pcmStreams_.size() >= 6) { + pcmStreams_.erase(pcmStreams_.begin()); + } + pcmStreams_.push_back(std::move(stream)); + lastActiveMs_ = nowMs(); + } + + void startMidiBytes(int playerId, const std::vector& mid, bool loop, + int playerVolPct) { + if (mid.size() < 14 || std::memcmp(mid.data(), "MThd", 4) != 0) return; + uint32_t hdrLen = readBe32(mid.data() + 4); + uint16_t numTracks = readBe16(mid.data() + 10); + uint16_t division = readBe16(mid.data() + 12); + if (division == 0) division = 480; + + struct RawTickEvent { + uint64_t tick = 0; + uint32_t seqOrder = 0; + uint8_t type = 0; // 0xFF = tempo (tempoUs), else MIDI status high nibble + uint8_t channel = 0; + uint8_t data1 = 0; + uint8_t data2 = 0; + uint32_t tempoUs = 500000; + }; + + std::vector rawEvents; + rawEvents.reserve(2048); + uint32_t orderCounter = 0; + + size_t pos = 8 + hdrLen; + for (uint16_t trk = 0; trk < numTracks && pos + 8 <= mid.size(); ++trk) { + if (std::memcmp(mid.data() + pos, "MTrk", 4) != 0) { + uint32_t skipSz = readBe32(mid.data() + pos + 4); + pos += 8 + skipSz; + continue; + } + uint32_t trkLen = readBe32(mid.data() + pos + 4); + size_t trkEnd = std::min(mid.size(), pos + 8 + trkLen); + size_t tpos = pos + 8; + uint64_t absTick = 0; + uint8_t runningStatus = 0; + + while (tpos < trkEnd) { + uint32_t delta = readMidiVarLen(mid.data(), trkEnd, tpos); + absTick += delta; + if (tpos >= trkEnd) break; + + uint8_t status = mid[tpos]; + if (status < 0x80) { + status = runningStatus; + } else { + tpos++; + if (status < 0xF0) runningStatus = status; + } + + if (status == 0xFF) { + if (tpos >= trkEnd) break; + uint8_t metaType = mid[tpos++]; + uint32_t metaLen = readMidiVarLen(mid.data(), trkEnd, tpos); + if (metaType == 0x51 && metaLen == 3 && tpos + 3 <= trkEnd) { + uint32_t usPerQn = (static_cast(mid[tpos]) << 16) | + (static_cast(mid[tpos + 1]) << 8) | + static_cast(mid[tpos + 2]); + if (usPerQn > 0) { + RawTickEvent ev; + ev.tick = absTick; + ev.seqOrder = orderCounter++; + ev.type = 0xFF; + ev.tempoUs = usPerQn; + rawEvents.push_back(ev); + } + } else if (metaType == 0x2F) { + tpos += metaLen; + break; + } + tpos = std::min(trkEnd, tpos + metaLen); + } else if (status == 0xF0 || status == 0xF7) { + uint32_t sysexLen = readMidiVarLen(mid.data(), trkEnd, tpos); + tpos = std::min(trkEnd, tpos + sysexLen); + } else { + uint8_t hi = status & 0xF0u; + uint8_t ch = status & 0x0Fu; + if (hi == 0x80 || hi == 0x90 || hi == 0xA0 || hi == 0xB0 || + hi == 0xE0) { + if (tpos + 2 > trkEnd) break; + uint8_t d1 = mid[tpos++] & 0x7Fu; + uint8_t d2 = mid[tpos++] & 0x7Fu; + RawTickEvent ev; + ev.tick = absTick; + ev.seqOrder = orderCounter++; + ev.type = (hi == 0x90 && d2 == 0) ? 0x80 : hi; + ev.channel = ch; + ev.data1 = d1; + ev.data2 = d2; + rawEvents.push_back(ev); + } else if (hi == 0xC0 || hi == 0xD0) { + if (tpos + 1 > trkEnd) break; + uint8_t d1 = mid[tpos++] & 0x7Fu; + RawTickEvent ev; + ev.tick = absTick; + ev.seqOrder = orderCounter++; + ev.type = hi; + ev.channel = ch; + ev.data1 = d1; + ev.data2 = 0; + rawEvents.push_back(ev); + } else { + break; + } + } + } + pos = trkEnd; + } + + if (rawEvents.empty()) return; + + std::sort(rawEvents.begin(), rawEvents.end(), + [](const RawTickEvent& a, const RawTickEvent& b) { + if (a.tick != b.tick) return a.tick < b.tick; + return a.seqOrder < b.seqOrder; + }); + + // Convert ticks to 48000 Hz audio frames using tempo map + std::vector frameEvents; + frameEvents.reserve(rawEvents.size()); + double currentFrameD = 0.0; + uint64_t prevTick = 0; + double usPerTick = 500000.0 / static_cast(division); + if (division & 0x8000u) { + int fps = -static_cast((division >> 8) & 0xFF); + int tpf = division & 0xFF; + if (fps > 0 && tpf > 0) usPerTick = 1000000.0 / (fps * tpf); + } + + for (const auto& rev : rawEvents) { + uint64_t dt = rev.tick - prevTick; + currentFrameD += + (static_cast(dt) * usPerTick * kSampleRate) / 1000000.0; + prevTick = rev.tick; + + if (rev.type == 0xFF) { + if ((division & 0x8000u) == 0) { + usPerTick = + static_cast(rev.tempoUs) / static_cast(division); + } + } else if (rev.type == 0x80 || rev.type == 0x90 || rev.type == 0xB0 || + rev.type == 0xC0 || rev.type == 0xE0) { + MidiEvent mev; + mev.frame = static_cast(currentFrameD); + mev.type = rev.type; + mev.channel = rev.channel; + mev.data1 = rev.data1; + mev.data2 = rev.data2; + frameEvents.push_back(mev); + } + } + + if (frameEvents.empty()) return; + + std::lock_guard lk(mu_); + float g = perceptualGain(playerVolPct); + auto it = playerGains_.find(playerId); + if (it != playerGains_.end()) g = it->second; + + midiSeq_ = MidiSequence{}; + midiSeq_.playerId = playerId; + midiSeq_.active = true; + midiSeq_.loop = loop; + midiSeq_.gain = g; + midiSeq_.events = std::move(frameEvents); + midiSeq_.totalFrames = + midiSeq_.events.back().frame + (kSampleRate / 5); // +200ms tail + midiVoices_.clear(); + lastActiveMs_ = nowMs(); + } + + bool startToneSequenceBytes(int playerId, const std::vector& seq, + bool loop, int playerVolPct) { + if (seq.size() < 4) return false; + // JSR-135 ToneControl sequence starts with VERSION (-2 = 0xFE, 1) + std::vector evs; + uint64_t curFrame = 0; + int tempoBpm = 120; + int resolution = 64; + + if (static_cast(seq[0]) == -2) { + size_t i = 2; + while (i + 1 < seq.size()) { + int8_t cmd = static_cast(seq[i]); + uint8_t param = seq[i + 1]; + i += 2; + if (cmd == -3) { // TEMPO (BPM = param * 4) + tempoBpm = std::max(20, param * 4); + } else if (cmd == -4) { // RESOLUTION + resolution = std::max(1, param); + } else if (cmd >= -1 && param > 0) { + uint64_t durFrames = + (static_cast(param) * 240ULL * kSampleRate) / + (static_cast(tempoBpm) * resolution); + durFrames = std::clamp(durFrames, 480, kSampleRate * 4); + if (cmd >= 0) { + MidiEvent on{curFrame, 0x90, 0, static_cast(cmd), 100}; + MidiEvent off{curFrame + (durFrames * 9) / 10, 0x80, 0, + static_cast(cmd), 0}; + evs.push_back(on); + evs.push_back(off); + } + curFrame += durFrames; + } + } + } + if (evs.empty()) return false; + + std::lock_guard lk(mu_); + float g = perceptualGain(playerVolPct); + auto it = playerGains_.find(playerId); + if (it != playerGains_.end()) g = it->second; + + midiSeq_ = MidiSequence{}; + midiSeq_.playerId = playerId; + midiSeq_.active = true; + midiSeq_.loop = loop; + midiSeq_.gain = g; + midiSeq_.events = std::move(evs); + midiSeq_.totalFrames = curFrame + (kSampleRate / 10); + midiVoices_.clear(); + lastActiveMs_ = nowMs(); + return true; + } + + void triggerMidiEventLocked(const MidiEvent& ev) { + uint8_t ch = ev.channel & 0x0Fu; + if (ev.type == 0x80) { + for (auto& mv : midiVoices_) { + if (mv.active && mv.channel == ch && mv.note == ev.data1 && + !mv.releasing) { + mv.releasing = true; + mv.releaseRemaining = 960; // 20ms smooth release + } + } + } else if (ev.type == 0x90) { + // Retrigger existing voice on same channel + note if present + for (auto& mv : midiVoices_) { + if (mv.active && mv.channel == ch && mv.note == ev.data1) { + initMidiVoice(mv, ch, ev.data1, ev.data2); + return; + } + } + for (auto& mv : midiVoices_) { + if (!mv.active) { + initMidiVoice(mv, ch, ev.data1, ev.data2); + return; + } + } + if (midiVoices_.size() < 16) { + MidiVoice mv; + initMidiVoice(mv, ch, ev.data1, ev.data2); + midiVoices_.push_back(mv); + } else { + // Steal oldest releasing or oldest voice + size_t bestIdx = 0; + int bestScore = -1; + for (size_t i = 0; i < midiVoices_.size(); ++i) { + int score = midiVoices_[i].ageSamples + + (midiVoices_[i].releasing ? 200000 : 0); + if (score > bestScore) { + bestScore = score; + bestIdx = i; + } + } + initMidiVoice(midiVoices_[bestIdx], ch, ev.data1, ev.data2); + } + } else if (ev.type == 0xB0) { + if (ev.data1 == 7) { + midiSeq_.chVolume[ch] = ev.data2; + } else if (ev.data1 == 11) { + midiSeq_.chExpr[ch] = ev.data2; + } else if (ev.data1 == 120 || ev.data1 == 123) { + for (auto& mv : midiVoices_) { + if (mv.active && mv.channel == ch) { + mv.releasing = true; + mv.releaseRemaining = 480; + } + } + } + } else if (ev.type == 0xC0) { + midiSeq_.chProgram[ch] = ev.data1; + } else if (ev.type == 0xE0) { + int bend = (static_cast(ev.data2) << 7) | ev.data1; + midiSeq_.chPitchBend[ch] = (bend - 8192) / 4096.0f; // +/- 2 semitones + } + } + + void initMidiVoice(MidiVoice& mv, uint8_t ch, uint8_t note, uint8_t vel) { + mv = MidiVoice{}; + mv.active = true; + mv.channel = ch; + mv.note = note; + mv.program = midiSeq_.chProgram[ch]; + mv.isDrum = (ch == 9); + mv.baseFreq = + 440.0f * + std::pow(2.0f, (note - 69 + midiSeq_.chPitchBend[ch]) / 12.0f); + mv.baseFreq = std::clamp(mv.baseFreq, 32.0f, 9000.0f); + mv.velocityGain = std::pow(std::clamp(vel, 1, 127) / 127.0f, 0.7f); + mv.env = 0.05f; + mv.releasing = false; + mv.releaseRemaining = 960; + mv.ageSamples = 0; + + if (mv.isDrum) { + mv.sustainLevel = 0.0f; + if (note == 35 || note == 36) { + mv.baseFreq = 135.0f; // Kick drum + mv.decayRate = 0.00032f; + mv.maxSamples = kSampleRate / 3; + } else if (note == 38 || note == 40) { + mv.baseFreq = 185.0f; // Snare drum + mv.decayRate = 0.00028f; + mv.maxSamples = kSampleRate / 3; + } else if (note == 42 || note == 44) { + mv.baseFreq = 820.0f; // Closed hi-hat + mv.decayRate = 0.00075f; + mv.maxSamples = kSampleRate / 8; + } else { + mv.baseFreq = 420.0f; // Open hat / cymbal / tom + mv.decayRate = 0.00018f; + mv.maxSamples = kSampleRate / 2; + } + } else { + // GM instrument family envelope shaping + uint8_t family = mv.program / 8; + if (family == 0 || family == 1 || family == 3 || family == 4 || + family == 5 || family == 13) { + // Piano, Chromatic Percussion, Guitar, Bass, Plucked + mv.sustainLevel = 0.25f; + mv.decayRate = 0.000035f; + mv.maxSamples = kSampleRate * 4; + } else { + // Organ, Strings, Ensemble, Brass, Reed, Pipe, Synth Lead/Pad + mv.sustainLevel = 0.65f; + mv.decayRate = 0.000012f; + mv.maxSamples = kSampleRate * 8; + } + } + } + + float sampleMidiVoiceLocked(MidiVoice& mv) { + mv.ageSamples++; + if (mv.ageSamples >= mv.maxSamples && !mv.releasing) { + mv.releasing = true; + mv.releaseRemaining = 960; + } + + // Attack / Decay / Sustain / Release envelope + if (mv.releasing) { + if (mv.releaseRemaining <= 0) { + mv.active = false; + return 0.0f; + } + mv.env *= 0.9965f; + mv.releaseRemaining--; + if (mv.env < 0.001f) { + mv.active = false; + return 0.0f; + } + } else if (mv.ageSamples < 144) { + // 3ms linear attack + mv.env = static_cast(mv.ageSamples) / 144.0f; + } else { + mv.env += (mv.sustainLevel - mv.env) * mv.decayRate * 8.0f; + if (mv.isDrum && mv.env < 0.002f) { + mv.active = false; + return 0.0f; + } + } + + // Advance LFSR noise generator + uint32_t bit = ((noiseLfsr_ >> 0) ^ (noiseLfsr_ >> 2) ^ (noiseLfsr_ >> 3) ^ + (noiseLfsr_ >> 5)) & + 1u; + noiseLfsr_ = (noiseLfsr_ >> 1) | (bit << 15); + float noise = ((static_cast(noiseLfsr_ & 0xFFu) - 128) / 128.0f); + + float sample = 0.0f; + if (mv.isDrum) { + if (mv.note == 35 || mv.note == 36) { + // Kick: pitch drops rapidly toward 44Hz + mv.baseFreq = 44.0f + (mv.baseFreq - 44.0f) * 0.9982f; + mv.phase += mv.baseFreq / static_cast(kSampleRate); + if (mv.phase >= 1.0f) mv.phase -= 1.0f; + sample = fastSin01(mv.phase) * 0.85f + + (mv.ageSamples < 240 ? noise * 0.25f : 0.0f); + } else if (mv.note == 38 || mv.note == 40) { + // Snare: body sine + snappy noise + mv.phase += mv.baseFreq / static_cast(kSampleRate); + if (mv.phase >= 1.0f) mv.phase -= 1.0f; + sample = fastSin01(mv.phase) * 0.35f + noise * 0.65f; + } else { + // Hi-hat / cymbal / percussion + mv.phase += mv.baseFreq / static_cast(kSampleRate); + if (mv.phase >= 1.0f) mv.phase -= 1.0f; + float metallic = (mv.phase < 0.5f ? 0.3f : -0.3f); + sample = noise * 0.55f + metallic * 0.25f; + } + } else { + float freq = mv.baseFreq; + mv.phase += freq / static_cast(kSampleRate); + if (mv.phase >= 1.0f) mv.phase -= 1.0f; + mv.subPhase += (freq * 0.5f) / static_cast(kSampleRate); + if (mv.subPhase >= 1.0f) mv.subPhase -= 1.0f; + + uint8_t family = mv.program / 8; + float duty = (family == 3 || family == 4) ? 0.25f : 0.5f; + float pulse = (mv.phase < duty) ? 0.42f : -0.42f; + float fundamental = fastSin01(mv.phase) * 0.45f; + float subOct = fastSin01(mv.subPhase) * 0.18f; + sample = pulse + fundamental + subOct; + } + + float chGain = (midiSeq_.chVolume[mv.channel] / 127.0f) * + (midiSeq_.chExpr[mv.channel] / 127.0f); + return sample * mv.env * mv.velocityGain * chGain * 0.2f; + } + + static bool configureLowLatency(snd_pcm_t* pcm, unsigned int rate, + snd_pcm_uframes_t periodSize = 256, + snd_pcm_uframes_t bufferSize = 1024) { + snd_pcm_hw_params_t* hw = nullptr; + snd_pcm_hw_params_alloca(&hw); + if (snd_pcm_hw_params_any(pcm, hw) < 0) return false; + if (snd_pcm_hw_params_set_access(pcm, hw, SND_PCM_ACCESS_RW_INTERLEAVED) < + 0) + return false; + if (snd_pcm_hw_params_set_format(pcm, hw, SND_PCM_FORMAT_S16_LE) < 0) + return false; + if (snd_pcm_hw_params_set_channels(pcm, hw, 2) < 0) return false; + if (snd_pcm_hw_params_set_rate_near(pcm, hw, &rate, nullptr) < 0) + return false; + if (snd_pcm_hw_params_set_period_size_near(pcm, hw, &periodSize, nullptr) < + 0) + return false; + if (snd_pcm_hw_params_set_buffer_size_near(pcm, hw, &bufferSize) < 0) + return false; + if (snd_pcm_hw_params(pcm, hw) < 0) return false; + + snd_pcm_sw_params_t* sw = nullptr; + snd_pcm_sw_params_alloca(&sw); + if (snd_pcm_sw_params_current(pcm, sw) == 0) { + snd_pcm_sw_params_set_start_threshold(pcm, sw, periodSize); + snd_pcm_sw_params_set_avail_min(pcm, sw, periodSize); + snd_pcm_sw_params(pcm, sw); + } + return true; + } void audioThreadLoop() { snd_pcm_t* pcm = nullptr; - constexpr unsigned int kRate = 24000; + // 512-frame periods in a 3072-frame ring (~64 ms at 48 kHz): small enough + // for responsive SFX, large enough that the synth thread survives being + // descheduled while the bytecode interpreter saturates a core. constexpr snd_pcm_uframes_t kPeriod = 512; + constexpr snd_pcm_uframes_t kBuffer = 3072; int16_t stereoBuf[kPeriod * 2]; - while (running_.load()) { - bool hasWork = false; + // Best effort: ask for real-time or raised priority for the mixer thread + // (silently ignored when the user lacks CAP_SYS_NICE / RLIMIT_RTPRIO). + { + sched_param sp{}; + sp.sched_priority = 10; + if (pthread_setschedparam(pthread_self(), SCHED_FIFO, &sp) != 0) { + (void)setpriority(PRIO_PROCESS, static_cast(::gettid()), -8); + } + } + + while (running_.load(std::memory_order_relaxed)) { + bool isPaused = paused_.load(std::memory_order_relaxed); + bool hasActiveAudio = false; + bool withinGraceWindow = false; + + // Follow live changes to the system speaker volume / mute (xdrawer, + // sxmo hooks, other apps) without restarting the MIDlet. + { + int64_t nowV = nowMs(); + if (nowV - lastVolPollMs_ >= 500) { + lastVolPollMs_ = nowV; + refreshSystemVolume(false); + } + } + bool sysMuted = sysMuted_.load(std::memory_order_relaxed); { std::lock_guard lk(mu_); - hasWork = !voices_.empty() || (pcmPos_ < pcmVoice_.size()); + hasActiveAudio = + !voices_.empty() || !pcmStreams_.empty() || midiSeq_.active; + if (!hasActiveAudio) { + for (const auto& mv : midiVoices_) { + if (mv.active) { + hasActiveAudio = true; + break; + } + } + } + int64_t now = nowMs(); + if (hasActiveAudio) { + lastActiveMs_ = now; + withinGraceWindow = true; + } else if (lastActiveMs_ > 0 && (now - lastActiveMs_) < 2500) { + // Keep ALSA open for 2.5s after sound completes so DMA finishes + // playing without truncation and back-to-back SFX have zero open lag + withinGraceWindow = true; + } } - if (!hasWork || !enabled) { + + if (!enabled || sysMuted || isPaused || !withinGraceWindow) { if (pcm) { snd_pcm_drop(pcm); snd_pcm_close(pcm); pcm = nullptr; } - ::usleep(12000); + ::usleep(10000); continue; } if (!pcm) { - if (snd_pcm_open(&pcm, "default", SND_PCM_STREAM_PLAYBACK, 0) < 0) { - if (snd_pcm_open(&pcm, "hw:0,0", SND_PCM_STREAM_PLAYBACK, 0) < 0) { - pcm = nullptr; - ::usleep(50000); - continue; + for (const char* dev : {"hw:0,0", "default", "plughw:0,0"}) { + if (snd_pcm_open(&pcm, dev, SND_PCM_STREAM_PLAYBACK, 0) == 0) { + if (!configureLowLatency(pcm, kSampleRate, kPeriod, kBuffer)) { + snd_pcm_set_params(pcm, SND_PCM_FORMAT_S16_LE, + SND_PCM_ACCESS_RW_INTERLEAVED, 2, kSampleRate, + 1, 64000); + } + break; } + pcm = nullptr; + } + if (!pcm) { + ::usleep(40000); + continue; } - snd_pcm_set_params(pcm, SND_PCM_FORMAT_S16_LE, - SND_PCM_ACCESS_RW_INTERLEAVED, 2, kRate, 1, 60000); } { std::lock_guard lk(mu_); - float masterGain = std::clamp(volumePct / 100.0f, 0.0f, 1.0f); + float masterGain = sysGain_.load(std::memory_order_relaxed); + for (size_t i = 0; i < kPeriod; ++i) { float mix = 0.0f; + + // 1. Standalone playTone voices for (auto it = voices_.begin(); it != voices_.end();) { if (it->remainingSamples <= 0) { it = voices_.erase(it); continue; } float env = 1.0f; - if (it->remainingSamples < 240) { - env = it->remainingSamples / 240.0f; + if (it->remainingSamples < 480) { + env = it->remainingSamples / 480.0f; } - // Rich square+sine retro J2ME synth tone - float s = (it->phase < 0.5f ? 0.6f : -0.6f) + - 0.4f * std::sin(it->phase * 6.2831853f); - mix += s * it->amp * env; - it->phase += it->freq / static_cast(kRate); + float s = (it->phase < 0.5f ? 0.55f : -0.55f) + + 0.45f * fastSin01(it->phase); + mix += s * it->amp * env * masterGain; + it->phase += it->freq / static_cast(kSampleRate); if (it->phase >= 1.0f) it->phase -= 1.0f; it->remainingSamples--; ++it; } - if (pcmPos_ < pcmVoice_.size()) { - mix += (pcmVoice_[pcmPos_++] / 32768.0f) * masterGain * 0.8f; - if (pcmPos_ >= pcmVoice_.size() && pcmLoop_) { - pcmPos_ = 0; + + // 2. Standard MIDI sequencer & polyphonic synth + if (midiSeq_.active) { + while (midiSeq_.eventIdx < midiSeq_.events.size() && + midiSeq_.events[midiSeq_.eventIdx].frame <= + midiSeq_.currentFrame) { + triggerMidiEventLocked(midiSeq_.events[midiSeq_.eventIdx]); + midiSeq_.eventIdx++; + } + midiSeq_.currentFrame++; + if (midiSeq_.currentFrame >= midiSeq_.totalFrames) { + if (midiSeq_.loop) { + midiSeq_.currentFrame = 0; + midiSeq_.eventIdx = 0; + } else { + midiSeq_.active = false; + } } } - int32_t sample = static_cast( - std::clamp(mix, -0.98f, 0.98f) * 32767.0f); - stereoBuf[i * 2] = static_cast(sample); - stereoBuf[i * 2 + 1] = static_cast(sample); + if (!midiVoices_.empty()) { + float midiMix = 0.0f; + for (auto& mv : midiVoices_) { + if (mv.active) { + midiMix += sampleMidiVoiceLocked(mv); + } + } + mix += midiMix * midiSeq_.gain * masterGain; + } + + // 3. Multi-stream resampled WAV SFX / audio + for (auto it = pcmStreams_.begin(); it != pcmStreams_.end();) { + if (it->pos < it->samples.size()) { + mix += (it->samples[it->pos++] / 32768.0f) * it->gain * + masterGain * 0.85f; + if (it->pos >= it->samples.size()) { + if (it->loop) { + it->pos = 0; + ++it; + } else { + it = pcmStreams_.erase(it); + } + } else { + ++it; + } + } else { + it = pcmStreams_.erase(it); + } + } + + // 2-stage low-pass filter + soft knee limiter matching gambatte_phone + float inSample = mix * 32767.0f; + lpStage1L_ += 0.58f * (inSample - lpStage1L_); + lpStage2L_ += 0.58f * (lpStage1L_ - lpStage2L_); + int32_t filtered = static_cast(lpStage2L_); + if (filtered > 24000) filtered = 24000 + ((filtered - 24000) >> 2); + if (filtered < -24000) filtered = -24000 + ((filtered + 24000) >> 2); + lastSample_ = static_cast( + std::clamp(filtered, -32768, 32767)); + stereoBuf[i * 2] = lastSample_; + stereoBuf[i * 2 + 1] = lastSample_; } } snd_pcm_sframes_t w = snd_pcm_writei(pcm, stereoBuf, kPeriod); if (w < 0) { - snd_pcm_recover(pcm, static_cast(w), 1); + if (snd_pcm_recover(pcm, static_cast(w), 1) < 0) { + snd_pcm_prepare(pcm); + } } } @@ -806,6 +1850,52 @@ class CldcNetMediaRuntime { *r = JVal::MakeInt(ok ? 1 : 0); return true; }); + vm.registerNative( + "java/lang/String", "regionMatches", "*", + [](Jvm& v, JThread&, const std::vector& a, JVal* r) { + bool ignoreCase = false; + int toffset = 0; + uint32_t otherRef = 0; + int ooffset = 0; + int len = 0; + if (a.size() >= 6) { + ignoreCase = (a[1].i != 0); + toffset = a[2].i; + otherRef = a[3].ref; + ooffset = a[4].i; + len = a[5].i; + } else if (a.size() >= 5) { + toffset = a[1].i; + otherRef = a[2].ref; + ooffset = a[3].i; + len = a[4].i; + } + if (otherRef == 0 || toffset < 0 || ooffset < 0 || len < 0) { + *r = JVal::MakeInt(0); + return true; + } + auto s1 = Jvm::utf8ToU16(v.getStringUtf8(a[0].ref)); + auto s2 = Jvm::utf8ToU16(v.getStringUtf8(otherRef)); + if (static_cast(toffset + len) > s1.size() || + static_cast(ooffset + len) > s2.size()) { + *r = JVal::MakeInt(0); + return true; + } + bool match = true; + for (int i = 0; i < len; ++i) { + uint16_t c1 = s1[toffset + i]; + uint16_t c2 = s2[ooffset + i]; + if (c1 == c2) continue; + if (ignoreCase && c1 < 128 && c2 < 128 && + std::tolower(c1) == std::tolower(c2)) { + continue; + } + match = false; + break; + } + *r = JVal::MakeInt(match ? 1 : 0); + return true; + }); vm.registerNative("java/lang/String", "indexOf", "*", [](Jvm& v, JThread&, const std::vector& a, JVal* r) { std::string s = v.getStringUtf8(a[0].ref); @@ -1081,6 +2171,82 @@ class CldcNetMediaRuntime { : 0); return true; }); + vm.registerNative(sbCls, "setCharAt", "(IC)V", + [](Jvm& v, JThread&, const std::vector& a, JVal*) { + JObject* self = v.getObj(a[0].ref); + if (!self) return true; + auto u16 = Jvm::utf8ToU16(self->strUtf8); + int idx = a[1].i; + if (idx >= 0 && idx < static_cast(u16.size())) { + u16[idx] = static_cast(a[2].i); + self->strUtf8 = + Jvm::u16ToUtf8(u16.data(), u16.size()); + } + return true; + }); + vm.registerNative(sbCls, "ensureCapacity", "(I)V", + [](Jvm&, JThread&, const std::vector&, JVal*) { + return true; + }); + vm.registerNative(sbCls, "capacity", "()I", + [](Jvm& v, JThread&, const std::vector& a, JVal* r) { + JObject* self = v.getObj(a[0].ref); + *r = JVal::MakeInt( + static_cast( + (self ? self->strUtf8.size() : 0) + 16)); + return true; + }); + vm.registerNative( + sbCls, "insert", "(IC)Ljava/lang/StringBuffer;", + [](Jvm& v, JThread&, const std::vector& a, JVal* r) { + JObject* self = v.getObj(a[0].ref); + if (self) { + auto u16 = Jvm::utf8ToU16(self->strUtf8); + int idx = std::clamp(a[1].i, 0, u16.size()); + u16.insert(u16.begin() + idx, static_cast(a[2].i)); + self->strUtf8 = Jvm::u16ToUtf8(u16.data(), u16.size()); + } + *r = a[0]; + return true; + }); + vm.registerNative( + sbCls, "insert", "*", + [](Jvm& v, JThread&, const std::vector& a, JVal* r) { + JObject* self = v.getObj(a[0].ref); + if (self && a.size() >= 3) { + auto u16 = Jvm::utf8ToU16(self->strUtf8); + int idx = std::clamp(a[1].i, 0, u16.size()); + std::string ins; + const JVal& x = a[2]; + if (x.type == JType::Ref) { + ins = (x.ref == 0) ? "null" : v.getStringUtf8(x.ref); + } else if (x.type == JType::Long) { + ins = std::to_string(x.l); + } else { + ins = std::to_string(x.i); + } + auto insU16 = Jvm::utf8ToU16(ins); + u16.insert(u16.begin() + idx, insU16.begin(), insU16.end()); + self->strUtf8 = Jvm::u16ToUtf8(u16.data(), u16.size()); + } + *r = a[0]; + return true; + }); + vm.registerNative(sbCls, "deleteCharAt", "(I)Ljava/lang/StringBuffer;", + [](Jvm& v, JThread&, const std::vector& a, JVal* r) { + JObject* self = v.getObj(a[0].ref); + if (self) { + auto u16 = Jvm::utf8ToU16(self->strUtf8); + if (a[1].i >= 0 && + a[1].i < static_cast(u16.size())) { + u16.erase(u16.begin() + a[1].i); + self->strUtf8 = + Jvm::u16ToUtf8(u16.data(), u16.size()); + } + } + *r = a[0]; + return true; + }); vm.registerNative(sbCls, "delete", "*", [](Jvm& v, JThread&, const std::vector& a, JVal* r) { JObject* self = v.getObj(a[0].ref); @@ -1395,6 +2561,32 @@ class CldcNetMediaRuntime { *r = JVal::MakeInt(0); return true; }); + vm.registerNative("java/lang/Thread", "setPriority", "(I)V", + [](Jvm&, JThread&, const std::vector&, JVal*) { + return true; + }); + vm.registerNative("java/lang/Thread", "getPriority", "()I", + [](Jvm&, JThread&, const std::vector&, JVal* r) { + *r = JVal::MakeInt(5); + return true; + }); + vm.registerNative("java/lang/Thread", "activeCount", "()I", + [](Jvm& v, JThread&, const std::vector&, JVal* r) { + int cnt = 0; + for (const auto& t : v.threads()) { + if (t->state != ThreadState::Finished) cnt++; + } + *r = JVal::MakeInt(std::max(1, cnt)); + return true; + }); + vm.registerNative("java/lang/Thread", "interrupt", "()V", + [](Jvm&, JThread&, const std::vector&, JVal*) { + return true; + }); + vm.registerNative("java/lang/Thread", "join", "*", + [](Jvm&, JThread&, const std::vector&, JVal*) { + return true; + }); // java/lang/Throwable vm.registerNative("java/lang/Throwable", "", "*", @@ -1587,6 +2779,71 @@ class CldcNetMediaRuntime { : 0); return true; }); + vm.registerNative(vCls, "setSize", "(I)V", + [](Jvm& v, JThread&, const std::vector& a, JVal*) { + JObject* self = v.getObj(a[0].ref); + if (self) { + int n = std::max(0, a[1].i); + self->refArr.resize(static_cast(n), 0); + } + return true; + }); + vm.registerNative(vCls, "capacity", "()I", + [](Jvm& v, JThread&, const std::vector& a, JVal* r) { + JObject* self = v.getObj(a[0].ref); + *r = JVal::MakeInt( + self ? static_cast( + std::max(10, self->refArr.capacity())) + : 10); + return true; + }); + vm.registerNative(vCls, "ensureCapacity", "(I)V", + [](Jvm& v, JThread&, const std::vector& a, JVal*) { + JObject* self = v.getObj(a[0].ref); + if (self && a[1].i > 0) { + self->refArr.reserve(static_cast(a[1].i)); + } + return true; + }); + vm.registerNative(vCls, "trimToSize", "()V", + [](Jvm&, JThread&, const std::vector&, JVal*) { + return true; + }); + vm.registerNative(vCls, "indexOf", "*", + [](Jvm& v, JThread&, const std::vector& a, JVal* r) { + JObject* self = v.getObj(a[0].ref); + int startIdx = (a.size() >= 3) ? std::max(0, a[2].i) : 0; + if (self) { + for (int i = startIdx; + i < static_cast(self->refArr.size()); ++i) { + if (self->refArr[i] == a[1].ref) { + *r = JVal::MakeInt(i); + return true; + } + } + } + *r = JVal::MakeInt(-1); + return true; + }); + vm.registerNative(vCls, "lastIndexOf", "*", + [](Jvm& v, JThread&, const std::vector& a, JVal* r) { + JObject* self = v.getObj(a[0].ref); + if (self && !self->refArr.empty()) { + int startIdx = + (a.size() >= 3) + ? std::min(a[2].i, + self->refArr.size() - 1) + : static_cast(self->refArr.size()) - 1; + for (int i = startIdx; i >= 0; --i) { + if (self->refArr[i] == a[1].ref) { + *r = JVal::MakeInt(i); + return true; + } + } + } + *r = JVal::MakeInt(-1); + return true; + }); vm.registerNative(vCls, "isEmpty", "()Z", [](Jvm& v, JThread&, const std::vector& a, JVal* r) { JObject* self = v.getObj(a[0].ref); @@ -2820,6 +4077,19 @@ class CldcNetMediaRuntime { } } + struct NativePlayer { + int playerId = 0; + int state = 200; // CLOSED=0, UNREALIZED=100, REALIZED=200, PREFETCHED=300, STARTED=400 + int loopCount = 1; + int volumeLevel = 80; + bool muted = false; + int64_t mediaTimeUs = 0; + std::string contentType = "audio/midi"; + std::vector data; + }; + + int nextPlayerId_ = 1; + void registerMmapi(Jvm& vm) { vm.registerNative( "javax/microedition/media/Manager", "playTone", "(III)V", @@ -2827,97 +4097,440 @@ class CldcNetMediaRuntime { sound.playTone(a[0].i, a[1].i, a[2].i); return true; }); + vm.registerNative( + "javax/microedition/media/Manager", "getSupportedContentTypes", "*", + [](Jvm& v, JThread&, const std::vector&, JVal* r) { + uint32_t arr = v.allocRefArray("java/lang/String", 4); + JObject* ao = v.getObj(arr); + ao->refArr[0] = v.allocString("audio/midi"); + ao->refArr[1] = v.allocString("audio/x-wav"); + ao->refArr[2] = v.allocString("audio/wav"); + ao->refArr[3] = v.allocString("audio/x-tone-seq"); + *r = JVal::MakeRef(arr); + return true; + }); + vm.registerNative( + "javax/microedition/media/Manager", "getSupportedProtocols", "*", + [](Jvm& v, JThread&, const std::vector&, JVal* r) { + uint32_t arr = v.allocRefArray("java/lang/String", 2); + JObject* ao = v.getObj(arr); + ao->refArr[0] = v.allocString("device"); + ao->refArr[1] = v.allocString("http"); + *r = JVal::MakeRef(arr); + return true; + }); vm.registerNative( "javax/microedition/media/Manager", "createPlayer", "*", - [](Jvm& v, JThread&, const std::vector& a, JVal* r) { + [this](Jvm& v, JThread&, const std::vector& a, JVal* r) { uint32_t pref = v.allocObject("javax/microedition/media/Player"); JObject* po = v.getObj(pref); - if (po && !a.empty() && a[0].type == JType::Ref && a[0].ref != 0) { + auto np = std::make_shared(); + np->playerId = nextPlayerId_++; + np->state = 200; // REALIZED + if (a.size() >= 2 && a[1].type == JType::Ref && a[1].ref != 0) { + np->contentType = v.getStringUtf8(a[1].ref); + } + if (!a.empty() && a[0].type == JType::Ref && a[0].ref != 0) { JObject* src = v.getObj(a[0].ref); - if (src && src->nativeData) { - po->nativeData = src->nativeData; + if (src) { + if (src->isString) { + std::string loc = v.getStringUtf8(a[0].ref); + if (loc.rfind("resource:", 0) == 0) { + loc = loc.substr(9); + } + if (v.jar) v.jar->extractEntry(loc, &np->data); + } else if (src->nativeData) { + auto* nis = static_cast( + src->nativeData.get()); + if (nis) { + if (nis->pos < nis->data.size()) { + np->data.assign(nis->data.begin() + nis->pos, + nis->data.end()); + nis->pos = nis->data.size(); + } else { + np->data = nis->data; + } + } + } } } + if (po) po->nativeData = np; *r = JVal::MakeRef(pref); return true; }); + auto ensureNativePlayer = [this](JObject* self) -> NativePlayer* { + if (!self) return nullptr; + if (!self->nativeData) { + auto np = std::make_shared(); + np->playerId = nextPlayerId_++; + self->nativeData = np; + } + return static_cast(self->nativeData.get()); + }; + for (const char* pCls : {"javax/microedition/media/Player", "javax/microedition/media/Controllable", + "javax/microedition/media/Control", "javax/microedition/media/control/VolumeControl", + "javax/microedition/media/control/ToneControl", "com/nokia/mid/sound/Sound"}) { - vm.registerNative(pCls, "", "*", - [](Jvm&, JThread&, const std::vector&, JVal*) { - return true; - }); - vm.registerNative(pCls, "realize", "()V", - [](Jvm&, JThread&, const std::vector&, JVal*) { - return true; - }); - vm.registerNative(pCls, "prefetch", "()V", - [](Jvm&, JThread&, const std::vector&, JVal*) { - return true; - }); + vm.registerNative( + pCls, "", "*", + [this, ensureNativePlayer](Jvm& v, JThread&, + const std::vector& a, JVal*) { + if (a.empty()) return true; + JObject* self = v.getObj(a[0].ref); + NativePlayer* np = ensureNativePlayer(self); + if (!np) return true; + // com.nokia.mid.sound.Sound(byte[] data, int type) or Sound(int freq, long dur) + if (a.size() >= 3 && a[1].type == JType::Ref && a[1].ref != 0) { + const JObject* bo = v.getObj(a[1].ref); + if (bo && bo->arrayKind == ArrayKind::Byte) { + np->data.resize(bo->byteArr.size()); + for (size_t i = 0; i < bo->byteArr.size(); ++i) { + np->data[i] = static_cast(bo->byteArr[i]); + } + } + } else if (a.size() >= 3 && a[1].type == JType::Int) { + // Sound(int freq, long duration) -> store synthetic tone header + int freq = std::clamp(a[1].i, 50, 8000); + int midiNote = static_cast( + std::round(69.0 + 12.0 * std::log2(freq / 440.0))); + midiNote = std::clamp(midiNote, 0, 127); + np->loopCount = 1; + if (self) self->nativeTag = (midiNote << 16) | + std::clamp( + a[2].type == JType::Long + ? static_cast(a[2].l) + : a[2].i, + 20, 5000); + } + return true; + }); + vm.registerNative( + pCls, "init", "*", + [ensureNativePlayer](Jvm& v, JThread&, const std::vector& a, + JVal*) { + if (a.size() >= 3 && a[1].type == JType::Ref && a[1].ref != 0) { + JObject* self = v.getObj(a[0].ref); + NativePlayer* np = ensureNativePlayer(self); + const JObject* bo = v.getObj(a[1].ref); + if (np && bo && bo->arrayKind == ArrayKind::Byte) { + np->data.resize(bo->byteArr.size()); + for (size_t i = 0; i < bo->byteArr.size(); ++i) { + np->data[i] = static_cast(bo->byteArr[i]); + } + } + } + return true; + }); + vm.registerNative( + pCls, "realize", "()V", + [ensureNativePlayer](Jvm& v, JThread&, const std::vector& a, + JVal*) { + NativePlayer* np = ensureNativePlayer(v.getObj(a[0].ref)); + if (np && np->state != 0 && np->state < 200) np->state = 200; + return true; + }); + vm.registerNative( + pCls, "prefetch", "()V", + [ensureNativePlayer](Jvm& v, JThread&, const std::vector& a, + JVal*) { + NativePlayer* np = ensureNativePlayer(v.getObj(a[0].ref)); + if (np && np->state != 0 && np->state < 300) np->state = 300; + return true; + }); vm.registerNative( pCls, "start", "()V", - [this](Jvm& v, JThread&, const std::vector& a, JVal*) { + [this, ensureNativePlayer](Jvm& v, JThread&, + const std::vector& a, JVal*) { JObject* self = v.getObj(a[0].ref); - if (self && self->nativeData) { - auto* nis = static_cast( - self->nativeData.get()); - sound.playWavBytes(nis->data, self->nativeTag < 0); - } else { - sound.playTone(69, 90, 75); + NativePlayer* np = ensureNativePlayer(self); + if (!np || np->state == 0) return true; + np->state = 400; // STARTED + int effVol = np->muted ? 0 : np->volumeLevel; + bool loop = (np->loopCount < 0 || np->loopCount > 1); + sound.setPlayerVolume(np->playerId, effVol); + if (!np->data.empty()) { + sound.startPlayerBytes(np->playerId, np->data, loop, effVol); + } else if (self && self->nativeTag > 0) { + int note = (self->nativeTag >> 16) & 0x7F; + int dur = self->nativeTag & 0xFFFF; + sound.playTone(note, dur > 0 ? dur : 90, effVol); } return true; }); vm.registerNative( pCls, "play", "(I)V", - [this](Jvm&, JThread&, const std::vector&, JVal*) { - sound.playTone(72, 80, 80); + [this, ensureNativePlayer](Jvm& v, JThread&, + const std::vector& a, JVal*) { + JObject* self = v.getObj(a[0].ref); + NativePlayer* np = ensureNativePlayer(self); + if (!np) return true; + np->loopCount = (a.size() >= 2 && a[1].i == 0) ? -1 : a[1].i; + np->state = 400; + int effVol = np->muted ? 0 : np->volumeLevel; + bool loop = (np->loopCount < 0 || np->loopCount > 1); + if (!np->data.empty()) { + sound.startPlayerBytes(np->playerId, np->data, loop, effVol); + } else if (self && self->nativeTag > 0) { + int note = (self->nativeTag >> 16) & 0x7F; + int dur = self->nativeTag & 0xFFFF; + sound.playTone(note, dur > 0 ? dur : 90, effVol); + } else { + sound.playTone(72, 80, effVol); + } return true; }); vm.registerNative( pCls, "stop", "()V", - [this](Jvm&, JThread&, const std::vector&, JVal*) { - sound.stopAll(); + [this, ensureNativePlayer](Jvm& v, JThread&, + const std::vector& a, JVal*) { + NativePlayer* np = ensureNativePlayer(v.getObj(a[0].ref)); + if (np) { + sound.stopPlayer(np->playerId); + if (np->state == 400) np->state = 300; // PREFETCHED + } + return true; + }); + vm.registerNative( + pCls, "deallocate", "()V", + [this, ensureNativePlayer](Jvm& v, JThread&, + const std::vector& a, JVal*) { + NativePlayer* np = ensureNativePlayer(v.getObj(a[0].ref)); + if (np) { + sound.stopPlayer(np->playerId); + if (np->state > 200) np->state = 200; // REALIZED + } + return true; + }); + vm.registerNative( + pCls, "close", "()V", + [this, ensureNativePlayer](Jvm& v, JThread&, + const std::vector& a, JVal*) { + NativePlayer* np = ensureNativePlayer(v.getObj(a[0].ref)); + if (np) { + sound.stopPlayer(np->playerId); + np->state = 0; // CLOSED + } + return true; + }); + vm.registerNative( + pCls, "release", "()V", + [this, ensureNativePlayer](Jvm& v, JThread&, + const std::vector& a, JVal*) { + NativePlayer* np = ensureNativePlayer(v.getObj(a[0].ref)); + if (np) { + sound.stopPlayer(np->playerId); + np->state = 0; + } + return true; + }); + vm.registerNative( + pCls, "getState", "()I", + [this, ensureNativePlayer](Jvm& v, JThread&, + const std::vector& a, JVal* r) { + JObject* self = v.getObj(a[0].ref); + NativePlayer* np = ensureNativePlayer(self); + if (!np) { + *r = JVal::MakeInt(0); + return true; + } + if (self && self->className == "com/nokia/mid/sound/Sound") { + // Nokia Sound constants: SOUND_PLAYING=0, SOUND_STOPPED=1, SOUND_UNINITIALIZED=3 + bool active = sound.isPlayerActive(np->playerId); + *r = JVal::MakeInt(active ? 0 : 1); + return true; + } + if (np->state == 400 && !np->data.empty()) { + bool isMidi = (np->data.size() >= 4 && + std::memcmp(np->data.data(), "MThd", 4) == 0); + bool isLooping = (np->loopCount < 0 || np->loopCount > 1); + if (!isMidi && !isLooping) { + // One-shot WAV SFX play asynchronously in the 6-channel mixer; + // report PREFETCHED (300) so games that check getState() == 400 + // before starting music or rapid SFX never drop sounds. + np->state = 300; + } else if (!sound.isPlayerActive(np->playerId)) { + np->state = 300; // Transition back to PREFETCHED when finished + } + } + *r = JVal::MakeInt(np->state); return true; }); - vm.registerNative(pCls, "deallocate", "()V", - [](Jvm&, JThread&, const std::vector&, JVal*) { - return true; - }); - vm.registerNative(pCls, "close", "()V", - [](Jvm&, JThread&, const std::vector&, JVal*) { - return true; - }); vm.registerNative( pCls, "setLoopCount", "(I)V", - [](Jvm& v, JThread&, const std::vector& a, JVal*) { - JObject* self = v.getObj(a[0].ref); - if (self) self->nativeTag = a[1].i; + [ensureNativePlayer](Jvm& v, JThread&, const std::vector& a, + JVal*) { + NativePlayer* np = ensureNativePlayer(v.getObj(a[0].ref)); + if (np) np->loopCount = a[1].i; + return true; + }); + vm.registerNative( + pCls, "setMediaTime", "(J)J", + [this, ensureNativePlayer](Jvm& v, JThread&, + const std::vector& a, JVal* r) { + NativePlayer* np = ensureNativePlayer(v.getObj(a[0].ref)); + int64_t t = (a.size() >= 2) ? std::max(0, a[1].l) : 0; + if (np) { + np->mediaTimeUs = t; + if (t == 0) sound.rewindPlayer(np->playerId); + } + *r = JVal::MakeLong(t); + return true; + }); + vm.registerNative( + pCls, "getMediaTime", "()J", + [ensureNativePlayer](Jvm& v, JThread&, const std::vector& a, + JVal* r) { + NativePlayer* np = ensureNativePlayer(v.getObj(a[0].ref)); + *r = JVal::MakeLong(np ? np->mediaTimeUs : 0); + return true; + }); + vm.registerNative( + pCls, "getDuration", "()J", + [](Jvm&, JThread&, const std::vector&, JVal* r) { + *r = JVal::MakeLong(1000000LL); + return true; + }); + vm.registerNative( + pCls, "getContentType", "()Ljava/lang/String;", + [ensureNativePlayer](Jvm& v, JThread&, const std::vector& a, + JVal* r) { + NativePlayer* np = ensureNativePlayer(v.getObj(a[0].ref)); + *r = JVal::MakeRef( + v.allocString(np ? np->contentType : "audio/midi")); + return true; + }); + vm.registerNative( + pCls, "addPlayerListener", + "(Ljavax/microedition/media/PlayerListener;)V", + [](Jvm&, JThread&, const std::vector&, JVal*) { + return true; + }); + vm.registerNative( + pCls, "removePlayerListener", + "(Ljavax/microedition/media/PlayerListener;)V", + [](Jvm&, JThread&, const std::vector&, JVal*) { return true; }); vm.registerNative( pCls, "getControl", "(Ljava/lang/String;)Ljavax/microedition/media/Control;", - [](Jvm& v, JThread&, const std::vector&, JVal* r) { - *r = JVal::MakeRef(v.allocObject( - "javax/microedition/media/control/VolumeControl")); + [ensureNativePlayer](Jvm& v, JThread&, const std::vector& a, + JVal* r) { + JObject* self = v.getObj(a[0].ref); + ensureNativePlayer(self); + std::string ctrlType = + (a.size() >= 2 && a[1].type == JType::Ref && a[1].ref != 0) + ? v.getStringUtf8(a[1].ref) + : "VolumeControl"; + std::string clsName = + (ctrlType.find("ToneControl") != std::string::npos) + ? "javax/microedition/media/control/ToneControl" + : "javax/microedition/media/control/VolumeControl"; + uint32_t cref = v.allocObject(clsName); + JObject* co = v.getObj(cref); + if (co && self) { + // Share NativePlayer between Player and its Control! + co->nativeData = self->nativeData; + } + *r = JVal::MakeRef(cref); + return true; + }); + vm.registerNative( + pCls, "getControls", "()[Ljavax/microedition/media/Control;", + [ensureNativePlayer](Jvm& v, JThread&, const std::vector& a, + JVal* r) { + JObject* self = v.getObj(a[0].ref); + ensureNativePlayer(self); + uint32_t arr = + v.allocRefArray("javax/microedition/media/Control", 1); + uint32_t cref = + v.allocObject("javax/microedition/media/control/VolumeControl"); + if (self && v.getObj(cref)) { + v.getObj(cref)->nativeData = self->nativeData; + } + v.getObj(arr)->refArr[0] = cref; + *r = JVal::MakeRef(arr); return true; }); vm.registerNative( pCls, "setLevel", "(I)I", - [this](Jvm&, JThread&, const std::vector& a, JVal* r) { - sound.volumePct = std::clamp(a[1].i, 0, 100); - *r = JVal::MakeInt(sound.volumePct); + [this, ensureNativePlayer](Jvm& v, JThread&, + const std::vector& a, JVal* r) { + NativePlayer* np = ensureNativePlayer(v.getObj(a[0].ref)); + int lvl = std::clamp(a[1].i, 0, 100); + if (np) { + np->volumeLevel = lvl; + sound.setPlayerVolume(np->playerId, np->muted ? 0 : lvl); + } + *r = JVal::MakeInt(lvl); return true; }); vm.registerNative( pCls, "getLevel", "()I", - [this](Jvm&, JThread&, const std::vector&, JVal* r) { - *r = JVal::MakeInt(sound.volumePct); + [ensureNativePlayer](Jvm& v, JThread&, const std::vector& a, + JVal* r) { + NativePlayer* np = ensureNativePlayer(v.getObj(a[0].ref)); + *r = JVal::MakeInt(np ? np->volumeLevel : 80); + return true; + }); + vm.registerNative( + pCls, "setMute", "(Z)V", + [this, ensureNativePlayer](Jvm& v, JThread&, + const std::vector& a, JVal*) { + NativePlayer* np = ensureNativePlayer(v.getObj(a[0].ref)); + if (np) { + np->muted = (a[1].i != 0); + sound.setPlayerVolume(np->playerId, + np->muted ? 0 : np->volumeLevel); + } + return true; + }); + vm.registerNative( + pCls, "isMuted", "()Z", + [ensureNativePlayer](Jvm& v, JThread&, const std::vector& a, + JVal* r) { + NativePlayer* np = ensureNativePlayer(v.getObj(a[0].ref)); + *r = JVal::MakeInt((np && np->muted) ? 1 : 0); + return true; + }); + vm.registerNative( + pCls, "setGain", "(I)V", + [this, ensureNativePlayer](Jvm& v, JThread&, + const std::vector& a, JVal*) { + NativePlayer* np = ensureNativePlayer(v.getObj(a[0].ref)); + if (np) { + np->volumeLevel = std::clamp((a[1].i * 100) / 255, 0, 100); + sound.setPlayerVolume(np->playerId, np->volumeLevel); + } + return true; + }); + vm.registerNative( + pCls, "getGain", "()I", + [ensureNativePlayer](Jvm& v, JThread&, const std::vector& a, + JVal* r) { + NativePlayer* np = ensureNativePlayer(v.getObj(a[0].ref)); + *r = JVal::MakeInt(np ? (np->volumeLevel * 255) / 100 : 200); + return true; + }); + vm.registerNative( + pCls, "setSequence", "([B)V", + [ensureNativePlayer](Jvm& v, JThread&, const std::vector& a, + JVal*) { + NativePlayer* np = ensureNativePlayer(v.getObj(a[0].ref)); + if (np && a.size() >= 2 && a[1].type == JType::Ref && a[1].ref != 0) { + const JObject* bo = v.getObj(a[1].ref); + if (bo && bo->arrayKind == ArrayKind::Byte) { + np->data.resize(bo->byteArr.size()); + for (size_t i = 0; i < bo->byteArr.size(); ++i) { + np->data[i] = static_cast(bo->byteArr[i]); + } + } + } return true; }); } diff --git a/src/games/remedy/remedy_jvm.hpp b/src/games/remedy/remedy_jvm.hpp index 5f7965e..3ce8fec 100644 --- a/src/games/remedy/remedy_jvm.hpp +++ b/src/games/remedy/remedy_jvm.hpp @@ -10,6 +10,7 @@ #include #include #include +#include #include #include #include @@ -150,6 +151,41 @@ struct JMethodInfo { std::vector exceptionTable; }; +struct JClass; + +// Native method handler signature: +// Receives (Jvm& vm, JThread& th, const std::vector& args, JVal* outReturn) +// Returns true if normal return (or yield), false if an exception was thrown on `th`. +using NativeMethodFn = std::function&, JVal*)>; + +// Lazily resolved Fieldref / Methodref / InterfaceMethodref constant pool entry. +// Caches the decoded strings, the typed field key, the static field storage +// slot and a monomorphic inline cache for method dispatch so the interpreter +// hot path avoids per-instruction string copies, concatenation and hierarchy +// walks. +struct CpRefCache { + bool ready = false; + std::string cls; + std::string name; + std::string desc; + std::string fieldKey; + char descFirst = 'I'; + + // getstatic / putstatic + JVal* staticSlot = nullptr; + + // invoke* + bool sigReady = false; + uint16_t numParams = 0; + JType returnType = JType::Void; + bool icValid = false; + std::string icClass; + JClass* icTargetCls = nullptr; + const JMethodInfo* icTargetMethod = nullptr; + const NativeMethodFn* icNative = nullptr; +}; + struct JClass { std::string name; std::string superName; @@ -194,6 +230,22 @@ struct JClass { } return false; } + + std::vector refCache; + + CpRefCache& refAt(uint16_t idx) { + if (refCache.size() != cp.size()) refCache.resize(cp.size()); + static CpRefCache kDummy; + if (idx >= refCache.size()) return kDummy; + CpRefCache& c = refCache[idx]; + if (!c.ready) { + cpRef(idx, &c.cls, &c.name, &c.desc); + c.fieldKey = c.desc.empty() ? c.name : (c.name + ":" + c.desc); + c.descFirst = c.desc.empty() ? 'I' : c.desc[0]; + c.ready = true; + } + return c; + } }; // --------------------------------------------------------------------------- @@ -244,6 +296,11 @@ struct JObject { } } + static std::string makeFieldKey(const std::string& name, + const std::string& desc) { + return desc.empty() ? name : (name + ":" + desc); + } + JVal getField(const std::string& name, char descFirstChar = 'I') const { auto it = fields.find(name); if (it != fields.end()) return it->second; @@ -257,9 +314,22 @@ struct JObject { } } + JVal getTypedField(const std::string& name, const std::string& desc) const { + if (!desc.empty()) { + auto it = fields.find(name + ":" + desc); + if (it != fields.end()) return it->second; + } + return getField(name, desc.empty() ? 'I' : desc[0]); + } + void setField(const std::string& name, const JVal& v) { fields[name] = v; } + + void setTypedField(const std::string& name, const std::string& desc, + const JVal& v) { + fields[makeFieldKey(name, desc)] = v; + } }; // --------------------------------------------------------------------------- @@ -304,12 +374,6 @@ struct JThread { std::vector frames; }; -// Native method handler signature: -// Receives (Jvm& vm, JThread& th, const std::vector& args, JVal* outReturn) -// Returns true if normal return (or yield), false if an exception was thrown on `th`. -using NativeMethodFn = std::function&, JVal*)>; - // --------------------------------------------------------------------------- // Descriptor Argument Parser // --------------------------------------------------------------------------- @@ -661,12 +725,21 @@ class Jvm { NativeMethodFn findNative(const std::string& className, const std::string& methodName, const std::string& descriptor) const { + const NativeMethodFn* p = findNativePtr(className, methodName, descriptor); + return p ? *p : NativeMethodFn{}; + } + + // Pointer variant (unordered_map values are address-stable) used by the + // interpreter's inline caches to avoid copying std::function objects. + const NativeMethodFn* findNativePtr(const std::string& className, + const std::string& methodName, + const std::string& descriptor) const { std::string cur = className; while (!cur.empty()) { auto it = natives_.find(cur + "." + methodName + descriptor); - if (it != natives_.end()) return it->second; + if (it != natives_.end()) return &it->second; auto wit = nativesWildcard_.find(cur + "." + methodName); - if (wit != nativesWildcard_.end()) return wit->second; + if (wit != nativesWildcard_.end()) return &wit->second; cur = getSuperClassName(cur); } return nullptr; @@ -771,6 +844,22 @@ class Jvm { } } } + + // True when at least one scheduled Java thread can make progress right now + // (runnable, or sleeping/waiting with an already-expired wake deadline). + bool anyThreadReady() const { + int64_t now = nowMs(); + for (const auto& th : threads_) { + if (!th || th->frames.empty()) continue; + if (th->state == ThreadState::Runnable) return true; + if ((th->state == ThreadState::Sleeping || + th->state == ThreadState::Waiting) && + th->wakeTimeMs > 0 && now >= th->wakeTimeMs) { + return true; + } + } + return false; + } bool resolveBytecodeMethod(const std::string& startClass, const std::string& methodName, const std::string& descriptor, @@ -806,7 +895,7 @@ class Jvm { JThread tempThread; tempThread.id = 9999; pushBytecodeFrame(tempThread, cls, &m, {}); - runThreadUntilReturn(tempThread, 0, 200000); + runThreadUntilReturn(tempThread, 0, 2000000); break; } } @@ -846,6 +935,7 @@ class Jvm { f.pc = 0; size_t numLocals = std::max(m->maxLocals + 4, args.size() * 2 + 4); f.locals.resize(numLocals); + f.stack.reserve(static_cast(m->maxStack) + 4); size_t localIdx = 0; for (const JVal& a : args) { if (localIdx >= f.locals.size()) f.locals.resize(localIdx + 4); @@ -970,7 +1060,7 @@ class Jvm { } private: - std::vector heap_; + std::deque heap_; std::unordered_map internPool_; std::unordered_map> classes_; std::unordered_map builtinSupers_; @@ -1121,7 +1211,7 @@ class Jvm { v = JVal::MakeRef(internString(cls->cpUtf8(ce.idx1))); } } - cls->staticFields[f.name] = v; + cls->staticFields[JObject::makeFieldKey(f.name, f.descriptor)] = v; } } @@ -1137,38 +1227,25 @@ class Jvm { } for (const auto& f : cls->fields) { if ((f.accessFlags & 0x0008) != 0) continue; // skip static - if (heap_[objRef].fields.find(f.name) != heap_[objRef].fields.end()) { + std::string fkey = JObject::makeFieldKey(f.name, f.descriptor); + if (heap_[objRef].fields.find(fkey) != heap_[objRef].fields.end()) { continue; } char d = f.descriptor.empty() ? 'I' : f.descriptor[0]; - if (d == 'J') heap_[objRef].fields[f.name] = JVal::MakeLong(0); - else if (d == 'F') heap_[objRef].fields[f.name] = JVal::MakeFloat(0.0f); - else if (d == 'D') heap_[objRef].fields[f.name] = JVal::MakeDouble(0.0); + if (d == 'J') heap_[objRef].fields[fkey] = JVal::MakeLong(0); + else if (d == 'F') heap_[objRef].fields[fkey] = JVal::MakeFloat(0.0f); + else if (d == 'D') heap_[objRef].fields[fkey] = JVal::MakeDouble(0.0); else if (d == 'L' || d == '[') { - heap_[objRef].fields[f.name] = JVal::Null(); + heap_[objRef].fields[fkey] = JVal::Null(); } else { - heap_[objRef].fields[f.name] = JVal::MakeInt(0); + heap_[objRef].fields[fkey] = JVal::MakeInt(0); } } cur = cls->superName; } } - JVal getStaticFieldVal(const std::string& className, - const std::string& fieldName, - const std::string& desc) { - std::string cur = className; - int depth = 0; - while (!cur.empty() && depth++ < 24) { - JClass* cls = loadClass(cur); - if (cls) { - ensureClassInitialized(cls); - auto it = cls->staticFields.find(fieldName); - if (it != cls->staticFields.end()) return it->second; - } - cur = getSuperClassName(cur); - } - char d = desc.empty() ? 'I' : desc[0]; + static JVal defaultValueForDesc(char d) { if (d == 'J') return JVal::MakeLong(0); if (d == 'F') return JVal::MakeFloat(0.0f); if (d == 'D') return JVal::MakeDouble(0.0); @@ -1176,14 +1253,57 @@ class Jvm { return JVal::MakeInt(0); } + // Find the storage slot of a static field, searching the referenced class, + // its superclasses and their superinterfaces (JVMS 5.4.3.2). Classes are + // initialized along the way. If the field is not declared anywhere, a + // default-valued slot is created on the referenced class. Returns nullptr + // only for classes that are not present in the JAR (pure native classes). + JVal* findStaticSlotIn(JClass* cls, const std::string& fkey, + const std::string& fieldName, int depth) { + if (!cls || depth > 24) return nullptr; + ensureClassInitialized(cls); + auto it = cls->staticFields.find(fkey); + if (it != cls->staticFields.end()) return &it->second; + auto it2 = cls->staticFields.find(fieldName); + if (it2 != cls->staticFields.end()) return &it2->second; + for (const std::string& iface : cls->interfaces) { + JVal* s = findStaticSlotIn(loadClass(iface), fkey, fieldName, depth + 1); + if (s) return s; + } + if (!cls->superName.empty() && cls->superName != "java/lang/Object") { + return findStaticSlotIn(loadClass(cls->superName), fkey, fieldName, + depth + 1); + } + return nullptr; + } + + JVal* resolveStaticSlot(const std::string& className, + const std::string& fieldName, + const std::string& desc) { + std::string fkey = JObject::makeFieldKey(fieldName, desc); + JClass* cls = loadClass(className); + if (!cls) return nullptr; + JVal* s = findStaticSlotIn(cls, fkey, fieldName, 0); + if (s) return s; + auto ins = cls->staticFields.emplace( + fkey, defaultValueForDesc(desc.empty() ? 'I' : desc[0])); + return &ins.first->second; + } + + JVal getStaticFieldVal(const std::string& className, + const std::string& fieldName, + const std::string& desc) { + JVal* s = resolveStaticSlot(className, fieldName, desc); + if (s) return *s; + return defaultValueForDesc(desc.empty() ? 'I' : desc[0]); + } + void setStaticFieldVal(const std::string& className, const std::string& fieldName, + const std::string& desc, const JVal& val) { - JClass* cls = loadClass(className); - if (cls) { - ensureClassInitialized(cls); - cls->staticFields[fieldName] = val; - } + JVal* s = resolveStaticSlot(className, fieldName, desc); + if (s) *s = val; } // Big-endian readers for .class format @@ -1494,6 +1614,98 @@ class Jvm { return true; } + // Cached variant of invokeMethodFromFrame used by the bytecode interpreter. + // Static and special call sites resolve once; virtual and interface call + // sites keep a monomorphic inline cache keyed on the receiver class. + bool invokeMethodCached(JThread& th, CpRefCache& rc, bool isStatic, + bool isSpecial) { + if (!rc.sigReady) { + MethodSigInfo sig = parseMethodDescriptor(rc.desc); + rc.numParams = static_cast(sig.paramTypes.size()); + rc.returnType = sig.returnType; + rc.sigReady = true; + } + size_t numArgs = rc.numParams + (isStatic ? 0 : 1); + std::vector args(numArgs); + { + JFrame& caller = th.frames.back(); + for (size_t i = 0; i < numArgs; ++i) { + args[numArgs - 1 - i] = caller.pop(); + } + } + + const std::string* lookupClass = &rc.cls; + if (!isStatic) { + uint32_t selfRef = args[0].ref; + if (selfRef == 0) { + throwException(th, "java/lang/NullPointerException", rc.name); + return dispatchAbnormalException(th); + } + if (!isSpecial) { + const JObject* selfObj = getObj(selfRef); + if (selfObj) lookupClass = &selfObj->className; + } + } + + bool monomorphic = isStatic || isSpecial; + if (!rc.icValid || (!monomorphic && rc.icClass != *lookupClass)) { + JClass* targetCls = nullptr; + const JMethodInfo* targetMethod = nullptr; + resolveBytecodeMethod(*lookupClass, rc.name, rc.desc, &targetCls, + &targetMethod); + const NativeMethodFn* nat = nullptr; + if (!targetMethod) { + nat = findNativePtr(*lookupClass, rc.name, rc.desc); + if (!nat && *lookupClass != rc.cls) { + nat = findNativePtr(rc.cls, rc.name, rc.desc); + } + } + rc.icClass = *lookupClass; + rc.icTargetCls = targetMethod ? targetCls : nullptr; + rc.icTargetMethod = targetMethod; + rc.icNative = nat; + rc.icValid = true; + } + + if (rc.icTargetCls && rc.icTargetMethod) { + pushBytecodeFrame(th, rc.icTargetCls, rc.icTargetMethod, args); + return true; + } + + if (rc.icNative && *rc.icNative) { + JVal retVal; + if (!(*rc.icNative)(*this, th, args, &retVal)) { + return dispatchAbnormalException(th); + } + if (rc.returnType != JType::Void && !th.frames.empty()) { + th.frames.back().push(retVal); + } + return true; + } + + // Fallback default no-op for unimplemented constructors or void methods + if (rc.returnType != JType::Void && !th.frames.empty()) { + switch (rc.returnType) { + case JType::Long: + th.frames.back().push(JVal::MakeLong(0)); + break; + case JType::Float: + th.frames.back().push(JVal::MakeFloat(0.0f)); + break; + case JType::Double: + th.frames.back().push(JVal::MakeDouble(0.0)); + break; + case JType::Ref: + th.frames.back().push(JVal::Null()); + break; + default: + th.frames.back().push(JVal::MakeInt(0)); + break; + } + } + return true; + } + void pushCpConstant(JFrame& f, JClass* cls, uint16_t idx) { if (!cls || idx == 0 || idx >= cls->cp.size()) { f.push(JVal::MakeInt(0)); @@ -2076,48 +2288,56 @@ class Jvm { case 0xb2: { // getstatic uint16_t idx = be16(code.data() + f.pc); f.pc += 2; - std::string clsName, fldName, fldDesc; - f.cls->cpRef(idx, &clsName, &fldName, &fldDesc); - JVal v = getStaticFieldVal(clsName, fldName, fldDesc); + CpRefCache& rc = f.cls->refAt(idx); + if (!rc.staticSlot) { + rc.staticSlot = resolveStaticSlot(rc.cls, rc.name, rc.desc); + } + JVal v = rc.staticSlot ? *rc.staticSlot + : defaultValueForDesc(rc.descFirst); th.frames.back().push(v); break; } case 0xb3: { // putstatic uint16_t idx = be16(code.data() + f.pc); f.pc += 2; - std::string clsName, fldName, fldDesc; - f.cls->cpRef(idx, &clsName, &fldName, &fldDesc); + CpRefCache& rc = f.cls->refAt(idx); JVal v = f.pop(); - setStaticFieldVal(clsName, fldName, v); + if (!rc.staticSlot) { + rc.staticSlot = resolveStaticSlot(rc.cls, rc.name, rc.desc); + } + if (rc.staticSlot) *rc.staticSlot = v; break; } case 0xb4: { // getfield uint16_t idx = be16(code.data() + f.pc); f.pc += 2; - std::string clsName, fldName, fldDesc; - f.cls->cpRef(idx, &clsName, &fldName, &fldDesc); + CpRefCache& rc = f.cls->refAt(idx); uint32_t objRef = f.popRef(); JObject* obj = getObj(objRef); if (!obj) { - throwException(th, "java/lang/NullPointerException", fldName); + throwException(th, "java/lang/NullPointerException", rc.name); return dispatchAbnormalException(th); } - f.push(obj->getField(fldName, fldDesc.empty() ? 'I' : fldDesc[0])); + auto it = obj->fields.find(rc.fieldKey); + if (it != obj->fields.end()) { + f.push(it->second); + } else { + f.push(obj->getField(rc.name, rc.descFirst)); + } break; } case 0xb5: { // putfield uint16_t idx = be16(code.data() + f.pc); f.pc += 2; - std::string clsName, fldName, fldDesc; - f.cls->cpRef(idx, &clsName, &fldName, &fldDesc); + CpRefCache& rc = f.cls->refAt(idx); JVal v = f.pop(); uint32_t objRef = f.popRef(); JObject* obj = getObj(objRef); if (!obj) { - throwException(th, "java/lang/NullPointerException", fldName); + throwException(th, "java/lang/NullPointerException", rc.name); return dispatchAbnormalException(th); } - obj->setField(fldName, v); + obj->fields[rc.fieldKey] = v; break; } @@ -2128,10 +2348,8 @@ class Jvm { case 0xb9: { // invokeinterface uint16_t idx = be16(code.data() + f.pc); f.pc += (op == 0xb9) ? 4 : 2; - std::string clsName, mName, mDesc; - f.cls->cpRef(idx, &clsName, &mName, &mDesc); - return invokeMethodFromFrame(th, clsName, mName, mDesc, - op == 0xb8, op == 0xb7); + CpRefCache& rc = f.cls->refAt(idx); + return invokeMethodCached(th, rc, op == 0xb8, op == 0xb7); } // Object & Array creation diff --git a/src/games/remedy/remedy_lcdui_natives.hpp b/src/games/remedy/remedy_lcdui_natives.hpp index 770a984..1d4d258 100644 --- a/src/games/remedy/remedy_lcdui_natives.hpp +++ b/src/games/remedy/remedy_lcdui_natives.hpp @@ -1885,6 +1885,22 @@ inline void registerLcduiAndM3gNatives(Jvm& vm, RuntimeAppContext* ctx) { model = static_cast(trObj->nativeData.get())->mat; } ctx->m3g->renderVertexBuffer(v, surf, a[1].ref, a[2].ref, a[3].ref, model); + } else if (firstObj->nativeData) { + // render(Node node, Transform transform) or render(World world) + Mat4 model = Mat4::Identity(); + JObject* trObj = v.getObj(a[2].ref); + if (trObj && trObj->nativeData) { + model = static_cast(trObj->nativeData.get())->mat; + } + if (firstObj->className == "javax/microedition/m3g/Mesh") { + auto* md = static_cast(firstObj->nativeData.get()); + for (size_t i = 0; i < md->submeshRefs.size(); ++i) { + uint32_t appRef = + (i < md->appearanceRefs.size()) ? md->appearanceRefs[i] : 0; + ctx->m3g->renderVertexBuffer(v, surf, md->vertexBufferRef, + md->submeshRefs[i], appRef, model); + } + } } return JValue::Null(); }); @@ -1892,6 +1908,11 @@ inline void registerLcduiAndM3gNatives(Jvm& vm, RuntimeAppContext* ctx) { [](Jvm&, JThread&, JValue*) -> JValue { return JValue::Null(); }); vm.registerWildcardNative("javax/microedition/m3g/Graphics3D", "addLight", [](Jvm&, JThread&, JValue*) -> JValue { return JValue::FromInt(0); }); + vm.registerWildcardNative("javax/microedition/m3g/Graphics3D", "getProperties", + [](Jvm& v, JThread&, JValue*) -> JValue { + return JValue::FromRef( + v.allocObject("java/util/Hashtable")); + }); // VertexArray vm.registerWildcardNative( @@ -1982,6 +2003,26 @@ inline void registerLcduiAndM3gNatives(Jvm& vm, RuntimeAppContext* ctx) { } return JValue::Null(); }); + vm.registerWildcardNative( + "javax/microedition/m3g/VertexBuffer", "setTexCoords", + [](Jvm& v, JThread&, JValue* a) -> JValue { + JObject* o = v.getObj(a[0].ref); + if (o) { + if (!o->nativeData) o->nativeData = std::make_shared(); + auto* vb = static_cast(o->nativeData.get()); + vb->texCoordsRef = a[2].ref; + vb->texScale = (a[3].f != 0.0f) ? a[3].f : 1.0f; + JObject* biasArr = v.getObj(a[4].ref); + if (biasArr && biasArr->floatArr.size() >= 2) { + vb->texBias[0] = biasArr->floatArr[0]; + vb->texBias[1] = biasArr->floatArr[1]; + if (biasArr->floatArr.size() >= 3) { + vb->texBias[2] = biasArr->floatArr[2]; + } + } + } + return JValue::Null(); + }); vm.registerWildcardNative( "javax/microedition/m3g/VertexBuffer", "setDefaultColor", [](Jvm& v, JThread&, JValue* a) -> JValue { @@ -2059,7 +2100,14 @@ inline void registerLcduiAndM3gNatives(Jvm& vm, RuntimeAppContext* ctx) { "javax/microedition/m3g/Transform", "", [](Jvm& v, JThread&, JValue* a) -> JValue { JObject* o = v.getObj(a[0].ref); - if (o) o->nativeData = std::make_shared(); + if (o) { + auto td = std::make_shared(); + JObject* src = v.getObj(a[1].ref); + if (src && src->nativeData) { + td->mat = static_cast(src->nativeData.get())->mat; + } + o->nativeData = td; + } return JValue::Null(); }); vm.registerWildcardNative( @@ -2072,6 +2120,42 @@ inline void registerLcduiAndM3gNatives(Jvm& vm, RuntimeAppContext* ctx) { } return JValue::Null(); }); + vm.registerWildcardNative( + "javax/microedition/m3g/Transform", "set", + [](Jvm& v, JThread&, JValue* a) -> JValue { + JObject* o = v.getObj(a[0].ref); + JObject* arg = v.getObj(a[1].ref); + if (!o || !arg) return JValue::Null(); + if (!o->nativeData) o->nativeData = std::make_shared(); + auto* tr = static_cast(o->nativeData.get()); + if (arg->arrayKind == ArrayKind::Float && arg->floatArr.size() >= 16) { + // M3G float[16] is row-major; convert to column-major Mat4 + for (int row = 0; row < 4; ++row) { + for (int col = 0; col < 4; ++col) { + tr->mat.m[col * 4 + row] = arg->floatArr[row * 4 + col]; + } + } + } else if (arg->nativeData) { + tr->mat = static_cast(arg->nativeData.get())->mat; + } + return JValue::Null(); + }); + vm.registerWildcardNative( + "javax/microedition/m3g/Transform", "get", + [](Jvm& v, JThread&, JValue* a) -> JValue { + JObject* o = v.getObj(a[0].ref); + JObject* arg = v.getObj(a[1].ref); + if (o && o->nativeData && arg && arg->arrayKind == ArrayKind::Float && + arg->floatArr.size() >= 16) { + auto* tr = static_cast(o->nativeData.get()); + for (int row = 0; row < 4; ++row) { + for (int col = 0; col < 4; ++col) { + arg->floatArr[row * 4 + col] = tr->mat.m[col * 4 + row]; + } + } + } + return JValue::Null(); + }); vm.registerWildcardNative( "javax/microedition/m3g/Transform", "postTranslate", [](Jvm& v, JThread&, JValue* a) -> JValue { @@ -2105,6 +2189,22 @@ inline void registerLcduiAndM3gNatives(Jvm& vm, RuntimeAppContext* ctx) { } return JValue::Null(); }); + vm.registerWildcardNative( + "javax/microedition/m3g/Transform", "postMultiply", + [](Jvm& v, JThread&, JValue* a) -> JValue { + JObject* o = v.getObj(a[0].ref); + JObject* other = v.getObj(a[1].ref); + if (o && other && other->nativeData) { + if (!o->nativeData) o->nativeData = std::make_shared(); + auto* tr = static_cast(o->nativeData.get()); + auto* otr = static_cast(other->nativeData.get()); + tr->mat = Mat4::Multiply(tr->mat, otr->mat); + } + return JValue::Null(); + }); + vm.registerWildcardNative( + "javax/microedition/m3g/Transform", "invert", + [](Jvm&, JThread&, JValue*) -> JValue { return JValue::Null(); }); // Camera vm.registerWildcardNative( @@ -2126,7 +2226,7 @@ inline void registerLcduiAndM3gNatives(Jvm& vm, RuntimeAppContext* ctx) { return JValue::Null(); }); - // Background & Appearance + // Background, Mesh, Image2D, Texture2D, Appearance, PolygonMode, CompositingMode, Material vm.registerWildcardNative( "javax/microedition/m3g/Background", "", [](Jvm& v, JThread&, JValue* a) -> JValue { @@ -2146,17 +2246,155 @@ inline void registerLcduiAndM3gNatives(Jvm& vm, RuntimeAppContext* ctx) { return JValue::Null(); }); vm.registerWildcardNative( - "javax/microedition/m3g/Appearance", "", - [](Jvm&, JThread&, JValue*) -> JValue { return JValue::Null(); }); + "javax/microedition/m3g/Background", "setColorClearEnable", + [](Jvm& v, JThread&, JValue* a) -> JValue { + JObject* o = v.getObj(a[0].ref); + if (o) { + if (!o->nativeData) o->nativeData = std::make_shared(); + static_cast(o->nativeData.get())->colorClearEnabled = + (a[1].i != 0); + } + return JValue::Null(); + }); vm.registerWildcardNative( - "javax/microedition/m3g/PolygonMode", "", - [](Jvm&, JThread&, JValue*) -> JValue { return JValue::Null(); }); + "javax/microedition/m3g/Background", "setDepthClearEnable", + [](Jvm& v, JThread&, JValue* a) -> JValue { + JObject* o = v.getObj(a[0].ref); + if (o) { + if (!o->nativeData) o->nativeData = std::make_shared(); + static_cast(o->nativeData.get())->depthClearEnabled = + (a[1].i != 0); + } + return JValue::Null(); + }); + vm.registerWildcardNative( - "javax/microedition/m3g/CompositingMode", "", - [](Jvm&, JThread&, JValue*) -> JValue { return JValue::Null(); }); + "javax/microedition/m3g/Mesh", "", + [](Jvm& v, JThread&, JValue* a) -> JValue { + JObject* o = v.getObj(a[0].ref); + if (!o) return JValue::Null(); + auto md = std::make_shared(); + md->vertexBufferRef = a[1].ref; + JObject* subArg = v.getObj(a[2].ref); + JObject* appArg = v.getObj(a[3].ref); + if (subArg && subArg->arrayKind == ArrayKind::Ref) { + md->submeshRefs = subArg->refArr; + } else if (a[2].ref != 0) { + md->submeshRefs.push_back(a[2].ref); + } + if (appArg && appArg->arrayKind == ArrayKind::Ref) { + md->appearanceRefs = appArg->refArr; + } else if (a[3].ref != 0) { + md->appearanceRefs.push_back(a[3].ref); + } + o->nativeData = md; + return JValue::Null(); + }); vm.registerWildcardNative( - "javax/microedition/m3g/Material", "", - [](Jvm&, JThread&, JValue*) -> JValue { return JValue::Null(); }); + "javax/microedition/m3g/Mesh", "getVertexBuffer", + [](Jvm& v, JThread&, JValue* a) -> JValue { + JObject* o = v.getObj(a[0].ref); + if (o && o->nativeData) { + return JValue::FromRef( + static_cast(o->nativeData.get())->vertexBufferRef); + } + return JValue::Null(); + }); + vm.registerWildcardNative( + "javax/microedition/m3g/Mesh", "getIndexBuffer", + [](Jvm& v, JThread&, JValue* a) -> JValue { + JObject* o = v.getObj(a[0].ref); + if (o && o->nativeData) { + auto* md = static_cast(o->nativeData.get()); + if (a[1].i >= 0 && + static_cast(a[1].i) < md->submeshRefs.size()) { + return JValue::FromRef(md->submeshRefs[a[1].i]); + } + } + return JValue::Null(); + }); + vm.registerWildcardNative( + "javax/microedition/m3g/Mesh", "getAppearance", + [](Jvm& v, JThread&, JValue* a) -> JValue { + JObject* o = v.getObj(a[0].ref); + if (o && o->nativeData) { + auto* md = static_cast(o->nativeData.get()); + if (a[1].i >= 0 && + static_cast(a[1].i) < md->appearanceRefs.size()) { + return JValue::FromRef(md->appearanceRefs[a[1].i]); + } + } + return JValue::Null(); + }); + vm.registerWildcardNative( + "javax/microedition/m3g/Mesh", "setAppearance", + [](Jvm& v, JThread&, JValue* a) -> JValue { + JObject* o = v.getObj(a[0].ref); + if (o && o->nativeData) { + auto* md = static_cast(o->nativeData.get()); + int idx = a[1].i; + if (idx >= 0) { + if (static_cast(idx) >= md->appearanceRefs.size()) { + md->appearanceRefs.resize(idx + 1, 0); + } + md->appearanceRefs[idx] = a[2].ref; + } + } + return JValue::Null(); + }); + + for (const char* m3gCls : + {"javax/microedition/m3g/Object3D", + "javax/microedition/m3g/Transformable", + "javax/microedition/m3g/Node", + "javax/microedition/m3g/Group", + "javax/microedition/m3g/World", + "javax/microedition/m3g/Light", + "javax/microedition/m3g/Image2D", + "javax/microedition/m3g/Texture2D", + "javax/microedition/m3g/Appearance", + "javax/microedition/m3g/PolygonMode", + "javax/microedition/m3g/CompositingMode", + "javax/microedition/m3g/Material", + "javax/microedition/m3g/Fog"}) { + vm.registerWildcardNative( + m3gCls, "", + [](Jvm&, JThread&, JValue*) -> JValue { return JValue::Null(); }); + for (const char* noOpMethod : + {"set", "setBlending", "setFiltering", "setWrapping", "setTexture", + "setPolygonMode", "setCompositingMode", "setMaterial", "setFog", + "setCulling", "setShading", "setWinding", + "setPerspectiveCorrectionEnable", "setTwoSidedLightingEnable", + "setLocalCameraLightingEnable", "setAlphaThreshold", + "setAlphaWriteEnable", "setColorWriteEnable", "setDepthTestEnable", + "setDepthWriteEnable", "setDepthOffset", "setColor", + "setVertexColorTrackingEnable", "setTranslation", "setOrientation", + "setScale", "setTransform", "setRenderingEnable", "setPickingEnable", + "setScope", "addChild", "removeChild", "setActiveCamera", + "setBackground", "setIntensity", "setMode", "setAttenuation", + "setSpotAngle", "setSpotExponent", "setUserID", "setUserObject"}) { + vm.registerWildcardNative( + m3gCls, noOpMethod, + [](Jvm&, JThread&, JValue*) -> JValue { return JValue::Null(); }); + } + vm.registerWildcardNative( + m3gCls, "animate", + [](Jvm&, JThread&, JValue*) -> JValue { return JValue::FromInt(0); }); + vm.registerWildcardNative( + m3gCls, "find", + [](Jvm&, JThread&, JValue* a) -> JValue { + return JValue::FromRef(a[0].ref); + }); + } + + vm.registerWildcardNative( + "javax/microedition/m3g/Loader", "load", + [](Jvm& v, JThread&, JValue*) -> JValue { + uint32_t arr = v.allocRefArray("javax/microedition/m3g/Object3D", 1); + uint32_t wref = v.allocObject("javax/microedition/m3g/World"); + v.getObj(arr)->refArr[0] = wref; + return JValue::FromRef(arr); + }); } // --------------------------------------------------------------------------- diff --git a/src/games/remedy/remedy_m3g_gl.hpp b/src/games/remedy/remedy_m3g_gl.hpp index cb72788..cb0dbb3 100644 --- a/src/games/remedy/remedy_m3g_gl.hpp +++ b/src/games/remedy/remedy_m3g_gl.hpp @@ -147,6 +147,13 @@ struct M3gBackgroundData { bool depthClearEnabled = true; }; +struct M3gMeshData { + uint32_t vertexBufferRef = 0; + std::vector submeshRefs; + std::vector appearanceRefs; + std::vector childrenRefs; +}; + // --------------------------------------------------------------------------- // Adreno 304 (FD304) EGL + GLES2 Offscreen 3D Renderer (with SW Fallback) // --------------------------------------------------------------------------- diff --git a/src/games/remedy/remedy_main.cpp b/src/games/remedy/remedy_main.cpp index 1064fec..45756af 100644 --- a/src/games/remedy/remedy_main.cpp +++ b/src/games/remedy/remedy_main.cpp @@ -201,8 +201,22 @@ class RemedyEmulator { bool leftSoftDown = false; bool rightSoftDown = false; bool chordTriggered = false; + bool rightSoftLongTriggered = false; int pendingSoftkey = 0; // 1=left, 2=right int64_t pendingSoftkeyDeadlineMs = 0; + int64_t rightSoftPressMs = 0; + + // Minimum 80ms / 2-tick hold for Canvas key presses so polling game loops + // (e.g. 58ms sleep in Castlevania / Tomb Raider) never miss brisk key taps + struct ActiveCanvasKey { + uint32_t dispRef = 0; + int mask = 0; + int64_t pressedAtMs = 0; + uint64_t pressedAtTick = 0; + bool releaseQueued = false; + }; + std::unordered_map activeCanvasKeys; + uint64_t midletTickCount = 0; // FPS counter int frameCounter = 0; @@ -285,6 +299,7 @@ class RemedyEmulator { } void openXdrawerAndRestoreGrab() { + cldcRuntime.sound.setPaused(true); ungrabKeyboard(); std::system("dwm-plugin xdrawer >/dev/null 2>&1"); usleep(120000); @@ -298,6 +313,8 @@ class RemedyEmulator { XRaiseWindow(neoWin.dpy, neoWin.win); XSetInputFocus(neoWin.dpy, neoWin.win, RevertToParent, CurrentTime); grabKeyboard(); + cldcRuntime.sound.refreshSystemVolume(true); + cldcRuntime.sound.setPaused(mode != EmuUiMode::RUNNING); neoWin.checkReloadTheme(); appCtx.repaintPending = true; } @@ -404,6 +421,9 @@ class RemedyEmulator { } bool loadMidletSuite(const std::string& path) { + cldcRuntime.sound.stopAll(); + activeCanvasKeys.clear(); + midletTickCount = 0; std::string errMsg; if (!loadSuiteFromJarOrJad(path, &jar, &suite, &errMsg)) { statusBanner = errMsg.empty() ? "Failed to open JAR/JAD" : errMsg; @@ -448,7 +468,8 @@ class RemedyEmulator { auto [initCls, initM] = vm->resolveMethod(mainClass, "", "()V", false); if (initM && !initM->code.empty()) { - vm->invokeManagedSync(mainTh, initCls, initM, {JValue::FromRef(midletRef)}); + vm->invokeManagedSync(mainTh, initCls, initM, + {JValue::FromRef(midletRef)}, 5000000); } mainTh.pendingExceptionRef = 0; mainTh.frames.clear(); @@ -456,7 +477,7 @@ class RemedyEmulator { vm->resolveMethod(mainClass, "startApp", "()V", false); if (startM && !startM->code.empty()) { vm->invokeManagedSync(mainTh, startCls, startM, - {JValue::FromRef(midletRef)}); + {JValue::FromRef(midletRef)}, 25000000); } currentJarOrJadPath = path; @@ -504,13 +525,49 @@ class RemedyEmulator { } } - // 3. Step timers and background Java threads (game loops, socket/HTTP threads) + // 3. Step timers and background Java threads (game loops, socket/HTTP threads). + // Use a wall-clock budget (~60% of the frame interval) instead of a fixed + // instruction count so CPU-heavy loaders (level/asset unpacking in games + // like Castlevania) run at full interpreter speed, while idle games that + // sleep in Thread.sleep() / wait() still return to poll() immediately. cldcRuntime.tickTimersAndSerialCallbacks(*vm); - vm->stepThreads(15000); + { + int64_t frameMs = 1000 / std::max(1, cfg.fpsLimit); + int64_t budgetMs = std::max(6, (frameMs * 6) / 10); + int64_t deadline = Jvm::NowMs() + budgetMs; + int slices = 0; + do { + vm->stepThreads(20000); + ++slices; + } while (slices < 64 && !vm->exitRequested && !appCtx.midletDestroyed && + vm->anyThreadReady() && Jvm::NowMs() < deadline); + } + midletTickCount++; + + if (!activeCanvasKeys.empty()) { + int64_t nowMs = Jvm::NowMs(); + for (auto it = activeCanvasKeys.begin(); it != activeCanvasKeys.end();) { + if (it->second.releaseQueued && + (nowMs - it->second.pressedAtMs >= 80) && + (midletTickCount - it->second.pressedAtTick >= 2)) { + uint32_t dRef = it->second.dispRef; + int mask = it->second.mask; + int kc = it->first; + it = activeCanvasKeys.erase(it); + if (mask != 0) appCtx.latchedKeyStates &= ~mask; + sendCanvasKeyEvent(dRef, "keyReleased", kc); + appCtx.repaintPending = true; + } else { + ++it; + } + } + } if (appCtx.midletDestroyed || vm->exitRequested) { + cldcRuntime.sound.stopAll(); hasLoadedMidlet = false; mode = EmuUiMode::BROWSER; + renderBrowserMenu(); return; } @@ -695,8 +752,18 @@ class RemedyEmulator { " FPS >"); items.push_back(std::string("FPS Overlay: ") + (cfg.showFps ? "< Shown >" : "< Hidden >")); - items.push_back(std::string("Audio (MMAPI): ") + - (cfg.audioEnabled ? "< ON >" : "< Muted >")); + // "Audio" shows the system speaker volume (shared with xdrawer and every + // other app); Left/Right change it system-wide, OK toggles ReMEdy sound. + int sysVol = cldcRuntime.sound.volumePct.load(); + std::string volLabel; + if (!cfg.audioEnabled) { + volLabel = "< Off >"; + } else if (cldcRuntime.sound.isSystemMuted()) { + volLabel = "< Speaker muted >"; + } else { + volLabel = "< " + std::to_string(sysVol) + "% >"; + } + items.push_back(std::string("Audio (MMAPI): ") + volLabel); items.push_back("Keypad Controls..."); if (hasLoadedMidlet) { items.push_back("Restart MIDlet"); @@ -899,7 +966,8 @@ class RemedyEmulator { } // Forward -6 to Canvas.keyPressed(-6) if fullScreen Canvas has no commands if (isCanvasDisplayable(*vm, dispRef)) { - sendCanvasKeyEvent(dispRef, "keyPressed", -6); + pressCanvasKey(dispRef, -6, 0); + if (!leftSoftDown) releaseCanvasKey(-6); } } else if (softkeyIdx == 2) { if (rightCmd != 0) { @@ -908,8 +976,15 @@ class RemedyEmulator { appCtx.repaintPending = true; return; } - // If MIDlet registered commands only on Left Softkey or none at all, - // Right Softkey opens the ReMEdy Pause Menu (or forwards -7 if Canvas handles it) + // If active Displayable is a Canvas with no LCDUI commands attached, + // forward Right Softkey (-7) directly to Canvas.keyPressed(-7) so full-screen + // games (Castlevania, Tomb Raider, AstroBlaster, etc.) receive Right Softkey. + // Holding Right Softkey >= 500ms or pressing End/Power (Escape) opens Pause Menu. + if (isCanvasDisplayable(*vm, dispRef) && st->commands.empty()) { + pressCanvasKey(dispRef, -7, 0); + if (!rightSoftDown) releaseCanvasKey(-7); + return; + } mode = EmuUiMode::PAUSED; renderPauseMenu(); } @@ -929,6 +1004,47 @@ class RemedyEmulator { } } + void pressCanvasKey(uint32_t dispRef, int kc, int mask) { + if (!vm || dispRef == 0 || kc == 0) return; + auto existing = activeCanvasKeys.find(kc); + if (existing != activeCanvasKeys.end()) { + if (existing->second.releaseQueued) { + if (existing->second.mask != 0) { + appCtx.latchedKeyStates &= ~existing->second.mask; + } + sendCanvasKeyEvent(existing->second.dispRef, "keyReleased", kc); + } + activeCanvasKeys.erase(existing); + } + ActiveCanvasKey ak; + ak.dispRef = dispRef; + ak.mask = mask; + ak.pressedAtMs = Jvm::NowMs(); + ak.pressedAtTick = midletTickCount; + ak.releaseQueued = false; + activeCanvasKeys[kc] = ak; + if (mask != 0) appCtx.latchedKeyStates |= mask; + sendCanvasKeyEvent(dispRef, "keyPressed", kc); + appCtx.repaintPending = true; + } + + void releaseCanvasKey(int kc) { + auto it = activeCanvasKeys.find(kc); + if (it == activeCanvasKeys.end()) return; + int64_t nowMs = Jvm::NowMs(); + if ((nowMs - it->second.pressedAtMs >= 80) && + (midletTickCount - it->second.pressedAtTick >= 2)) { + uint32_t dRef = it->second.dispRef; + int mask = it->second.mask; + activeCanvasKeys.erase(it); + if (mask != 0) appCtx.latchedKeyStates &= ~mask; + sendCanvasKeyEvent(dRef, "keyReleased", kc); + appCtx.repaintPending = true; + } else { + it->second.releaseQueued = true; + } + } + void handleHighLevelKeyPress(uint32_t dispRef, KeySym ks) { JObject* dispObj = vm->getObj(dispRef); LcduiScreenState* st = ensureScreenState(*vm, dispRef); @@ -1106,6 +1222,15 @@ class RemedyEmulator { ks = XK_Escape; } + if (ks == XF86XK_AudioLowerVolume || ks == XF86XK_AudioRaiseVolume) { + int step = (ks == XF86XK_AudioRaiseVolume) ? 5 : -5; + int cur = cldcRuntime.sound.volumePct.load(); + int newVol = std::clamp(((cur + step) / 5) * 5, 0, 100); + cldcRuntime.sound.setSystemVolume(newVol); + if (mode == EmuUiMode::PAUSED) renderPauseMenu(); + return true; + } + // Softkey chord detection (both softkeys pressed within 45 ms -> xdrawer) bool isLeftSoft = (ks == XK_F1 || ks == XK_Super_L); bool isRightSoft = (ks == XK_F2 || (ks == XK_BackSpace && mode != EmuUiMode::RUNNING)); @@ -1132,7 +1257,11 @@ class RemedyEmulator { } if (isLeftSoft) leftSoftDown = true; - if (isRightSoft) rightSoftDown = true; + if (isRightSoft) { + rightSoftDown = true; + rightSoftPressMs = Jvm::NowMs(); + rightSoftLongTriggered = false; + } if (leftSoftDown && rightSoftDown) { chordTriggered = true; pendingSoftkey = 0; @@ -1158,18 +1287,26 @@ class RemedyEmulator { ks == _EVDEVK(0x247)) { ks = XK_F2; } - if (ks == XK_F1 || ks == XK_Super_L) leftSoftDown = false; - if (ks == XK_F2 || ks == XK_BackSpace) rightSoftDown = false; + bool wasLeftSoft = (ks == XK_F1 || ks == XK_Super_L); + bool wasRightSoft = (ks == XK_F2 || ks == XK_BackSpace); + if (wasLeftSoft) leftSoftDown = false; + if (wasRightSoft) rightSoftDown = false; if (!leftSoftDown && !rightSoftDown) chordTriggered = false; if (mode == EmuUiMode::RUNNING && vm && appCtx.currentDisplayableRef != 0 && isCanvasDisplayable(*vm, appCtx.currentDisplayableRef)) { + if (wasLeftSoft) { + releaseCanvasKey(-6); + return; + } + if (wasRightSoft) { + releaseCanvasKey(-7); + return; + } int mask = 0; int kc = mapKeysymToMidpKeyCode(ks, &mask); - if (mask != 0) appCtx.latchedKeyStates &= ~mask; if (kc != 0 && !appCtx.commandMenuOpen) { - sendCanvasKeyEvent(appCtx.currentDisplayableRef, "keyReleased", kc); - appCtx.repaintPending = true; + releaseCanvasKey(kc); } } } @@ -1293,9 +1430,16 @@ class RemedyEmulator { cfg.showFps = !cfg.showFps; cfg.save(); } else if (choice.rfind("Audio (MMAPI):", 0) == 0) { - cfg.audioEnabled = !cfg.audioEnabled; - cldcRuntime.sound.enabled = cfg.audioEnabled; - cfg.save(); + if (ks == XK_Left || ks == XK_Right) { + int cur = cldcRuntime.sound.volumePct.load(); + int step = (ks == XK_Left) ? -5 : 5; + cldcRuntime.sound.setSystemVolume( + std::clamp(((cur + step) / 5) * 5, 0, 100)); + } else { + cfg.audioEnabled = !cfg.audioEnabled; + cldcRuntime.sound.enabled = cfg.audioEnabled; + cfg.save(); + } } else if (choice == "Keypad Controls...") { controlsSel = 0; controlsScroll = 0; @@ -1401,10 +1545,8 @@ class RemedyEmulator { int mask = 0; int kc = mapKeysymToMidpKeyCode(ks, &mask); - if (mask != 0) appCtx.latchedKeyStates |= mask; if (kc != 0) { - sendCanvasKeyEvent(dispRef, "keyPressed", kc); - appCtx.repaintPending = true; + pressCanvasKey(dispRef, kc, mask); } return true; } @@ -1429,6 +1571,7 @@ class RemedyEmulator { bool running = true; while (running) { updateTimer(cfg.fpsLimit); + cldcRuntime.sound.setPaused(mode != EmuUiMode::RUNNING); while (XPending(neoWin.dpy) > 0) { XEvent ev; XNextEvent(neoWin.dpy, &ev); @@ -1475,6 +1618,18 @@ class RemedyEmulator { } if (!running) break; + if (mode == EmuUiMode::RUNNING && rightSoftDown && !leftSoftDown && + !chordTriggered && !rightSoftLongTriggered && + Jvm::NowMs() - rightSoftPressMs >= 500) { + rightSoftLongTriggered = true; + pendingSoftkey = 0; + releaseCanvasKey(-7); + pauseSel = 0; + pauseScroll = 0; + mode = EmuUiMode::PAUSED; + renderPauseMenu(); + } + if (pendingSoftkey != 0 && Jvm::NowMs() >= pendingSoftkeyDeadlineMs) { int s = pendingSoftkey; pendingSoftkey = 0; @@ -1488,7 +1643,7 @@ class RemedyEmulator { pfds[0].events = POLLIN; pfds[1].fd = tfd; pfds[1].events = POLLIN; - int timeoutMs = (pendingSoftkey != 0) ? 10 : 50; + int timeoutMs = (pendingSoftkey != 0 || rightSoftDown) ? 10 : 50; int pr = poll(pfds, (tfd >= 0) ? 2 : 1, timeoutMs); if (pr > 0 && tfd >= 0 && (pfds[1].revents & POLLIN)) { uint64_t exp = 0;