Skip to content

Instantly share code, notes, and snippets.

@DopefishJustin
Created July 13, 2017 17:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DopefishJustin/d79b5fce9621c78dca50fdaefe6cc1d0 to your computer and use it in GitHub Desktop.
Save DopefishJustin/d79b5fce9621c78dca50fdaefe6cc1d0 to your computer and use it in GitHub Desktop.
diff --git a/src/emu/machine.cpp b/src/emu/machine.cpp
index 7c59ef6..7d0b1d2 100644
--- a/src/emu/machine.cpp
+++ b/src/emu/machine.cpp
@@ -1347,10 +1347,36 @@ void js_main_loop()
{
device_scheduler * scheduler;
scheduler = &(jsmess_machine->scheduler());
- attotime stoptime(scheduler->time() + attotime(0,HZ_TO_ATTOSECONDS(60)));
+
+ // we use a requestAnimationFrame callback which is commonly 60Hz but can vary due to monitor refresh rate, low battery mode, etc.
+ // so we must empirically determine how long to run the emulation for
+ static double prev_time = 0;
+ double curr_time = emscripten_get_now(); // in ms
+ double elapsed_time = curr_time - prev_time;
+ attoseconds_t time_to_run;
+ // if we get way behind, don't do more than 1/30 of a second worth
+ if (elapsed_time < 1000.0/30.0) {
+ time_to_run = ATTOSECONDS_IN_MSEC(elapsed_time);
+ }
+ else {
+ time_to_run = HZ_TO_ATTOSECONDS(30);
+ }
+ prev_time = curr_time;
+
+ attotime stoptime(scheduler->time() + attotime(0,time_to_run));
+
while (scheduler->time() < stoptime) {
scheduler->timeslice();
}
+
+ // check the audio buffer, if we are about to run out then run a little extra
+ // (will return -1 if web audio is unavailable)
+ if (EM_ASM_INT_V({return jsmame_sample_count()}) > -1) {
+ int sample_rate = jsmess_machine->sound().first_stream()->sample_rate();
+ while (EM_ASM_INT_V({return jsmame_sample_count()}) < sample_rate/60) {
+ scheduler->timeslice();
+ }
+ }
}
void js_set_main_loop(running_machine * machine) {
diff --git a/src/osd/modules/sound/js_sound.js b/src/osd/modules/sound/js_sound.js
index b06cbb4..9075601 100644
--- a/src/osd/modules/sound/js_sound.js
+++ b/src/osd/modules/sound/js_sound.js
@@ -185,18 +185,18 @@ function get_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;
+ //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 {
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment