--- a/scripts/genie.lua +++ b/scripts/genie.lua @@ -1166,22 +1166,23 @@ "-Wno-implicit-function-declaration", "-s USE_SDL_TTF=2", } + -- Keep async startup frames live across Emscripten unwind. Enabling catches + -- in cli_frontend or running_machine::run creates invoke stack restores. buildoptions_cpp { "-std=c++17", - "-s EXCEPTION_CATCHING_ALLOWED=\"['_ZN15running_machine17start_all_devicesEv','_ZN12cli_frontend7executeEiPPc','_ZN8chd_file11open_commonEb','_ZN8chd_file13read_metadataEjjRNSt3__212basic_stringIcNS0_11char_traitsIcEENS0_9allocatorIcEEEE','_ZN8chd_file13read_metadataEjjRNSt3__26vectorIhNS0_9allocatorIhEEEE','_ZNK19netlist_mame_device19base_validity_checkER16validity_checker']\"", + "-s EXCEPTION_CATCHING_ALLOWED=\"['_ZN15running_machine17start_all_devicesEv','_ZN8chd_file11open_commonEb','_ZN8chd_file13read_metadataEjjRNSt3__212basic_stringIcNS0_11char_traitsIcEENS0_9allocatorIcEEEE','_ZN8chd_file13read_metadataEjjRNSt3__26vectorIhNS0_9allocatorIhEEEE','_ZNK19netlist_mame_device19base_validity_checkER16validity_checker']\"", } defines { "ASIO_HAS_PTHREADS", } linkoptions { "-Wl,--start-group", + "-s DISABLE_EXCEPTION_CATCHING=0", "-O" .. _OPTIONS["OPTIMIZE"], "-s USE_SDL=2", "-s USE_SDL_TTF=2", - "--memory-init-file 0", - "-s DEFAULT_LIBRARY_FUNCS_TO_INCLUDE=\"['\\$$ERRNO_CODES']\"", "-s EXPORTED_FUNCTIONS=\"['_main', '_malloc', '__ZN15running_machine30emscripten_get_running_machineEv', '__ZN15running_machine17emscripten_get_uiEv', '__ZN15running_machine20emscripten_get_soundEv', '__ZN15mame_ui_manager12set_show_fpsEb', '__ZNK15mame_ui_manager8show_fpsEv', '__ZN13sound_manager4muteEbh', '_SDL_PauseAudio', '_SDL_SendKeyboardKey', '__ZN15running_machine15emscripten_saveEPKc', '__ZN15running_machine15emscripten_loadEPKc', '__ZN15running_machine21emscripten_hard_resetEv', '__ZN15running_machine21emscripten_soft_resetEv', '__ZN15running_machine15emscripten_exitEv']\"", - "-s EXPORTED_RUNTIME_METHODS=\"['cwrap']\"", + "-s EXPORTED_RUNTIME_METHODS=\"['cwrap','FS','callMain','Browser']\"", "-s ERROR_ON_UNDEFINED_SYMBOLS=0", "-s USE_WEBGL2=1", "-s LEGACY_GL_EMULATION=1", @@ -1218,6 +1219,7 @@ else linkoptions { "-s ALLOW_MEMORY_GROWTH=1", + "-s MAXIMUM_MEMORY=536870912", } end archivesplit_size "20" --- a/scripts/src/mame/frontend.lua +++ b/scripts/src/mame/frontend.lua @@ -73,10 +73,6 @@ MAME_DIR .. "src/frontend/mame/luaengine.cpp", MAME_DIR .. "src/frontend/mame/luaengine.h", MAME_DIR .. "src/frontend/mame/luaengine.ipp", - MAME_DIR .. "src/frontend/mame/luaengine_debug.cpp", - MAME_DIR .. "src/frontend/mame/luaengine_input.cpp", - MAME_DIR .. "src/frontend/mame/luaengine_mem.cpp", - MAME_DIR .. "src/frontend/mame/luaengine_render.cpp", MAME_DIR .. "src/frontend/mame/mame.cpp", MAME_DIR .. "src/frontend/mame/mame.h", MAME_DIR .. "src/frontend/mame/mameopts.cpp", @@ -198,6 +194,16 @@ MAME_DIR .. "src/frontend/mame/ui/widgets.h", } +-- The asmjs target retains Lua lifecycle support without plugin userdata bindings. +if (_OPTIONS["targetos"] ~= "asmjs") then + files { + MAME_DIR .. "src/frontend/mame/luaengine_debug.cpp", + MAME_DIR .. "src/frontend/mame/luaengine_input.cpp", + MAME_DIR .. "src/frontend/mame/luaengine_mem.cpp", + MAME_DIR .. "src/frontend/mame/luaengine_render.cpp", + } +end + pchsource(MAME_DIR .. "src/frontend/mame/audit.cpp") dependency { --- a/src/emu/machine.cpp +++ b/src/emu/machine.cpp @@ -1301,11 +1301,25 @@ #if defined(__EMSCRIPTEN__) +// The reduced Dream Life browser target supplies the EEPROM transaction guard. +extern "C" bool dreamlife_nvram_safe(running_machine *machine); + running_machine * running_machine::emscripten_running_machine; +static double browser_last_tick_ms = 0.0; +static double browser_frame_debt_ms = 0.0; void running_machine::emscripten_main_loop() { running_machine *machine = emscripten_running_machine; + const double now = emscripten_get_now(); + double elapsed = now - browser_last_tick_ms; + browser_last_tick_ms = now; + // Never fast-forward a hidden tab or replay a long interruption. + if (elapsed < 0.0 || elapsed > 250.0 || EM_ASM_INT({ return document.hidden ? 1 : 0; })) + { + browser_frame_debt_ms = 0.0; + return; + } auto profile = g_profiler.start(PROFILER_EXTRA); @@ -1315,9 +1329,15 @@ device_scheduler * scheduler; scheduler = &(machine->scheduler()); - // Emscripten will call this function at 60Hz, so step the simulation - // forward for the amount of time that has passed since the last frame + // Browser callbacks may be 30/60/120 Hz or late. Execute fixed original + // 60 Hz steps from elapsed time, with bounded catch-up, at any refresh. + constexpr double frame_ms = 1000.0 / 60.0; + browser_frame_debt_ms = std::min(browser_frame_debt_ms + elapsed, frame_ms * 4.0); + const int steps = std::min(4, int((browser_frame_debt_ms + 0.000001) / frame_ms)); const attotime frametime(0,HZ_TO_ATTOSECONDS(60)); + for (int step = 0; step < steps && !machine->m_paused; ++step) + { + browser_frame_debt_ms -= frame_ms; const attotime stoptime(scheduler->time() + frametime); while (!machine->m_paused && !machine->scheduled_event_pending() && scheduler->time() < stoptime) @@ -1330,15 +1350,20 @@ break; } } + } } // otherwise, just pump video updates through else + { + browser_frame_debt_ms = 0.0; machine->m_video->frame_update(); + } // cancel the emscripten loop if the system has been told to exit if (machine->exit_pending()) { emscripten_cancel_main_loop(); + emscripten_running_machine = nullptr; } } @@ -1348,6 +1373,10 @@ EM_ASM ( JSMESS.running = true; ); + browser_last_tick_ms = emscripten_get_now(); + browser_frame_debt_ms = 0.0; + // Vsync scheduling avoids mobile timer clamping; elapsed-time steps above + // preserve the hardware clock on high-refresh and variable-refresh screens. emscripten_set_main_loop(&(emscripten_main_loop), 0, 1); } @@ -1382,4 +1411,42 @@ emscripten_running_machine->schedule_load(name); } +bool running_machine::emscripten_flush_nvram() +{ + running_machine *const machine = emscripten_running_machine; + if (!machine || machine->phase() != machine_phase::RUNNING || machine->exit_pending() || !dreamlife_nvram_safe(machine)) + return false; + + // The normal Emscripten loop does not reach the native shutdown save path. + // Flush only the original EEPROM; this does not save live game RAM. + machine->nvram_save(); + return true; +} + +extern "C" EMSCRIPTEN_KEEPALIVE int dreamlife_flush_nvram() +{ + // A true result means a safe flush was attempted. The browser also checks + // that the resulting EEPROM file is exactly 512 bytes before committing it. + return running_machine::emscripten_flush_nvram() ? 1 : 0; +} + +// Read-only timing probe: compares emulated seconds with browser elapsed time. +extern "C" EMSCRIPTEN_KEEPALIVE double dreamlife_emulated_seconds() +{ + running_machine *const machine = running_machine::emscripten_get_running_machine(); + return machine ? machine->time().as_double() : 0.0; +} + +extern "C" EMSCRIPTEN_KEEPALIVE int dreamlife_pause(int paused) +{ + running_machine *const machine = running_machine::emscripten_get_running_machine(); + if (!machine || machine->phase() != machine_phase::RUNNING || machine->exit_pending()) + return 0; + if (paused) + machine->pause(); + else + machine->resume(); + return 1; +} + #endif /* defined(__EMSCRIPTEN__) */ --- a/src/emu/machine.h +++ b/src/emu/machine.h @@ -361,6 +361,7 @@ static void emscripten_soft_reset(); static void emscripten_save(const char *name); static void emscripten_load(const char *name); + static bool emscripten_flush_nvram(); #endif }; --- a/src/emu/video.cpp +++ b/src/emu/video.cpp @@ -663,6 +663,11 @@ void video_manager::update_throttle(attotime emutime) { +#if defined(__EMSCRIPTEN__) + // The browser loop already paces fixed simulation steps to elapsed time. + // Native sleep/spin blocks the UI and audio producer on this same thread. + return; +#endif /* Throttling theory: --- a/src/frontend/mame/luaengine.cpp +++ b/src/frontend/mame/luaengine.cpp @@ -759,6 +759,8 @@ void lua_engine::initialize() { +#if !defined(__EMSCRIPTEN__) + // Browser preservation target omits optional Lua developer/plugin bindings. static const enum_parser s_movie_recording_format_parser = { @@ -2172,6 +2174,7 @@ initialize_input(emu); initialize_memory(emu); initialize_render(emu); +#endif } //------------------------------------------------- --- a/src/mame/tvgames/spg2xx_dreamlife.cpp +++ b/src/mame/tvgames/spg2xx_dreamlife.cpp @@ -11,6 +11,9 @@ #include "machine/eepromser.h" +#if defined(__EMSCRIPTEN__) +#include +#endif namespace { @@ -24,11 +27,24 @@ void dreamlif(machine_config &config); +#if defined(__EMSCRIPTEN__) + bool browser_nvram_safe() const + { + return !(m_browser_eeprom_signals & 1) && m_eeprom->ready() + && machine().time() >= m_browser_eeprom_activity + attotime::from_msec(100); + } +#endif + private: uint16_t portb_r(); virtual void portb_w(offs_t offset, uint16_t data, uint16_t mem_mask = ~0) override; required_device m_eeprom; + +#if defined(__EMSCRIPTEN__) + uint16_t m_browser_eeprom_signals = 0; + attotime m_browser_eeprom_activity = attotime::zero; +#endif }; @@ -42,6 +58,16 @@ void dreamlif_state::portb_w(offs_t offset, uint16_t data, uint16_t mem_mask) { +#if defined(__EMSCRIPTEN__) + // CS, CLK and DI are the only output signals wired to the EEPROM. + // Wait for a quiet interval after their final transition before persisting. + uint16_t const signals = data & 0x0007; + if (signals != m_browser_eeprom_signals) + { + m_browser_eeprom_signals = signals; + m_browser_eeprom_activity = machine().time(); + } +#endif logerror("%s: portb_w (%04x)\n", machine().describe_context(), data); m_eeprom->di_write(BIT(data, 2)); m_eeprom->cs_write(BIT(data, 0) ? ASSERT_LINE : CLEAR_LINE); @@ -138,6 +164,15 @@ } // anonymous namespace +#if defined(__EMSCRIPTEN__) +extern "C" bool dreamlife_nvram_safe(running_machine *machine) +{ + if (!machine || std::strcmp(machine->system().name, "dreamlif")) + return false; + return static_cast(machine->root_device()).browser_nvram_safe(); +} +#endif + // Hasbro games CONS( 2005, dreamlif, 0, 0, dreamlif, dreamlif, dreamlif_state, empty_init, "Hasbro", "Dream Life (Version 1.0, Feb 07 2005)", MACHINE_IMPERFECT_SOUND ) --- a/src/osd/modules/sound/js_sound.js +++ b/src/osd/modules/sound/js_sound.js @@ -1,220 +1,88 @@ // license:BSD-3-Clause // copyright-holders:Grant Galitz, Katelyn Gadd -/*************************************************************************** +// Dream Life browser adapter: schedule PCM on Web Audio's rendering thread. +// This also works on LAN HTTP, where AudioWorklet is unavailable. +var jsmame_web_audio = (function () { + var context = null, gain_node = null, nextStart = 0; + var sources = new Set(); + var leadSeconds = 0.080, maxQueueSeconds = 0.250; + var stats = { scheduledFrames: 0, completedFrames: 0, droppedFrames: 0, + underruns: 0, maxLatenessMs: 0, nonFinite: 0, maxRms: 0, peak: 0, flushes: 0, errors: 0 }; - JSMAME web audio backend v0.4 + function flush() { + sources.forEach(function (source) { + source.onended = null; + try { source.stop(); } catch (_) {} + try { source.disconnect(); } catch (_) {} + }); + sources.clear(); nextStart = 0; stats.flushes++; + } - Original by katelyn gadd - kg at luminance dot org ; @antumbral on twitter - Substantial changes by taisel + function lazy_init() { + if (context) return; + var Constructor = window.AudioContext || window.webkitAudioContext; + if (!window.dreamlife_audio_context && !Constructor) return; + context = window.dreamlife_audio_context || new Constructor({ latencyHint: 'playback' }); + gain_node = context.createGain(); gain_node.gain.value = 1; + gain_node.connect(context.destination); + context.addEventListener('statechange', function () { if (context.state !== 'running') flush(); }); + } -***************************************************************************/ + function set_mastervolume(attenuation) { + lazy_init(); + if (context) gain_node.gain.value = Math.max(0, Math.min(1, 1 + attenuation / 32)); + } -var jsmame_web_audio = (function () { + function update_audio_stream(pointer, frames) { + lazy_init(); + if (!context || frames <= 0) return; + if (context.state !== 'running') { stats.droppedFrames += frames; return; } + var now = context.currentTime; + if (!nextStart) nextStart = now + leadSeconds; + else if (nextStart < now + 0.004) { + stats.underruns++; + stats.maxLatenessMs = Math.max(stats.maxLatenessMs, (now - nextStart) * 1000); + // Retain the original sample rate and pitch when recovering from lateness. + nextStart = now + leadSeconds; + } + if (nextStart - now > maxQueueSeconds || sources.size >= 24) { + stats.droppedFrames += frames; return; + } + var buffer = context.createBuffer(2, frames, context.sampleRate); + var left = buffer.getChannelData(0), right = buffer.getChannelData(1); + var base = pointer >> 1, sum = 0; + for (var i = 0; i < frames; i++) { + var l = HEAP16[base + i * 2] / 32768, r = HEAP16[base + i * 2 + 1] / 32768; + if (!Number.isFinite(l) || !Number.isFinite(r)) { stats.nonFinite++; l = r = 0; } + left[i] = l; right[i] = r; sum += l * l + r * r; + stats.peak = Math.max(stats.peak, Math.abs(l), Math.abs(r)); + } + stats.maxRms = Math.max(stats.maxRms, Math.sqrt(sum / (frames * 2))); + var source = context.createBufferSource(); source.buffer = buffer; source.connect(gain_node); + source.onended = function () { + sources.delete(source); source.disconnect(); stats.completedFrames += frames; + }; + try { source.start(nextStart); } + catch (_) { source.onended = null; source.disconnect(); stats.errors++; return; } + sources.add(source); nextStart += frames / context.sampleRate; stats.scheduledFrames += frames; + } -var context = null; -var gain_node = null; -var eventNode = null; -var sampleScale = 32766; -var inputBuffer = new Float32Array(44100); -var bufferSize = 44100; -var start = 0; -var rear = 0; -var watchDogDateLast = null; -var watchDogTimerEvent = null; + function sample_count() { + if (!context) return -1; + return Math.max(0, Math.round((nextStart - context.currentTime) * context.sampleRate)) * 2; + } -function lazy_init () { - //Make - if (context) { - //Return if already created: - return; - } - if (typeof AudioContext != "undefined") { - //Standard context creation: - context = new AudioContext(); - } - else if (typeof webkitAudioContext != "undefined") { - //Older webkit context creation: - context = new webkitAudioContext(); - } - else { - //API not found! - return; - } - //Generate a volume control node: - gain_node = context.createGain(); - //Set initial volume to 1: - gain_node.gain.value = 1.0; - //Connect volume node to output: - gain_node.connect(context.destination); - //Initialize the streaming event: - init_event(); -}; + function get_stats() { + return Object.assign({ backend: 'scheduled-buffers', sampleRate: context ? context.sampleRate : null, + queueMs: context && nextStart ? Math.max(0, (nextStart - context.currentTime) * 1000) : 0, + buffers: sources.size, leadMs: leadSeconds * 1000 }, stats); + } -function init_event() { - //Generate a streaming node point: - if (typeof context.createScriptProcessor == "function") { - //Current standard compliant way: - eventNode = context.createScriptProcessor(4096, 0, 2); - } - else { - //Deprecated way: - eventNode = context.createJavaScriptNode(4096, 0, 2); - } - //Make our tick function the audio callback function: - eventNode.onaudioprocess = tick; - //Connect stream to volume control node: - eventNode.connect(gain_node); - //Workarounds for browser issues: - initializeWatchDog(); -}; - -function initializeWatchDog() { - watchDogDateLast = (new Date()).getTime(); - if (watchDogTimerEvent === null) { - watchDogTimerEvent = setInterval(function () { - var timeDiff = (new Date()).getTime() - watchDogDateLast; - if (timeDiff > 500) { - //WORKAROUND FOR FIREFOX BUG: - //TODO: decide if we want to user agent sniff Firefox here, - //since Google Chrome doesn't need this: - disconnect_old_event(); - init_event(); - - //Work around autoplay restrictions in Chrome 71+ https://developers.google.com/web/updates/2017/09/autoplay-policy-changes#webaudio - if (context) { - context.resume(); - } - } - }, 500); - } -}; - -function disconnect_old_event() { - //Disconnect from audio graph: - eventNode.disconnect(); - //IIRC there was a firefox bug that did not GC this event when nulling the node itself: - eventNode.onaudioprocess = null; - //Null the glitched/unused node: - eventNode = null; -}; - -function set_mastervolume ( - // even though it's 'attenuation' the value is negative, so... - attenuation_in_decibels -) { - lazy_init(); - if (!context) return; - - // http://stackoverflow.com/questions/22604500/web-audio-api-working-with-decibels - // seemingly incorrect/broken. figures. welcome to Web Audio - // var gain_web_audio = 1.0 - Math.pow(10, 10 / attenuation_in_decibels); - - // HACK: Max attenuation in JSMESS appears to be 32. - // Hit ' then left/right arrow to test. - // FIXME: This is linear instead of log10 scale. - var gain_web_audio = 1.0 + (+attenuation_in_decibels / +32); - if (gain_web_audio < +0) - gain_web_audio = +0; - else if (gain_web_audio > +1) - gain_web_audio = +1; - - gain_node.gain.value = gain_web_audio; -}; - -function update_audio_stream ( - pBuffer, // pointer into emscripten heap. int16 samples - samples_this_frame // int. number of samples at pBuffer address. -) { - lazy_init(); - if (!context) return; - - for ( - var i = 0, - l = samples_this_frame | 0; - i < l; - i++ - ) { - var offset = - // divide by sizeof(int16_t) since pBuffer is offset - // in bytes - ((pBuffer / 2) | 0) + - ((i * 2) | 0); - - var left_sample = HEAP16[offset]; - var right_sample = HEAP16[(offset + 1) | 0]; - - // normalize from signed int16 to signed float - var left_sample_float = left_sample / sampleScale; - var right_sample_float = right_sample / sampleScale; - - inputBuffer[rear++] = left_sample_float; - inputBuffer[rear++] = right_sample_float; - if (rear == bufferSize) { - rear = 0; - } - if (start == rear) { - start += 2; - if (start == bufferSize) { - start = 0; - } - } - } -}; -function tick (event) { - //Find all output channels: - for (var bufferCount = 0, buffers = []; bufferCount < 2; ++bufferCount) { - buffers[bufferCount] = event.outputBuffer.getChannelData(bufferCount); - } - //Copy samples from the input buffer to the Web Audio API: - for (var index = 0; index < 4096 && start != rear; ++index) { - buffers[0][index] = inputBuffer[start++]; - buffers[1][index] = inputBuffer[start++]; - if (start == bufferSize) { - start = 0; - } - } - //Pad with latest if we're underrunning: - var idx = (index == 0 ? bufferSize : index) - 1; - while (index < 4096) { - buffers[0][index] = buffers[0][idx]; - buffers[1][index++] = buffers[1][idx]; - } - //Deep inside the bowels of vendors bugs, - //we're using watchdog for a firefox bug, - //where the user agent decides to stop firing events - //if the user agent lags out due to system load. - //Don't even ask.... - watchDogDateLast = (new Date()).getTime(); -} - -function get_context() { - return context; -}; - -function sample_count() { - //TODO get someone to call this from the emulator, - //so the emulator can do proper audio buffering by - //knowing how many samples are left: - if (!context) { - //Use impossible value as an error code: - return -1; - } - var count = rear - start; - if (start > rear) { - count += bufferSize; - } - return count; -} - -return { - set_mastervolume: set_mastervolume, - update_audio_stream: update_audio_stream, - get_context: get_context, - sample_count: sample_count -}; - + return { set_mastervolume: set_mastervolume, update_audio_stream: update_audio_stream, + get_context: function () { return context; }, sample_count: sample_count, get_stats: get_stats, flush: flush }; })(); window.jsmame_set_mastervolume = jsmame_web_audio.set_mastervolume; window.jsmame_update_audio_stream = jsmame_web_audio.update_audio_stream; window.jsmame_sample_count = jsmame_web_audio.sample_count; +window.jsmame_web_audio = jsmame_web_audio; --- a/src/osd/sdl/window.cpp +++ b/src/osd/sdl/window.cpp @@ -853,6 +853,11 @@ // soft driver also used | SDL_WINDOW_INPUT_GRABBED | SDL_WINDOW_MOUSE_FOCUS m_extra_flags |= (fullscreen() ? SDL_WINDOW_INPUT_FOCUS | SDL_WINDOW_FULLSCREEN : SDL_WINDOW_RESIZABLE); +#if defined(SDLMAME_EMSCRIPTEN) + // Render the original pixel grid. CSS scales the display without asking + // SDL's software rasterizer to redraw at the phone/desktop layout size. + m_extra_flags &= ~SDL_WINDOW_RESIZABLE; +#endif #if defined(SDLMAME_WIN32) SDL_SetHint(SDL_HINT_VIDEO_MINIMIZE_ON_FOCUS_LOSS, "0");