foxygit / fake-08-xbox360 Log in
commit 2d46326fc808f387f99d79c0a2573df36fe7979f
Author:     Jon Bell <j.to.the.bell@gmail.com>
AuthorDate: Mon Dec 29 17:40:54 2025 -0700
Commit:     Jon Bell <j.to.the.bell@gmail.com>
CommitDate: Mon Dec 29 17:40:54 2025 -0700

    Port over audio updates from zepto8
---
 platform/SDL2Desktop/Makefile |   34 +-
 source/Audio.cpp              | 1197 +++++++++++++++++++++++++++--------------
 source/Audio.h                |   12 +-
 source/PicoRam.h              |   80 +--
 source/cart.cpp               |    4 +-
 source/filter.cpp             |  100 ++++
 source/filter.h               |   44 ++
 source/synth.cpp              |  140 +++--
 source/synth.h                |   30 +-
 test/audiotests.cpp           |  223 +-------
 test/carttests.cpp            |    4 +-
 test/vmtests.cpp              |    2 +-
 12 files changed, 1138 insertions(+), 732 deletions(-)

diff --git a/platform/SDL2Desktop/Makefile b/platform/SDL2Desktop/Makefile
index 13892b0..8af8396 100644
--- a/platform/SDL2Desktop/Makefile
+++ b/platform/SDL2Desktop/Makefile
@@ -17,6 +17,7 @@ INCLUDES	:=	${INCLUDES}
 CC = $(CXX)

 CFLAGS	:=	-g -Wall -Wno-deprecated -ffunction-sections -std=c++17 \
+			-MMD -MP \
 			$(DEFINES)

 CFLAGS	+=	$(INCLUDE) -DVER_STR=\"$(APP_VERSION)\"
@@ -24,9 +25,38 @@ CFLAGS	+=	$(INCLUDE) -DVER_STR=\"$(APP_VERSION)\"
 CXXFLAGS	:= $(CFLAGS) -fno-rtti -fno-exceptions
 #-std=gnu++11 was used before... not sure of difference

-LIBS	:= -lSDL2
+# SDL2 flags via pkg-config or sdl2-config with sensible fallbacks (Homebrew paths)
+SDL2_CFLAGS := $(shell pkg-config --cflags sdl2 2>/dev/null)
+SDL2_LIBS   := $(shell pkg-config --libs sdl2 2>/dev/null)

-LDFLAGS	:= $(LIBS)
+ifeq ($(strip $(SDL2_CFLAGS)),)
+SDL2_CFLAGS := $(shell sdl2-config --cflags 2>/dev/null)
+SDL2_LIBS   := $(shell sdl2-config --libs 2>/dev/null)
+endif
+
+ifeq ($(strip $(SDL2_CFLAGS)),)
+UNAME_S := $(shell uname -s)
+UNAME_M := $(shell uname -m)
+ifeq ($(UNAME_S),Darwin)
+ifeq ($(UNAME_M),arm64)
+# Add parent include dir so #include <SDL2/SDL.h> resolves
+SDL2_CFLAGS := -I/opt/homebrew/include
+SDL2_LIBS   := -L/opt/homebrew/lib -lSDL2
+else
+SDL2_CFLAGS := -I/usr/local/include
+SDL2_LIBS   := -L/usr/local/lib -lSDL2
+endif
+endif
+endif
+
+# Add include flags for SDL2 to both C and C++ compiles
+CFLAGS	+= $(SDL2_CFLAGS)
+CXXFLAGS += $(SDL2_CFLAGS)
+
+# Keep legacy LIBS but prefer SDL2_LIBS for correctness
+LIBS	?= -lSDL2
+
+LDFLAGS	:= $(LIBS) $(SDL2_LIBS)


 #---------------------------------------------------------------------------------
diff --git a/source/Audio.cpp b/source/Audio.cpp
index f1c5508..8d1c0fb 100644
--- a/source/Audio.cpp
+++ b/source/Audio.cpp
@@ -1,18 +1,18 @@
 #include "Audio.h"
 #include "synth.h"
+#include "filter.h"
 #include "hostVmShared.h"
 #include "mathhelpers.h"

 #include <cstdint>
 #include <string>
 #include <sstream>
-#include <algorithm> // std::max
+#include <algorithm>
 #include <cmath>
-#include <float.h> // std::max
+#include <float.h>
+#include <cassert>

-
-
-//playback implemenation based on zetpo 8's
+//playback implementation based on zepto8's
 //https://github.com/samhocevar/zepto8/blob/master/src/pico8/sfx.cpp

 Audio::Audio(PicoRam* memory){
@@ -22,23 +22,41 @@ Audio::Audio(PicoRam* memory){
 }

 void Audio::resetAudioState() {
+    _audioState._musicChannel.count = -1;
+    _audioState._musicChannel.pattern = -1;
+    _audioState._musicChannel.mask = 0;
+    _audioState._musicChannel.volume_music = 0.5f;
+    _audioState._musicChannel.volume_sfx = 0.5f;
+    _audioState._musicChannel.fade_volume = 0.f;
+    _audioState._musicChannel.fade_volume_step = 0.f;
+    _audioState._musicChannel.offset = -1;
+    _audioState._musicChannel.length = 0;
+
     for(int i = 0; i < 4; i++) {
-        _audioState._sfxChannels[i].sfxId = -1;
-        _audioState._sfxChannels[i].offset = 0;
-        _audioState._sfxChannels[i].current_note.phi = 0;
+        _audioState._sfxChannels[i].main_sfx.sfx = -1;
+        _audioState._sfxChannels[i].main_sfx.offset = 0;
+        _audioState._sfxChannels[i].main_sfx.time = 0;
+        _audioState._sfxChannels[i].main_sfx.prev_key = 24;
+        _audioState._sfxChannels[i].main_sfx.prev_vol = 0;
+
+        _audioState._sfxChannels[i].custom_sfx.sfx = -1;
+        _audioState._sfxChannels[i].sfx_music = -1;
+        _audioState._sfxChannels[i].length = 0;
         _audioState._sfxChannels[i].can_loop = true;
         _audioState._sfxChannels[i].is_music = false;
-        _audioState._sfxChannels[i].prev_note.n.setKey(0);
-        _audioState._sfxChannels[i].prev_note.n.setVolume(0);
+        _audioState._sfxChannels[i].fade = 0.0f;
+        _audioState._sfxChannels[i].last_main_instrument = 0;
+        _audioState._sfxChannels[i].last_main_key = 0;
+        _audioState._sfxChannels[i].reverb_index = 0;
+
+        // Reset reverb buffers
+        std::memset(_audioState._sfxChannels[i].reverb_2, 0, sizeof(_audioState._sfxChannels[i].reverb_2));
+        std::memset(_audioState._sfxChannels[i].reverb_4, 0, sizeof(_audioState._sfxChannels[i].reverb_4));
+
+        // Reset damp filters
+        _audioState._sfxChannels[i].damp1 = z8::filter(z8::filter::type::highshelf, 2400.0f, 1.0f, -6.0f);
+        _audioState._sfxChannels[i].damp2 = z8::filter(z8::filter::type::highshelf, 1000.0f, 1.0f, -12.0f);
     }
-    _audioState._musicChannel.count = 0;
-    _audioState._musicChannel.pattern = -1;
-    _audioState._musicChannel.master = -1;
-    _audioState._musicChannel.mask = 0xf;
-    _audioState._musicChannel.speed = 0;
-    _audioState._musicChannel.volume = 0.f;
-    _audioState._musicChannel.volume_step = 0.f;
-    _audioState._musicChannel.offset = 0.f;
 }

 audioState_t* Audio::getAudioState() {
@@ -46,26 +64,18 @@ audioState_t* Audio::getAudioState() {
 }

 int Audio::api_sfx(int sfx, int channel, int offset, int length){
-    //TODO: handle length
-    //match pico 8 behavior
-    if (sfx < -2) {
-        sfx = 0;
-    }
-    if (length < 0) {
-        length = 31;
-    }
+    // SFX index: valid values are 0..63 for actual samples,
+    // -1 to stop sound on a channel, -2 to stop looping on a channel
+    // Audio channel: valid values are 0..3, -1 (autoselect), or -2 (stop sfx on any channel)

-    //pico 8 returns nil in some of these cases, but I think I need to handle that
-    // in the lua api
-    if (sfx > 63 || channel < -2 || channel > 3 || offset > 31 || length > 31) {
+    if (sfx < -2 || sfx > 63 || channel < -2 || channel > 4 || offset > 31)
         return 0;
-    }

-    //CHANNEL -2: to stop the given sound from playing on any channel
+    // CHANNEL -2: to stop the given sound from playing on any channel
     if (channel == -2) {
-        for(int i = 0; i < 4; i++) {
-            if (_audioState._sfxChannels[i].sfxId == sfx) {
-                _audioState._sfxChannels[i].sfxId = -1;
+        for (int i = 0; i < 4; ++i) {
+            if (_audioState._sfxChannels[i].main_sfx.sfx == sfx) {
+                _audioState._sfxChannels[i].main_sfx.sfx = -1;
             }
         }
         return 0;
@@ -73,102 +83,177 @@ int Audio::api_sfx(int sfx, int channel, int offset, int length){

     if (sfx == -1)
     {
-        // Stop playing the current channel
-        if (channel != -1) {
-            _audioState._sfxChannels[channel].sfxId = -1;
+        // Stop playing if sfx is a non musical channel
+        if (channel != -1)
+        {
+            if (!_audioState._sfxChannels[channel].is_music)
+                _audioState._sfxChannels[channel].main_sfx.sfx = -1;
         }
+        else
+        {
+            // stop playing all non musical channels
+            for (int i = 0; i < 4; ++i)
+            {
+                if (!_audioState._sfxChannels[i].is_music)
+                    _audioState._sfxChannels[i].main_sfx.sfx = -1;
+            }
+        }
+        return 0;
     }
-    else if (sfx == -2)
+
+    if (sfx == -2)
     {
-        // Stop looping the current channel
-        if (channel != -1) {
-            _audioState._sfxChannels[channel].can_loop = false;
+        // Stop looping if sfx is a non musical channel
+        if (channel != -1)
+        {
+            if (!_audioState._sfxChannels[channel].is_music)
+                _audioState._sfxChannels[channel].can_loop = false;
         }
+        else
+        {
+            // stop looping all non musical channels
+            for (int i = 0; i < 4; ++i)
+            {
+                if (!_audioState._sfxChannels[i].is_music)
+                    _audioState._sfxChannels[i].can_loop = false;
+            }
+        }
+        return 0;
     }
-    else
+
+    // Find the first available channel: either a channel that plays
+    // nothing, or a channel that is already playing this sample (in
+    // this case PICO-8 decides to forcibly reuse that channel, which
+    // is reasonable)
+    if (channel == -1)
     {
-        // Find the first available channel: either a channel that plays
-        // nothing, or a channel that is already playing this sample (in
-        // this case PICO-8 decides to forcibly reuse that channel, which
-        // is reasonable)
-        if (channel == -1)
+        for (int i = 0; i < 4; ++i)
         {
-            for (int i = 0; i < 4; ++i)
-                if (_audioState._sfxChannels[i].sfxId == -1 ||
-                    _audioState._sfxChannels[i].sfxId == sfx)
-                {
-                    channel = i;
-                    break;
-                }
+            if (((1 << i) & _audioState._musicChannel.mask) != 0)
+                continue;
+
+            if (_audioState._sfxChannels[i].main_sfx.sfx == -1 ||
+                _audioState._sfxChannels[i].main_sfx.sfx == sfx)
+            {
+                channel = i;
+                break;
+            }
         }
+    }

-        // If still no channel found, the PICO-8 strategy seems to be to
-        // stop the sample with the lowest ID currently playing
-        if (channel == -1)
+    // if no free channel is found, stop music's first interruptable channel
+    if (channel == -1)
+    {
+        for (int i = 0; i < 4; ++i)
         {
-            for (int i = 0; i < 4; ++i) {
-               if (channel == -1 || _audioState._sfxChannels[i].sfxId < _audioState._sfxChannels[channel].sfxId) {
-                   channel = i;
-               }
+            if (((1 << i) & _audioState._musicChannel.mask) != 0)
+                continue;
+
+            if (_audioState._sfxChannels[i].is_music)
+            {
+                channel = i;
+                break;
             }
         }
+    }

-        // Stop any channel playing the same sfx
-        for (int i = 0; i < 4; ++i) {
-            if (_audioState._sfxChannels[i].sfxId == sfx) {
-                _audioState._sfxChannels[i].sfxId = -1;
+    // If still no channel found, the PICO-8 strategy seems to be to
+    // stop the channel with fastest speed (if there are several, take the latest one)
+    if (channel == -1)
+    {
+        uint8_t fastest_speed = 255;
+        for (int i = 0; i < 4; ++i)
+        {
+            if (((1 << i) & _audioState._musicChannel.mask) != 0)
+                continue;
+
+            int const index = _audioState._sfxChannels[i].main_sfx.sfx;
+            if (index < 0 || index >= 64)
+                continue;
+
+            struct sfx const& sfx_data = _memory->sfx[index];
+            if (sfx_data.speed <= fastest_speed)
+            {
+                channel = i;
+                fastest_speed = sfx_data.speed;
             }
         }
+    }
+
+    // still no channel found, the sfx is ignored
+    if (channel == -1)
+        return 0;
+
+    // Stop any channel playing the same sfx
+    for (int i = 0; i < 4; ++i)
+        if (_audioState._sfxChannels[i].main_sfx.sfx == sfx)
+            _audioState._sfxChannels[i].main_sfx.sfx = -1;

-        // Play this sound!
-        _audioState._sfxChannels[channel].sfxId = sfx;
-        _audioState._sfxChannels[channel].offset = std::max(0.f, (float)offset);
-        _audioState._sfxChannels[channel].current_note.phi = 0.f;
-        _audioState._sfxChannels[channel].can_loop = true;
-        _audioState._sfxChannels[channel].is_music = false;
-        // Playing an instrument starting with the note C-2 and the
-        // slide effect causes no noticeable pitch variation in PICO-8,
-        // so I assume this is the default value for “previous key”.
-        _audioState._sfxChannels[channel].prev_note.n.setKey(24);
-        // There is no default value for “previous volume”.
-        _audioState._sfxChannels[channel].prev_note.n.setVolume(0);
+    // if there is already a music playing sfx, store it to be picked back up later before it's replaced
+    if (_audioState._sfxChannels[channel].main_sfx.sfx != -1 && _audioState._sfxChannels[channel].is_music)
+    {
+        _audioState._sfxChannels[channel].sfx_music = _audioState._sfxChannels[channel].main_sfx.sfx;
     }

+    // Play this sound!
+    launch_sfx(sfx, channel, (float)std::max(0, offset), (float)std::max(0, length), false);
+
     return channel;
 }

 void Audio::api_music(int pattern, int16_t fade_len, int16_t mask){
-    if (pattern < -1 || pattern > 63) {
+    // pattern: 0..63, -1 to stop music.
+    // fade_len: fade length in milliseconds (default 0)
+    // mask: reserved channels
+
+    if (pattern < -1 || pattern > 63)
         return;
-    }

     if (pattern == -1)
     {
         // Music will stop when fade out is finished
-        _audioState._musicChannel.volume_step = fade_len <= 0 ? -FLT_MAX
-                                  : -_audioState._musicChannel.volume * (1000.f / fade_len);
+        _audioState._musicChannel.fade_volume_step = fade_len <= 0 ? -FLT_MAX
+                                  : -_audioState._musicChannel.fade_volume * (1000.f / fade_len);
         return;
     }

+    // Initialise music state for the whole song
     _audioState._musicChannel.count = 0;
-    _audioState._musicChannel.mask = mask ? mask & 0xf : 0xf;
+    _audioState._musicChannel.mask = mask & 0xf;

-    _audioState._musicChannel.volume = 1.f;
-    _audioState._musicChannel.volume_step = 0.f;
+    _audioState._musicChannel.fade_volume = 1.f;
+    _audioState._musicChannel.fade_volume_step = 0.f;
     if (fade_len > 0)
     {
-        _audioState._musicChannel.volume = 0.f;
-        _audioState._musicChannel.volume_step = 1000.f / fade_len;
+        _audioState._musicChannel.fade_volume = 0.f;
+        _audioState._musicChannel.fade_volume_step = 1000.f / fade_len;
     }

     set_music_pattern(pattern);
 }

 void Audio::set_music_pattern(int pattern) {
-    _audioState._musicChannel.pattern = pattern;
-    _audioState._musicChannel.offset = 0;
+    using std::max, std::min;
+
+    // stop all previously playing music sounds
+    for (int n = 0; n < 4; ++n)
+        if (_audioState._sfxChannels[n].is_music)
+        {
+            _audioState._sfxChannels[n].main_sfx.sfx = -1;
+            _audioState._sfxChannels[n].sfx_music = -1;
+        }
+
+    if (pattern < 0 || pattern > 63)
+    {
+        _audioState._musicChannel.pattern = -1;
+        _audioState._musicChannel.count = -1;
+        _audioState._musicChannel.offset = -1;
+        _audioState._musicChannel.mask = 0;
+        _audioState._musicChannel.length = 0.0f;
+        return;
+    }

-    //array to access song's channels. may be better to have this part of the struct?
+    // Get song channels
     uint8_t channels[] = {
         _memory->songs[pattern].getSfx0(),
         _memory->songs[pattern].getSfx1(),
@@ -176,114 +261,87 @@ void Audio::set_music_pattern(int pattern) {
         _memory->songs[pattern].getSfx3(),
     };

-    uint16_t shortest = 32 * 255; // longest sfx possible
-    bool foundNonLooping = false;
-    // Find music speed; it’s the speed of the fastest sfx
-	// While we are looping through this, find the lowest *valid* sfx length
-    _audioState._musicChannel.master = -1;
-    _audioState._musicChannel.speed = 0;
-	_audioState._musicChannel.length = 32; //as far as i can tell, there is no way to make an sfx longer than 32.
+    // Find music duration
+    // if there is at least one non-looping channel:
+    // length of the first non-looping channel
+    // if not (all channels are looping):
+    // length of slowest channel (so it stops when all channels have reached at least 32 steps)
+
+    int16_t duration_looping = -1;
+    int16_t duration_no_loop = -1;
     for (int i = 0; i < 4; ++i)
     {
-        uint8_t n = channels[i];
-
+        int n = channels[i];
         if (n & 0x40)
             continue;
-	// we ignore loooping length if we have non-looping channel
-        auto &sfx = _memory->sfx[n & 0x3f];
-        bool looping = sfx.loopRangeStart < sfx.loopRangeEnd;
-	bool firstNonLooping = !looping && !foundNonLooping;
-	if (!looping) {
-		foundNonLooping=true;
-	}
-
-	uint8_t length = 32;
-	if(sfx.loopRangeStart != 0 && sfx.loopRangeEnd == 0)
-	{
-		length= sfx.loopRangeStart;
-	}
-	else if (sfx.loopRangeEnd > sfx.loopRangeStart) {
-		// length = sfx.loopRangeEnd;
-    // pico 8 pretends like it's length 32!
-	}
-
-	uint16_t timeLength = length * std::max(1, (int)sfx.speed);;
-
-        if ((!looping || !foundNonLooping) && (firstNonLooping || _audioState._musicChannel.master == -1 || shortest > timeLength))
+
+        auto &sfx_data = _memory->sfx[n & 0x3f];
+        bool has_loop = sfx_data.loopRangeEnd > 0 && sfx_data.loopRangeEnd > sfx_data.loopRangeStart;
+        if (has_loop)
+        {
+            int16_t sfx_duration = 32 * sfx_data.speed;
+            duration_looping = max(duration_looping, sfx_duration);
+        }
+        else
         {
-	    shortest = timeLength;
-            _audioState._musicChannel.master = i;
-            _audioState._musicChannel.speed = std::max(1, (int)sfx.speed);
-	    _audioState._musicChannel.length = length;
+            // take duration of first non_looping channel
+            int16_t end_time = 32;
+            if (sfx_data.loopRangeEnd == 0 && sfx_data.loopRangeStart > 0)
+            {
+                end_time = min<int16_t>(end_time, sfx_data.loopRangeStart);
+            }
+            duration_no_loop = end_time * sfx_data.speed;
+            break;
         }
     }
-
-
+
+    int16_t duration = duration_no_loop > 0 ? duration_no_loop : duration_looping;
+    if (duration <= 0)
+    {
+        // Default duration if no valid sfx found
+        duration = 32;
+    }
+
+    // Initialise music state for the current pattern
+    _audioState._musicChannel.pattern = pattern;
+    _audioState._musicChannel.offset = 0;
+    _audioState._musicChannel.length = (float)duration;

     // Play music sfx on active channels
     for (int i = 0; i < 4; ++i)
     {
-        if (((1 << i) & _audioState._musicChannel.mask) == 0)
+        int n = channels[i];
+        if (n & 0x40)
             continue;

-        uint8_t n = channels[i];
-        if (n & 0x40) {
-            // Make sure this channel will be silent
-            _audioState._sfxChannels[i].sfxId = -1;
-            continue;
+        if (_audioState._sfxChannels[i].main_sfx.sfx == -1)
+        {
+            launch_sfx(n, i, 0, 0, true);
         }
-
-        _audioState._sfxChannels[i].sfxId = n;
-        _audioState._sfxChannels[i].offset = 0.f;
-        _audioState._sfxChannels[i].current_note.phi = 0.f;
-	// if the master channel loops we'll never finish
-        _audioState._sfxChannels[i].can_loop = i != _audioState._musicChannel.master;
-        _audioState._sfxChannels[i].is_music = true;
-        _audioState._sfxChannels[i].prev_note.n.setKey(24);
-        _audioState._sfxChannels[i].prev_note.n.setVolume(0);
-    }
-}
-
-void Audio::FillAudioBuffer(void *audioBuffer, size_t offset, size_t size){
-    if (audioBuffer == nullptr) {
-        return;
-    }
-
-    uint32_t *buffer = (uint32_t *)audioBuffer;
-
-    for (size_t i = 0; i < size; ++i){
-        int32_t sample = 0;
-
-        for (int c = 0; c < 4; ++c) {
-            sample += this->getSampleForChannel(c);
+        else
+        {
+            // if there is already a sfx playing, we store the music one to be played later, when the current sfx stop
+            _audioState._sfxChannels[i].sfx_music = n;
         }
-
-	    if (sample > 0x7fff) sample = 0x7fff; else if (sample < -0x8000) sample = -0x8000;
-
-        //buffer is stereo, so just send the mono sample to both channels
-        buffer[i] = (sample<<16) | (sample & 0xffff);
     }
 }

-
-void Audio::FillMonoAudioBuffer(void *audioBuffer, size_t offset, size_t size){
-    if (audioBuffer == nullptr) {
-        return;
-    }
-
-    int16_t *buffer = (int16_t *)audioBuffer;
-
-    for (size_t i = 0; i < size; ++i){
-        int32_t sample = 0;
-
-        for (int c = 0; c < 4; ++c) {
-            sample += this->getSampleForChannel(c);
-        }
-
-	    if (sample > 0x7fff) sample = 0x7fff; else if (sample < -0x8000) sample = -0x8000;
-
-        buffer[i] = sample;
-    }
+void Audio::launch_sfx(int16_t sfx, int16_t chan, float offset, float length, bool is_music)
+{
+    _audioState._sfxChannels[chan].main_sfx.sfx = sfx;
+    _audioState._sfxChannels[chan].main_sfx.offset = std::max(0.f, offset);
+    _audioState._sfxChannels[chan].main_sfx.time = 0.f;
+    _audioState._sfxChannels[chan].length = std::max(0.f, length);
+    _audioState._sfxChannels[chan].can_loop = true;
+    _audioState._sfxChannels[chan].is_music = is_music;
+    _audioState._sfxChannels[chan].last_main_instrument = 0xff;
+    _audioState._sfxChannels[chan].last_main_key = 0xff;
+    // Playing an instrument starting with the note C-2 and the
+    // slide effect causes no noticeable pitch variation in PICO-8,
+    // so I assume this is the default value for "previous key".
+    _audioState._sfxChannels[chan].main_sfx.prev_key = 24;
+    // There is no default value for "previous volume".
+    _audioState._sfxChannels[chan].main_sfx.prev_vol = 0.f;
 }

 static float key_to_freq(float key)
@@ -292,16 +350,14 @@ static float key_to_freq(float key)
     return 440.f * exp2((key - 33.f) / 12.f);
 }

-const float C2_FREQ = key_to_freq(24);
-
 int16_t Audio::getCurrentSfxId(int channel){
-    return _audioState._sfxChannels[channel].sfxId;
+    return _audioState._sfxChannels[channel].main_sfx.sfx;
 }

 int Audio::getCurrentNoteNumber(int channel){
-    return _audioState._sfxChannels[channel].sfxId < 0
+    return _audioState._sfxChannels[channel].main_sfx.sfx < 0
         ? -1
-        : _audioState._sfxChannels[channel].offset;
+        : (int)_audioState._sfxChannels[channel].main_sfx.offset;
 }

 int16_t Audio::getCurrentMusic(){
@@ -313,266 +369,615 @@ int16_t Audio::getMusicPatternCount(){
 }

 int16_t Audio::getMusicTickCount(){
-    return _audioState._musicChannel.offset * _audioState._musicChannel.speed;
+    return (int16_t)_audioState._musicChannel.offset;
 }

-float Audio::getSampleForSfx(rawSfxChannel &channel, float freqShift) {
-    using std::max;
-    int const samples_per_second = 22050;
+void Audio::update_sfx_state(sfx_state& cur_sfx, z8::synth_param& new_synth,
+                              float freq_factor, float length, bool is_music,
+                              bool can_loop, bool half_rate, double inv_frames_per_second)
+{
+    using std::fabs, std::fmod, std::floor, std::max;

-    if (channel.sfxId < 0 || channel.sfxId > 63) {
-        //no (valid) sfx here. return silence
-        return 0;
-    }
-    struct sfx const &sfx = _memory->sfx[channel.sfxId];
+    if (cur_sfx.sfx == -1) return;
+
+    int const index = cur_sfx.sfx;
+    assert(index >= 0 && index < 64);
+    struct sfx const& sfx_data = _memory->sfx[index];

     // Speed must be 1—255 otherwise the SFX is invalid
-    int const speed = max(1, (int)sfx.speed);
+    int const speed = max(1, (int)sfx_data.speed);
+
+    double const offset = cur_sfx.offset;
+    double const time = cur_sfx.time;

     // PICO-8 exports instruments as 22050 Hz WAV files with 183 samples
     // per speed unit per note, so this is how much we should advance
-    float const offset_per_second = 22050.f / (183.f * speed);
-    float const offset_per_sample = offset_per_second / samples_per_second;
-    float next_offset = channel.offset + offset_per_sample;
-
-    // Handle SFX loops. From the documentation: “Looping is turned
-    // off when the start index >= end index”.
-    float const loop_range = float(sfx.loopRangeEnd - sfx.loopRangeStart);
-    if (loop_range > 0.f && next_offset >= sfx.loopRangeStart && channel.can_loop) {
-        next_offset = fmod(next_offset - sfx.loopRangeStart, loop_range)
-                    + sfx.loopRangeStart;
+    double const offset_per_second = 22050.0 / (183.0 * speed);
+    double const offset_per_frame = offset_per_second * inv_frames_per_second;
+    double next_offset = offset + offset_per_frame;
+    double next_time = time + offset_per_frame;
+
+    // Handle SFX loops. From the documentation: "Looping is turned
+    // off when the start index >= end index".
+    float const loop_range = float(sfx_data.loopRangeEnd - sfx_data.loopRangeStart);
+    if (loop_range > 0.f && next_offset >= sfx_data.loopRangeEnd && can_loop)
+    {
+        next_offset = fmod(next_offset - sfx_data.loopRangeStart, loop_range)
+            + sfx_data.loopRangeStart;
     }

-    int const note_idx = (int)floor(channel.offset);
-    channel.current_note.n=sfx.notes[note_idx];
-    int const next_note_idx = (int)floor(next_offset);
+    bool has_end = false;
+    float end_time = 32.f;
+    if (length > 0.0f)
+    {
+        has_end = true;
+        end_time = length;
+    }
+    // in pico 8, strangely, len is not applied to musical sfx except for pattern len calculation
+    // it's probably a bug
+    if (!is_music && sfx_data.loopRangeEnd == 0 && sfx_data.loopRangeStart > 0)
+    {
+        has_end = true;
+        end_time = std::min<float>(end_time, sfx_data.loopRangeStart);
+    }
+    // if there is no loop, we end after the length
+    if (loop_range <= 0.f)
+    {
+        has_end = true;
+        // if not a music sfx, check where is the last note to early stop
+        if (!is_music)
+        {
+            int last_note = 0;
+            for (int n = 0; n < 32; ++n)
+            {
+                if (sfx_data.notes[n].getVolume() > 0)
+                {
+                    last_note = std::min(32, n + 1);
+                }
+            }
+            end_time = std::min(end_time, float(last_note));
+        }
+    }

+    if (offset < 32)
+    {
+        int const note_id = (int)floor(offset);
+        int const next_note_id = (int)floor(next_offset);

+        uint8_t key = sfx_data.notes[note_id].getKey();
+        float volume = sfx_data.notes[note_id].getVolume() / 7.f;
+        float freq = key_to_freq(key) * freq_factor;

-    /*
-    if (volume == 0.f){
-        //volume all the way off. return silence, but make sure to set stuff
-        channel.offset = next_offset;
+        if (volume > 0.f)
+        {
+            int const fx = sfx_data.notes[note_id].getEffect();

-        if (next_offset >= 32.f){
-            channel.sfxId = -1;
-            if (channel.getChildChannel()) {
-              channel.getChildChannel()->sfxId = -1;
+            // Apply effect, if any
+            switch (fx)
+            {
+            case FX_NO_EFFECT:
+                break;
+            case FX_SLIDE:
+            {
+                float t = (float)fmod(offset, 1.0);
+                // From the documentation: "Slide to the next note and volume",
+                // but it's actually _from_ the _prev_ note and volume.
+                freq = lerp(key_to_freq((float)cur_sfx.prev_key), freq, t);
+                if (cur_sfx.prev_vol > 0.f)
+                    volume = lerp(cur_sfx.prev_vol, volume, t);
+                break;
             }
-        }
-        else if (next_note_idx != note_idx){
-            channel.prev_note = sfx.notes[note_idx];
+            case FX_VIBRATO:
+            {
+                // 7.5f and 0.25f were found empirically by matching
+                // frequency graphs of PICO-8 instruments.
+                float t = (float)(fabs(fmod(7.5 * offset / offset_per_second, 1.0)) - 0.5) - 0.25f;
+                // Vibrato half a semi-tone, so multiply by pow(2,1/12)
+                freq = lerp(freq, freq * 1.059463094359f, t);
+                break;
+            }
+            case FX_DROP:
+                freq *= 1.f - (float)fmod(offset, 1.0);
+                break;
+            case FX_FADE_IN:
+                volume *= (float)fmod(offset, 1.0);
+                break;
+            case FX_FADE_OUT:
+                volume *= 1.f - (float)fmod(offset, 1.0);
+                break;
+            case FX_ARP_FAST:
+            case FX_ARP_SLOW:
+            {
+                // From the documentation:
+                // "6 arpeggio fast  //  Iterate over groups of 4 notes at speed of 4
+                //  7 arpeggio slow  //  Iterate over groups of 4 notes at speed of 8"
+                // "If the SFX speed is <= 8, arpeggio speeds are halved to 2, 4"
+                int const m = (speed <= 8 ? 32 : 16) / (fx == FX_ARP_FAST ? 4 : 8);
+                int const n = (int)(m * 7.5 * offset / offset_per_second);
+                int const arp_note = (note_id & ~3) | (n & 3);
+                freq = key_to_freq(sfx_data.notes[arp_note].getKey());
+                break;
+            }
+            }
+
+            if (half_rate) freq *= 0.5f;
+
+            new_synth.key = key;
+            new_synth.freq = freq;
+            new_synth.instrument = sfx_data.notes[note_id].getWaveform();
+            new_synth.custom = sfx_data.notes[note_id].getCustom();
+            new_synth.filters = sfx_data.filters;
+            new_synth.volume = volume;
+            new_synth.is_music = is_music;
+
+            new_synth.phi = new_synth.phi + (float)(freq * inv_frames_per_second);
         }

-        return 0;
-    }
-    */
-
-    // tiniest fade in/out to fix popping
-    // the real version uses a crossfade it looks like
-    // 25 samples was estimated from looking at pcm out from pico-8
-    float const fade_duration = offset_per_sample * 25;
-    float offset_part = fmod(channel.offset, 1.f);
-    float crossfade = 0;
-    if (offset_part < fade_duration) {
-      crossfade = (fade_duration-offset_part)/fade_duration;
+        if (next_note_id != note_id)
+        {
+            cur_sfx.prev_key = sfx_data.notes[note_id].getKey();
+            cur_sfx.prev_vol = sfx_data.notes[note_id].getVolume() / 7.f;
+        }
     }
-

-    bool custom = (bool) sfx.notes[note_idx].getCustom() && channel.getChildChannel() != NULL;
-    // it seems we're not allowed to play custom instruments
-    // recursively inside a custom instrument.
-    float waveform = this->getSampleForNote(channel.current_note, channel, channel.getChildChannel(), channel.prev_note.n, freqShift, false);
-    if (crossfade > 0) {
-      waveform *= (1.0f-crossfade);
-      note dummyNote;
-      waveform+= crossfade * this->getSampleForNote(channel.prev_note, channel, channel.getPrevChildChannel(), dummyNote, freqShift, true);
+    cur_sfx.offset = next_offset;
+    cur_sfx.time = next_time;
+
+    if (has_end && next_time >= end_time)
+    {
+        cur_sfx.sfx = -1;
     }
-    uint8_t len = sfx.loopRangeEnd == 0 ? 32 : sfx.loopRangeEnd;
-    bool lastNote = note_idx == len - 1;
-    if (lastNote && 1.0f - offset_part < fade_duration) {
-      waveform *= (fade_duration - 1.0f + offset_part)/fade_duration;
+}
+
+float Audio::get_synth_sample(z8::synth_param& params)
+{
+    // Play note
+    float waveform = z8::synth::waveform(params);
+
+    uint8_t detune = (params.filters / 8) % 3;
+    if (detune != 0 && params.instrument != z8::synth::INST_NOISE)
+    {
+        // detune is a second wave slightly offset
+        float factor = 1.0f;
+        if (params.instrument == z8::synth::INST_TRIANGLE)
+            factor = (detune == 1) ? 3.0f / 4.0f : 3.0f / 2.0f; // triangle detune adds a fourth or a fifth
+        else if (params.instrument == z8::synth::INST_ORGAN)
+            factor = (detune == 1) ? 200.0f / 199.0f : 800.0f / 199.0f; // slight offset, detune 2 at 2 octave above
+        else if (params.instrument == z8::synth::INST_PHASER)
+            factor = (detune == 1) ? 49.0f / 50.0f : 400.0f / 199.0f;
+        else
+            factor = (detune == 1) ? 200.0f / 199.0f : 400.0f / 199.0f; // others are slight offset, detune 2 at 1 octave above
+
+        z8::synth_param second_wave = params;
+        second_wave.phi *= factor;
+        if (detune == 2 && params.instrument == z8::synth::INST_ORGAN)
+            second_wave.instrument = z8::synth::INST_TRIANGLE; // organ second wave seems to be simpler
+        waveform += z8::synth::waveform(second_wave) * 0.5f;
     }

+    float volume = params.volume;
+
     // Apply master music volume from fade in/out
-    // FIXME: check whether this should be done after distortion
-    if (channel.is_music) {
-        waveform *= _audioState._musicChannel.volume;
+    if (params.is_music)
+    {
+        volume *= _audioState._musicChannel.fade_volume * _audioState._musicChannel.volume_music;
+    }
+    else
+    {
+        volume *= _audioState._musicChannel.volume_sfx;
     }

-    channel.offset = next_offset;
+    return std::clamp(waveform * volume, -1.0f, 1.0f);
+}

-    if (next_offset >= 32.f){
-        channel.sfxId = -1;
-        if (custom) {
-          channel.getChildChannel()->sfxId = -1;
-        }
+void Audio::FillAudioBuffer(void *audioBuffer, size_t offset, size_t size){
+    if (audioBuffer == nullptr) {
+        return;
     }
-    else if (next_note_idx != note_idx){
-        channel.prev_note = channel.current_note; //sfx.notes[note_idx].getKey();
-        channel.current_note.n = sfx.notes[next_note_idx];
-        channel.current_note.phi = channel.prev_note.phi;
-        if (custom) {
-            if (!sfx.notes[next_note_idx].getCustom() ||
-                sfx.notes[next_note_idx].getKey() != sfx.notes[note_idx].getKey() ||
-                sfx.notes[next_note_idx].getWaveform() != sfx.notes[note_idx].getWaveform()
-              ) {
-                channel.rotateChannels();
-                channel.getChildChannel()->sfxId = -1;
+
+    uint32_t *buffer = (uint32_t *)audioBuffer;
+
+    for (size_t i = 0; i < size; ++i){
+        int32_t sample = 0;
+        float channel_mix = 0.0f;
+
+        bool is_pause = _memory->drawState.soundPauseState == 1;
+
+        for (int chan = 0; chan < 4; ++chan) {
+            double inv_frames_per_second = ((_memory->hwState.half_rate & (1 << chan)) ? 0.5 : 1.0) / 22050.0;
+
+            sfxChannel& channel_state = _audioState._sfxChannels[chan];
+
+            // Advance music using the first channel
+            if (chan == 0 && _audioState._musicChannel.pattern != -1 && !is_pause)
+            {
+                double const offset_per_second = 22050.0 / 183.0;
+                double const offset_per_frame = offset_per_second * inv_frames_per_second;
+                _audioState._musicChannel.offset += offset_per_frame;
+                _audioState._musicChannel.fade_volume += (float)(_audioState._musicChannel.fade_volume_step * inv_frames_per_second);
+                _audioState._musicChannel.fade_volume = clamp(_audioState._musicChannel.fade_volume, 0.f, 1.f);
+
+                if (_audioState._musicChannel.fade_volume_step < 0 && _audioState._musicChannel.fade_volume <= 0)
+                {
+                    set_music_pattern(-1);
+                }
+                else if (_audioState._musicChannel.offset >= _audioState._musicChannel.length)
+                {
+                    int16_t next_pattern = _audioState._musicChannel.pattern + 1;
+                    int16_t next_count = _audioState._musicChannel.count + 1;
+                    if (_memory->songs[_audioState._musicChannel.pattern].getStop())
+                    {
+                        next_pattern = -1;
+                        next_count = -1;
+                    }
+                    else if (_memory->songs[_audioState._musicChannel.pattern].getLoop())
+                        while (--next_pattern > 0 && !_memory->songs[next_pattern].getStart())
+                            ;
+
+                    _audioState._musicChannel.count = next_count;
+                    set_music_pattern(next_pattern);
+                }
             }
-        }
-    }
-    return waveform;

-}
+            // if no sfx is playing and there is a music sfx stored
+            if (channel_state.main_sfx.sfx == -1 && channel_state.sfx_music != -1 && !is_pause)
+            {
+                int const index = channel_state.sfx_music;
+                assert(index >= 0 && index < 64);
+                struct sfx const& sfx_data = _memory->sfx[index];

-float Audio::getSampleForNote(noteChannel &channel, rawSfxChannel &parentChannel, rawSfxChannel *childChannel, note prev_note, float freqShift, bool forceRemainder) {
-    using std::max;
-    float offset = parentChannel.offset;
-    int const samples_per_second = 22050;
-    //TODO: apply effects
-    int const fx = channel.n.getEffect();
-    uint8_t key = channel.n.getKey();
-    float volume = channel.n.getVolume() / 7.f;
-    float freq = key_to_freq(key);
+                // compute offset to start the sfx to
+                bool want_play = true;
+                int const speed = std::max(1, (int)sfx_data.speed);
+                double new_offset = _audioState._musicChannel.offset / speed;

-    struct sfx const &sfx = _memory->sfx[parentChannel.sfxId];
+                float const loop_range = (float)(sfx_data.loopRangeEnd - sfx_data.loopRangeStart);
+                if (loop_range > 0.f && channel_state.can_loop)
+                {
+                    if (new_offset > sfx_data.loopRangeStart)
+                        new_offset = std::fmod(new_offset - sfx_data.loopRangeStart, loop_range) + sfx_data.loopRangeStart;
+                }
+                else
+                {
+                    if (new_offset > 32.0)
+                        want_play = false;
+                }

-    // Speed must be 1—255 otherwise the SFX is invalid
-    int const speed = max(1, (int)sfx.speed);
-    float const offset_per_second = 22050.f / (183.f * speed);
-    int const note_idx = (int)floor(offset);
-
-    // previous note effectively goes beyond offset fmod 1 when in crossfade
-    float tmod= 0;
-    if (forceRemainder) tmod = 1.0f;
-    tmod += fmod(offset, 1.f);
-    // Apply effect, if any
-    switch (fx)
-    {
-        case FX_NO_EFFECT:
-            break;
-        case FX_SLIDE:
-        {
-            // From the documentation: “Slide to the next note and volume”,
-            // but it’s actually _from_ the _prev_ note and volume.
-            freq = lerp(key_to_freq(prev_note.getKey()), freq, tmod);
-            if (prev_note.getVolume() > 0)
-                volume = lerp(prev_note.getVolume() / 7.0f, volume, tmod);
-            break;
-        }
-        case FX_VIBRATO:
-        {
-            // 7.5f and 0.25f were found empirically by matching
-            // frequency graphs of PICO-8 instruments.
-            float t = fabs(fmod(7.5f * tmod / offset_per_second, 1.0f) - 0.5f) - 0.25f;
-            // Vibrato half a semi-tone, so multiply by pow(2,1/12)
-            freq = lerp(freq, freq * 1.059463094359f, t);
-            break;
-        }
-        case FX_DROP:
-            freq *= 1.f - fmod(offset, 1.f);
-            break;
-        case FX_FADE_IN:
-            volume *= std::min(1.f, tmod);
-            break;
-        case FX_FADE_OUT:
-            volume *= max(0.0f, 1.f - tmod);
-            break;
-        case FX_ARP_FAST:
-        case FX_ARP_SLOW:
-        {
-            // From the documentation:
-            // “6 arpeggio fast  //  Iterate over groups of 4 notes at speed of 4
-            //  7 arpeggio slow  //  Iterate over groups of 4 notes at speed of 8”
-            // “If the SFX speed is <= 8, arpeggio speeds are halved to 2, 4”
-            int const m = (speed <= 8 ? 32 : 16) / (fx == FX_ARP_FAST ? 4 : 8);
-            int const n = (int)(m * 7.5f * offset / offset_per_second);
-            int const arp_note = (note_idx & ~3) | (n & 3);
-            freq = key_to_freq(sfx.notes[arp_note].getKey());
-            break;
+                if (want_play)
+                {
+                    launch_sfx(index, chan, (float)new_offset, 0, true);
+                }
+                channel_state.sfx_music = -1;
+            }
+
+            z8::synth_param& last_synth = channel_state.last_synth;
+            z8::synth_param new_synth;
+            new_synth.phi = last_synth.phi;
+            new_synth.last_advance = last_synth.last_advance;
+            new_synth.last_sample = last_synth.last_sample;
+            float value = 0.0f;
+
+            if (!is_pause)
+            {
+                double main_sfx_base_offset = channel_state.main_sfx.offset;
+                bool half_rate = _memory->hwState.half_rate & (1 << (chan + 4));
+                // update main sfx
+                update_sfx_state(channel_state.main_sfx, new_synth, 1.0f, channel_state.length,
+                                channel_state.is_music, channel_state.can_loop, half_rate, inv_frames_per_second);
+
+                bool restart_custom = new_synth.instrument != channel_state.last_main_instrument ||
+                                      new_synth.key != channel_state.last_main_key;
+                channel_state.last_main_instrument = new_synth.instrument;
+                channel_state.last_main_key = new_synth.key;
+
+                if (new_synth.volume > 0.0f)
+                {
+                    if (new_synth.custom)
+                    {
+                        // also need to restart if main_sfx loops (new offset is before base offset)
+                        if (channel_state.main_sfx.offset < main_sfx_base_offset) restart_custom = true;
+                        // also need to restart if custom_sfx.sfx == -1 (it has ended) and main_sfx.offset is changing integer
+                        if (channel_state.custom_sfx.sfx == -1 &&
+                            std::floor(main_sfx_base_offset) != std::floor(channel_state.main_sfx.offset))
+                            restart_custom = true;
+
+                        if (restart_custom)
+                        {
+                            channel_state.custom_sfx.sfx = new_synth.instrument;
+                            channel_state.custom_sfx.offset = 0.0;
+                            channel_state.custom_sfx.time = 0.0;
+                        }
+                        new_synth.phi = last_synth.phi;
+                        float const freq_base = key_to_freq(24); // C2
+                        float freq_factor = new_synth.freq / freq_base;
+                        float main_sfx_volume = new_synth.volume;
+                        update_sfx_state(channel_state.custom_sfx, new_synth, freq_factor, 0.0f, false, true, half_rate, inv_frames_per_second);
+                        new_synth.volume *= main_sfx_volume;
+                    }
+                    value = get_synth_sample(new_synth);
+                }
+            }
+
+            // detect harsh changes of states, and do a small fade
+            float freq_threshold = std::min(new_synth.freq, last_synth.freq) * 0.01f;
+            if (std::abs(new_synth.volume - last_synth.volume) > 0.1f
+                || std::abs(new_synth.freq - last_synth.freq) > freq_threshold
+                || new_synth.instrument != last_synth.instrument)
+            {
+                if (channel_state.fade <= 0.0f) // avoid continuous fades, it messes with noise algo
+                {
+                    channel_state.fade_synth = last_synth;
+                }
+                channel_state.fade = 1.0f;
+                // reset phi between notes so we don't get very big values that would lose precision
+                new_synth.phi = std::fmod(new_synth.phi, 1.0f);
+            }
+            last_synth = new_synth;
+
+            uint8_t reverb = (last_synth.filters / 24) % 3;
+            uint8_t dampen = (last_synth.filters / 72) % 3;
+            float chan_reverb1_value = reverb == 1 ? 1.0f : 0.0f;
+            float chan_reverb2_value = reverb == 2 ? 1.0f : 0.0f;
+            float chan_damp1_value = dampen == 1 ? 1.0f : 0.0f;
+            float chan_damp2_value = dampen == 2 ? 1.0f : 0.0f;
+
+            if (channel_state.fade > 0.0f)
+            {
+                channel_state.fade_synth.phi = channel_state.fade_synth.phi +
+                    (float)(channel_state.fade_synth.freq * inv_frames_per_second);
+                float value_fade = get_synth_sample(channel_state.fade_synth);
+
+                value = lerp(value, value_fade, channel_state.fade);
+
+                // Also mix fade filter values
+                uint8_t fade_reverb = (channel_state.fade_synth.filters / 24) % 3;
+                uint8_t fade_dampen = (channel_state.fade_synth.filters / 72) % 3;
+                chan_reverb1_value = lerp(chan_reverb1_value, fade_reverb == 1 ? 1.0f : 0.0f, channel_state.fade);
+                chan_reverb2_value = lerp(chan_reverb2_value, fade_reverb == 2 ? 1.0f : 0.0f, channel_state.fade);
+                chan_damp1_value = lerp(chan_damp1_value, fade_dampen == 1 ? 1.0f : 0.0f, channel_state.fade);
+                chan_damp2_value = lerp(chan_damp2_value, fade_dampen == 2 ? 1.0f : 0.0f, channel_state.fade);
+
+                channel_state.fade -= (float)(130.0 * inv_frames_per_second);
+            }
+
+            // hw can force fx passes
+            if (_memory->hwState.reverb & (1 << (chan + 4))) chan_reverb1_value = 1.0f;
+            if (_memory->hwState.reverb & (1 << chan)) chan_reverb2_value = 1.0f;
+            if (_memory->hwState.lowpass & (1 << (chan + 4))) chan_damp1_value = 1.0f;
+            if (_memory->hwState.lowpass & (1 << chan)) chan_damp2_value = 1.0f;
+
+            if (chan_reverb1_value > 0.0f)
+                value += chan_reverb1_value * channel_state.reverb_2[channel_state.reverb_index % 366] * 0.5f;
+            if (chan_reverb2_value > 0.0f)
+                value += chan_reverb2_value * channel_state.reverb_4[channel_state.reverb_index % 732] * 0.5f;
+
+            channel_state.reverb_2[channel_state.reverb_index % 366] = value;
+            channel_state.reverb_4[channel_state.reverb_index % 732] = value;
+            ++channel_state.reverb_index;
+
+            float value_damp1 = channel_state.damp1.run(value);
+            if (chan_damp1_value > 0.0f) value = lerp(value, value_damp1, chan_damp1_value);
+
+            float value_damp2 = channel_state.damp2.run(value);
+            if (chan_damp2_value > 0.0f) value = lerp(value, value_damp2, chan_damp2_value);
+
+            int16_t chan_sample = (int16_t)(32767.99f * std::clamp(value, -0.99f, 0.99f));
+
+            // Apply hardware distort
+            if (_memory->hwState.distort & (1 << chan))
+            {
+                chan_sample = chan_sample / 0x1000 * 0x1249;
+            }
+            else if (_memory->hwState.distort & (1 << (chan + 4)))
+            {
+                chan_sample = (chan_sample - (chan_sample < 0 ? 0x1000 : 0)) / 0x1000 * 0x1249;
+            }
+            channel_mix += chan_sample;
         }
+
+        sample = (int32_t)std::clamp(channel_mix, -32767.9f, 32767.9f);
+
+        //buffer is stereo, so just send the mono sample to both channels
+        buffer[i] = ((uint32_t)(uint16_t)sample << 16) | ((uint16_t)sample);
     }
-    freq*=freqShift;
-
-    bool custom = (bool) channel.n.getCustom() && childChannel != NULL;
-    float waveform;
-    if (custom) {
-      if (childChannel->sfxId == -1) {
-        // initialize child channel
-        childChannel->sfxId = channel.n.getWaveform();
-        childChannel->offset = 0;
-        childChannel->current_note.phi = 0;
-        childChannel->can_loop = true;
-        // don't want to double lower volume for music subchannel
-        childChannel->is_music = false;
-        childChannel->prev_note.n.setKey(0);
-        childChannel->prev_note.n.setVolume(0);
-      }
-      waveform = volume * this->getSampleForSfx(*childChannel, freq/C2_FREQ);
-    } else {
-      waveform = volume * z8::synth::waveform(channel.n.getWaveform(), channel.phi);
-    }
-    channel.phi = channel.phi + freq / samples_per_second;
-    return waveform;
 }


-//adapted from zepto8 sfx.cpp (wtfpl license)
-int16_t Audio::getSampleForChannel(int channel){
-    using std::fabs;
-    using std::fmod;
-    using std::floor;
-    using std::max;
+void Audio::FillMonoAudioBuffer(void *audioBuffer, size_t offset, size_t size){
+    if (audioBuffer == nullptr) {
+        return;
+    }

-    int const samples_per_second = 22050;
+    int16_t *buffer = (int16_t *)audioBuffer;

-    int16_t sample = 0;
+    for (size_t i = 0; i < size; ++i){
+        float channel_mix = 0.0f;

-    // Advance music using the master channel
-    if (channel == _audioState._musicChannel.master && _audioState._musicChannel.pattern != -1)
-    {
-        float const offset_per_second = 22050.f / (183.f * _audioState._musicChannel.speed);
-        float const offset_per_sample = offset_per_second / samples_per_second;
-        _audioState._musicChannel.offset += offset_per_sample;
-        _audioState._musicChannel.volume += _audioState._musicChannel.volume_step / samples_per_second;
-        _audioState._musicChannel.volume = clamp(_audioState._musicChannel.volume, 0.f, 1.f);
+        bool is_pause = _memory->drawState.soundPauseState == 1;

-        if (_audioState._musicChannel.volume_step < 0 && _audioState._musicChannel.volume <= 0)
-        {
-            // Fade out is finished, stop playing the current song
-            for (int i = 0; i < 4; ++i) {
-                if (_audioState._sfxChannels[i].is_music) {
-                    _audioState._sfxChannels[i].sfxId = -1;
+        for (int chan = 0; chan < 4; ++chan) {
+            double inv_frames_per_second = ((_memory->hwState.half_rate & (1 << chan)) ? 0.5 : 1.0) / 22050.0;
+
+            sfxChannel& channel_state = _audioState._sfxChannels[chan];
+
+            // Advance music using the first channel
+            if (chan == 0 && _audioState._musicChannel.pattern != -1 && !is_pause)
+            {
+                double const offset_per_second = 22050.0 / 183.0;
+                double const offset_per_frame = offset_per_second * inv_frames_per_second;
+                _audioState._musicChannel.offset += offset_per_frame;
+                _audioState._musicChannel.fade_volume += (float)(_audioState._musicChannel.fade_volume_step * inv_frames_per_second);
+                _audioState._musicChannel.fade_volume = clamp(_audioState._musicChannel.fade_volume, 0.f, 1.f);
+
+                if (_audioState._musicChannel.fade_volume_step < 0 && _audioState._musicChannel.fade_volume <= 0)
+                {
+                    set_music_pattern(-1);
+                }
+                else if (_audioState._musicChannel.offset >= _audioState._musicChannel.length)
+                {
+                    int16_t next_pattern = _audioState._musicChannel.pattern + 1;
+                    int16_t next_count = _audioState._musicChannel.count + 1;
+                    if (_memory->songs[_audioState._musicChannel.pattern].getStop())
+                    {
+                        next_pattern = -1;
+                        next_count = -1;
+                    }
+                    else if (_memory->songs[_audioState._musicChannel.pattern].getLoop())
+                        while (--next_pattern > 0 && !_memory->songs[next_pattern].getStart())
+                            ;
+
+                    _audioState._musicChannel.count = next_count;
+                    set_music_pattern(next_pattern);
                 }
             }
-            _audioState._musicChannel.pattern = -1;
-        }
-        else if (_audioState._musicChannel.offset >= _audioState._musicChannel.length)
-        {
-            int16_t next_pattern = _audioState._musicChannel.pattern + 1;
-            int16_t next_count = _audioState._musicChannel.count + 1;
-            //todo: pull out these flags, get memory storage correct as well
-            if (_memory->songs[_audioState._musicChannel.pattern].getStop()) //stop part of the loop flag
+
+            // if no sfx is playing and there is a music sfx stored
+            if (channel_state.main_sfx.sfx == -1 && channel_state.sfx_music != -1 && !is_pause)
             {
-                next_pattern = -1;
-                next_count = _audioState._musicChannel.count;
+                int const index = channel_state.sfx_music;
+                assert(index >= 0 && index < 64);
+                struct sfx const& sfx_data = _memory->sfx[index];
+
+                bool want_play = true;
+                int const speed = std::max(1, (int)sfx_data.speed);
+                double new_offset = _audioState._musicChannel.offset / speed;
+
+                float const loop_range = (float)(sfx_data.loopRangeEnd - sfx_data.loopRangeStart);
+                if (loop_range > 0.f && channel_state.can_loop)
+                {
+                    if (new_offset > sfx_data.loopRangeStart)
+                        new_offset = std::fmod(new_offset - sfx_data.loopRangeStart, loop_range) + sfx_data.loopRangeStart;
+                }
+                else
+                {
+                    if (new_offset > 32.0)
+                        want_play = false;
+                }
+
+                if (want_play)
+                {
+                    launch_sfx(index, chan, (float)new_offset, 0, true);
+                }
+                channel_state.sfx_music = -1;
             }
-            else if (_memory->songs[_audioState._musicChannel.pattern].getLoop()){
-                while (--next_pattern > 0 && !_memory->songs[next_pattern].getStart())
-                    ;
+
+            z8::synth_param& last_synth = channel_state.last_synth;
+            z8::synth_param new_synth;
+            new_synth.phi = last_synth.phi;
+            new_synth.last_advance = last_synth.last_advance;
+            new_synth.last_sample = last_synth.last_sample;
+            float value = 0.0f;
+
+            if (!is_pause)
+            {
+                double main_sfx_base_offset = channel_state.main_sfx.offset;
+                bool half_rate = _memory->hwState.half_rate & (1 << (chan + 4));
+                update_sfx_state(channel_state.main_sfx, new_synth, 1.0f, channel_state.length,
+                                channel_state.is_music, channel_state.can_loop, half_rate, inv_frames_per_second);
+
+                bool restart_custom = new_synth.instrument != channel_state.last_main_instrument ||
+                                      new_synth.key != channel_state.last_main_key;
+                channel_state.last_main_instrument = new_synth.instrument;
+                channel_state.last_main_key = new_synth.key;
+
+                if (new_synth.volume > 0.0f)
+                {
+                    if (new_synth.custom)
+                    {
+                        if (channel_state.main_sfx.offset < main_sfx_base_offset) restart_custom = true;
+                        if (channel_state.custom_sfx.sfx == -1 &&
+                            std::floor(main_sfx_base_offset) != std::floor(channel_state.main_sfx.offset))
+                            restart_custom = true;
+
+                        if (restart_custom)
+                        {
+                            channel_state.custom_sfx.sfx = new_synth.instrument;
+                            channel_state.custom_sfx.offset = 0.0;
+                            channel_state.custom_sfx.time = 0.0;
+                        }
+                        new_synth.phi = last_synth.phi;
+                        float const freq_base = key_to_freq(24);
+                        float freq_factor = new_synth.freq / freq_base;
+                        float main_sfx_volume = new_synth.volume;
+                        update_sfx_state(channel_state.custom_sfx, new_synth, freq_factor, 0.0f, false, true, half_rate, inv_frames_per_second);
+                        new_synth.volume *= main_sfx_volume;
+                    }
+                    value = get_synth_sample(new_synth);
+                }
             }

-            _audioState._musicChannel.count = next_count;
-            set_music_pattern(next_pattern);
-        }
-    }
+            float freq_threshold = std::min(new_synth.freq, last_synth.freq) * 0.01f;
+            if (std::abs(new_synth.volume - last_synth.volume) > 0.1f
+                || std::abs(new_synth.freq - last_synth.freq) > freq_threshold
+                || new_synth.instrument != last_synth.instrument)
+            {
+                if (channel_state.fade <= 0.0f)
+                {
+                    channel_state.fade_synth = last_synth;
+                }
+                channel_state.fade = 1.0f;
+                new_synth.phi = std::fmod(new_synth.phi, 1.0f);
+            }
+            last_synth = new_synth;
+
+            uint8_t reverb = (last_synth.filters / 24) % 3;
+            uint8_t dampen = (last_synth.filters / 72) % 3;
+            float chan_reverb1_value = reverb == 1 ? 1.0f : 0.0f;
+            float chan_reverb2_value = reverb == 2 ? 1.0f : 0.0f;
+            float chan_damp1_value = dampen == 1 ? 1.0f : 0.0f;
+            float chan_damp2_value = dampen == 2 ? 1.0f : 0.0f;
+
+            if (channel_state.fade > 0.0f)
+            {
+                channel_state.fade_synth.phi = channel_state.fade_synth.phi +
+                    (float)(channel_state.fade_synth.freq * inv_frames_per_second);
+                float value_fade = get_synth_sample(channel_state.fade_synth);
+
+                value = lerp(value, value_fade, channel_state.fade);
+
+                uint8_t fade_reverb = (channel_state.fade_synth.filters / 24) % 3;
+                uint8_t fade_dampen = (channel_state.fade_synth.filters / 72) % 3;
+                chan_reverb1_value = lerp(chan_reverb1_value, fade_reverb == 1 ? 1.0f : 0.0f, channel_state.fade);
+                chan_reverb2_value = lerp(chan_reverb2_value, fade_reverb == 2 ? 1.0f : 0.0f, channel_state.fade);
+                chan_damp1_value = lerp(chan_damp1_value, fade_dampen == 1 ? 1.0f : 0.0f, channel_state.fade);
+                chan_damp2_value = lerp(chan_damp2_value, fade_dampen == 2 ? 1.0f : 0.0f, channel_state.fade);
+
+                channel_state.fade -= (float)(130.0 * inv_frames_per_second);
+            }
+
+            if (_memory->hwState.reverb & (1 << (chan + 4))) chan_reverb1_value = 1.0f;
+            if (_memory->hwState.reverb & (1 << chan)) chan_reverb2_value = 1.0f;
+            if (_memory->hwState.lowpass & (1 << (chan + 4))) chan_damp1_value = 1.0f;
+            if (_memory->hwState.lowpass & (1 << chan)) chan_damp2_value = 1.0f;
+
+            if (chan_reverb1_value > 0.0f)
+                value += chan_reverb1_value * channel_state.reverb_2[channel_state.reverb_index % 366] * 0.5f;
+            if (chan_reverb2_value > 0.0f)
+                value += chan_reverb2_value * channel_state.reverb_4[channel_state.reverb_index % 732] * 0.5f;

-    sample = (int16_t) (32767.99f * this->getSampleForSfx(_audioState._sfxChannels[channel]));
+            channel_state.reverb_2[channel_state.reverb_index % 366] = value;
+            channel_state.reverb_4[channel_state.reverb_index % 732] = value;
+            ++channel_state.reverb_index;
+
+            float value_damp1 = channel_state.damp1.run(value);
+            if (chan_damp1_value > 0.0f) value = lerp(value, value_damp1, chan_damp1_value);
+
+            float value_damp2 = channel_state.damp2.run(value);
+            if (chan_damp2_value > 0.0f) value = lerp(value, value_damp2, chan_damp2_value);
+
+            int16_t chan_sample = (int16_t)(32767.99f * std::clamp(value, -0.99f, 0.99f));
+
+            if (_memory->hwState.distort & (1 << chan))
+            {
+                chan_sample = chan_sample / 0x1000 * 0x1249;
+            }
+            else if (_memory->hwState.distort & (1 << (chan + 4)))
+            {
+                chan_sample = (chan_sample - (chan_sample < 0 ? 0x1000 : 0)) / 0x1000 * 0x1249;
+            }
+            channel_mix += chan_sample;
+        }

-    // TODO: Apply hardware effects
-    if (_memory->hwState.distort & (1 << channel)) {
-        sample = sample / 0x1000 * 0x1249;
+        buffer[i] = (int16_t)std::clamp(channel_mix, -32767.9f, 32767.9f);
     }
-    return sample;
 }
diff --git a/source/Audio.h b/source/Audio.h
index cc36bc5..ba6b9f7 100644
--- a/source/Audio.h
+++ b/source/Audio.h
@@ -1,6 +1,7 @@
 #pragma once

 #include "PicoRam.h"
+#include "synth.h"

 #include <string>

@@ -91,12 +92,12 @@ class Audio {
     audioState_t _audioState;

     void set_music_pattern(int pattern);
+    void update_sfx_state(sfx_state& cur_sfx, z8::synth_param& new_synth,
+                          float freq_factor, float length, bool is_music,
+                          bool can_loop, bool half_rate, double inv_frames_per_second);
+    float get_synth_sample(z8::synth_param& params);
+    void launch_sfx(int16_t sfx, int16_t chan, float offset, float length, bool is_music);

-    public:
-    float getSampleForSfx(rawSfxChannel &channel, float freqShift = 1.0f);
-    int16_t getSampleForChannel(int channel);
-    float getSampleForNote(noteChannel &note_channel, rawSfxChannel &parentChannel, rawSfxChannel *childChannel, note prev_note, float freqShift, bool forceRemainder);
-
     public:
     Audio(PicoRam* memory);

@@ -115,4 +116,3 @@ class Audio {
     void FillAudioBuffer(void *audioBuffer,size_t offset, size_t size);
     void FillMonoAudioBuffer(void *audioBuffer,size_t offset, size_t size);
 };
-
diff --git a/source/PicoRam.h b/source/PicoRam.h
index 424ffa8..d651d44 100644
--- a/source/PicoRam.h
+++ b/source/PicoRam.h
@@ -3,6 +3,8 @@
 #include <cstdint>
 #include <cstring>
 #include <string>
+#include "filter.h"
+#include "synth.h"

 /*
 0x0 	0x0fff 	Sprite sheet (0-127)
@@ -109,7 +111,11 @@ struct sfx {
         {
             note notes[32];

-            uint8_t editorMode;
+            // 0: filters + editor flag
+            // 1: speed (1-255)
+            // 2: loop start
+            // 3: loop end
+            uint8_t filters;
             uint8_t speed;
             uint8_t loopRangeStart;
             uint8_t loopRangeEnd;
@@ -119,52 +125,50 @@ struct sfx {
     };
 };

+// Audio states: music channel
 struct musicChannel {
-    int16_t count = 0;
+    int16_t count = -1;
     int16_t pattern = -1;
-    int8_t master = -1;
-    uint8_t mask = 0xf;
-    uint8_t speed = 0;
-    float volume = 0.f;
-    float volume_step = 0.f;
-    float offset = 0.f;
-	uint8_t length = 0;
+    uint8_t mask = 0;
+    float volume_music = 0.5f;
+    float volume_sfx = 0.5f;
+    float fade_volume = 0.f;
+    float fade_volume_step = 0.f;
+    double offset = -1;
+    float length = 0;
 };

-struct noteChannel {
-    float phi = 0;
-    note n;
+// SFX playback state
+struct sfx_state {
+    int16_t sfx = -1;
+    double offset = 0;
+    double time = 0;
+    int8_t prev_key = 0;
+    float prev_vol = 0;
 };

-struct rawSfxChannel {
-    int16_t sfxId = -1;
-    float offset = 0;
+// Audio channel state
+struct sfxChannel {
+    sfx_state main_sfx;
+    sfx_state custom_sfx;
+
+    int16_t sfx_music = -1;
+    float length = 0;
     bool can_loop = true;
     bool is_music = false;
-    noteChannel current_note;
-    noteChannel prev_note;
-    virtual rawSfxChannel *getChildChannel() {
-      return NULL;
-    }
-    virtual rawSfxChannel *getPrevChildChannel() {
-      return NULL;
-    }
-    virtual void rotateChannels() {
-    }
-};

-struct sfxChannel : rawSfxChannel {
-    rawSfxChannel customInstrumentChannel;
-    rawSfxChannel prevInstrumentChannel;
-    virtual rawSfxChannel *getChildChannel() {
-      return &(this->customInstrumentChannel);
-    }
-    virtual rawSfxChannel *getPrevChildChannel() {
-      return &(this->prevInstrumentChannel);
-    }
-    virtual void rotateChannels() {
-      prevInstrumentChannel = customInstrumentChannel;
-    }
+    z8::synth_param last_synth;
+    z8::synth_param fade_synth;
+    float fade = 0.0f;
+    uint8_t last_main_instrument = 0;
+    uint8_t last_main_key = 0;
+
+    int reverb_index = 0;
+    float reverb_2[366] = {};
+    float reverb_4[732] = {};
+
+    z8::filter damp1;
+    z8::filter damp2;
 };

 struct audioState_t {
diff --git a/source/cart.cpp b/source/cart.cpp
index bd5e71f..94a1e8d 100644
--- a/source/cart.cpp
+++ b/source/cart.cpp
@@ -592,7 +592,7 @@ void Cart::setSfx(std::string sfxString) {
     while (std::getline(s, line)) {
         buf[0] = line[0];
         buf[1] = line[1];
-        uint8_t editorMode = (uint8_t)strtol(buf, NULL, 16);
+        uint8_t filters = (uint8_t)strtol(buf, NULL, 16);

         buf[0] = line[2];
         buf[1] = line[3];
@@ -606,7 +606,7 @@ void Cart::setSfx(std::string sfxString) {
         buf[1] = line[7];
         uint8_t loopRangeEnd = (uint8_t)strtol(buf, NULL, 16);

-        CartRom.SfxData[sfxIdx].editorMode = editorMode;
+        CartRom.SfxData[sfxIdx].filters = filters;
         CartRom.SfxData[sfxIdx].speed = noteDuration;
         CartRom.SfxData[sfxIdx].loopRangeStart = loopRangeStart;
         CartRom.SfxData[sfxIdx].loopRangeEnd = loopRangeEnd;
diff --git a/source/filter.cpp b/source/filter.cpp
new file mode 100644
index 0000000..2ad3e17
--- /dev/null
+++ b/source/filter.cpp
@@ -0,0 +1,100 @@
+//
+//  ZEPTO-8 — Fantasy console emulator
+//
+//  Copyright © 2017–2024 Sam Hocevar <sam@hocevar.net>
+//
+//  This program is free software. It comes without any warranty, to
+//  the extent permitted by applicable law. You can redistribute it
+//  and/or modify it under the terms of the Do What the Fuck You Want
+//  to Public License, Version 2, as published by the WTFPL Task Force.
+//  See http://www.wtfpl.net/ for more details.
+//
+
+#include "filter.h"
+
+#include <cmath> // std::cos, std::sin, std::pow, std::sqrt
+
+namespace z8
+{
+
+static constexpr float F_TAU = 6.283185307179586f;
+
+filter::filter(type t, float freq, float q, float gain)
+{
+    init(t, freq, q, gain);
+}
+
+void filter::init(type t, float freq, float q, float gain)
+{
+    // Formulae are from https://www.w3.org/TR/audio-eq-cookbook/
+    float w0 = F_TAU * freq / 22050;
+    float cosw0 = std::cos(w0);
+    float a = std::pow(10.0f, gain / 40);
+    float alpha;
+    if (t == type::lowshelf || t == type::highshelf)
+        alpha = (std::sin(w0) / 2) * std::sqrt((a + 1 / a) * (1 / q - 1) + 2);
+    else
+        alpha = std::sin(w0) / (2 * q);
+
+    float a0, a1, a2, b0, b1, b2;
+    switch (t)
+    {
+    case type::lpf:
+        a0 =  1 + alpha;
+        a1 = -2 * cosw0;
+        a2 =  1 - alpha;
+        b0 = (1 - cosw0) / 2;
+        b1 = (1 - cosw0);
+        b2 = (1 - cosw0) / 2;
+        break;
+    case type::hpf:
+        a0 =  1 + alpha;
+        a1 = -2 * cosw0;
+        a2 =  1 - alpha;
+        b0 =  (1 + cosw0) / 2;
+        b1 = -(1 + cosw0);
+        b2 =  (1 + cosw0) / 2;
+        break;
+    case type::lowshelf:
+    {
+        float sqra = 2 * std::sqrt(a) * alpha;
+        a0 = (a + 1) + (a - 1) * cosw0 + sqra;
+        a1 = -2 * ((a - 1) + (a + 1) * cosw0);
+        a2 = (a + 1) + (a - 1) * cosw0 - sqra;
+        b0 = a * ((a + 1) - (a - 1) * cosw0 + sqra);
+        b1 = 2 * a * ((a - 1) - (a + 1) * cosw0);
+        b2 = a * ((a + 1) - (a - 1) * cosw0 - sqra);
+        break;
+    }
+    case type::highshelf:
+    {
+        float sqra = 2 * std::sqrt(a) * alpha;
+        a0 = (a + 1) - (a - 1) * cosw0 + sqra;
+        a1 = 2 * ((a - 1) - (a + 1) * cosw0);
+        a2 = (a + 1) - (a - 1) * cosw0 - sqra;
+        b0 = a * ((a + 1) + (a - 1) * cosw0 + sqra);
+        b1 = -2 * a * ((a - 1) + (a + 1) * cosw0);
+        b2 = a * ((a + 1) + (a - 1) * cosw0 - sqra);
+        break;
+    }
+    }
+    c1 = b0 / a0;
+    c2 = b1 / a0;
+    c3 = b2 / a0;
+    c4 = a1 / a0;
+    c5 = a2 / a0;
+}
+
+float filter::run(float input)
+{
+    float output = c1 * input + c2 * linput + c3 * llinput - c4 * loutput - c5 * lloutput;
+    llinput = linput;
+    linput = input;
+    lloutput = loutput;
+    loutput = output;
+
+    return output;
+}
+
+} // namespace z8
+
diff --git a/source/filter.h b/source/filter.h
new file mode 100644
index 0000000..36655e7
--- /dev/null
+++ b/source/filter.h
@@ -0,0 +1,44 @@
+//
+//  ZEPTO-8 — Fantasy console emulator
+//
+//  Copyright © 2016—2020 Sam Hocevar <sam@hocevar.net>
+//
+//  This program is free software. It comes without any warranty, to
+//  the extent permitted by applicable law. You can redistribute it
+//  and/or modify it under the terms of the Do What the Fuck You Want
+//  to Public License, Version 2, as published by the WTFPL Task Force.
+//  See http://www.wtfpl.net/ for more details.
+//
+
+#pragma once
+
+namespace z8
+{
+
+//
+// Biquad filter
+//
+
+class filter
+{
+public:
+    enum class type
+    {
+        lpf, hpf, lowshelf, highshelf
+    };
+
+    filter() = default;
+    filter(type t, float freq, float q, float gain);
+
+    void init(type t, float freq, float q, float gain);
+    float run(float input);
+
+    float c1 = 0, c2 = 0, c3 = 0, c4 = 0, c5 = 0;
+    float linput = 0;
+    float llinput = 0;
+    float loutput = 0;
+    float lloutput = 0;
+};
+
+} // namespace z8
+
diff --git a/source/synth.cpp b/source/synth.cpp
index 972803c..a7b5e0b 100644
--- a/source/synth.cpp
+++ b/source/synth.cpp
@@ -12,112 +12,105 @@

 #include "synth.h"

-//#include <lol/noise> // lol::perlin_noise
 #include <cmath>     // std::fabs, std::fmod
-#include <algorithm> //std::min, std::max
-
-//temp for printf debugging
-//#include <stdio.h>
+#include <cstdlib>   // rand

 namespace z8
 {

-float synth::waveform(int instrument, float advance)
+// Simple random function returning float in range [-1, 1]
+static float rand_float()
 {
-    using std::fabs;
-    using std::fmod;
+    return ((float)rand() / (float)RAND_MAX) * 2.0f - 1.0f;
+}

-    //const from picolove:
-    //local function note_to_hz(note)
-	//  return 440 * 2 ^ ((note - 33) / 12)
-    //end
-    //local tscale = note_to_hz(63) / __sample_rate
-    const float tscale = 0.11288053831187f;
+float synth::waveform(synth_param &params)
+{
+    using std::fabs, std::fmod;

+    float advance = params.phi;
     float t = fmod(advance, 1.f);
     float ret = 0.f;

+    bool noiz = params.filters & 0x2;
+    bool buzz = params.filters & 0x4;
+
     // Multipliers were measured from PICO-8 WAV exports. Waveforms are
     // inferred from those exports by guessing what the original formulas
     // could be.
-    switch (instrument)
+    switch (params.instrument)
     {
         case INST_TRIANGLE:
-            return 0.5f * (fabs(4.f * t - 2.0f) - 1.0f);
+            ret = 1.0f - fabs(4.f * t - 2.0f);
+            if (buzz) {
+                // seems to be averaged with a tilted saw
+                static float const a = 0.875f;
+                float bret = t < a ? 2.f * t / a - 1.f
+                            : 2.f * (1.f - t) / (1.f - a) - 1.f;
+                ret = ret * 0.75f + bret * 0.25f;
+            }
+            return ret * 0.5f;
         case INST_TILTED_SAW:
         {
-            static float const a = 0.9f;
+            float a = buzz ? 0.975f : 0.875f;
             ret = t < a ? 2.f * t / a - 1.f
                         : 2.f * (1.f - t) / (1.f - a) - 1.f;
             return ret * 0.5f;
         }
         case INST_SAW:
-            return 0.653f * (t < 0.5f ? t : t - 1.f);
+            ret = (t < 0.5f ? t : t - 1.f);
+            // slight offset looping on 2x period
+            if (buzz) ret = ret * 0.83f - (fabs(fmod(advance, 2.f) - 1.0f) < 0.5 ? 0.085f : 0.0f);
+            return 0.653f * ret;
         case INST_SQUARE:
-            return t < 0.5f ? 0.25f : -0.25f;
+            return t < (buzz ? 0.4f : 0.5f) ? 0.25f : -0.25f;
         case INST_PULSE:
-            return t < 1.f / 3 ? 0.25f : -0.25f;
+            return t < (buzz ? 0.255f : 0.316f) ? 0.25f : -0.25f;
         case INST_ORGAN:
             ret = t < 0.5f ? 3.f - fabs(24.f * t - 6.f)
                            : 1.f - fabs(16.f * t - 12.f);
+            if (buzz)
+            {
+                // add a cut on the first of the two triangles
+                ret = t < 0.5f ? ret * 2.0f + 3.0f : ret;
+                ret = (t < 0.5f && ret>-1.875f) ? ret * 0.2f - 1.0f : ret + 0.5f;
+            }
             return ret / 9.f;
         case INST_NOISE:
         {
-            // Spectral analysis indicates this is some kind of brown noise,
-            // but losing almost 10dB per octave. I thought using Perlin noise
-            // would be fun, but it’s definitely not accurate.
-            //
-            // This may help us create a correct filter:
-            // http://www.firstpr.com.au/dsp/pink-noise/
-
-            //TODO: not even doing zepto 8 noise here
-
-            //static lol::perlin_noise<1> noise;
-            //for (float m = 1.75f, d = 1.f; m <= 128; m *= 2.25f, d *= 0.75f)
-            //    ret += d * noise.eval(lol::vec_t<float, 1>(m * advance));
-
-            //ret = ((float)rand() / (float)RAND_MAX);
-
-            //return ret * 0.4f;
-
-            //picolove noise function in lua
-            //zepto8 phi == picolove oscpos (x parameter in picolove generator func, advance in synth.cpp waveform function)
-            //-- noise
-            //osc[6] = function()
-            //    local lastx = 0
-            //    local sample = 0
-            //    local lsample = 0
-            //    local tscale = note_to_hz(63) / __sample_rate
-            //1,041.8329
-            //    return function(x)
-            //        local scale = (x - lastx) / tscale
-            //        lsample = sample
-            //        sample = (lsample + scale * (math.random() * 2 - 1)) / (1 + scale)
-            //        lastx = x
-            //        return math.min(math.max((lsample + sample) * 4 / 3 * (1.75 - scale), -1), 1) *
-            //            0.7
-            //    end
-            //end
-            //printf("tscale: %f\n", tscale);
-            //printf("advance: %f\n", advance);
-
-            float scale = (advance - lastadvance) / tscale;
-            //printf("scale: %f\n", scale);
-            lsample = sample;
-            sample = (lsample + scale * (((float)rand() / (float)RAND_MAX) * 2.0f - 1.0f)) / (1.0f + scale);
-            //printf("sample: %f\n", sample);
-            lastadvance = advance;
-            float endval = std::min(std::max((lsample + sample) * 4.0f / 3.0f * (1.75f - scale), -1.0f), 1.0f) * 0.2f;
-            //printf("endval: %f\n", endval);
-            return endval;
+            //const float tscale = 22050 / key_to_freq(63);
+            const float tscale = 8.858923f;
+            float scale = (advance - params.last_advance) * tscale;
+            float new_sample = (params.last_sample + scale * rand_float()) / (1.0f + scale);
+
+            float factor = 1.0f - params.key / 63.0f;
+            ret = new_sample * 1.5f * (1.0f + factor * factor);
+
+            if (noiz)
+            {
+                // sound a bit like a saw tooth but not quite
+                ret *= 2.0f*(t < 0.5f ? t : t - 1.f);
+            }
+
+            params.last_advance = advance;
+            params.last_sample = new_sample;
+
+            return ret;
         }
         case INST_PHASER:
-        {   // This one has a subfrequency of freq/128 that appears
-            // to modulate two signals using a triangle wave
-            // FIXME: amplitude seems to be affected, too
-            float k = fabs(2.f * fmod(advance / 128.f, 1.f) - 1.f);
-            float u = fmod(t + 0.5f * k, 1.0f);
-            ret = fabs(4.f * u - 2.f) - fabs(8.f * t - 4.f);
+        {   // sum of two triangle waves with a slightly different frequency
+            // the ratio between the frequency seems to be around 110 for c2
+            // but it is 97 for c0 and 127 for c5, not sure how to adjust that
+            ret = 2.f - fabs(8.f * t - 4.f);
+            ret += 1.f - fabs(4.f * fmod(advance * 109.f/110.f, 1.f) - 2.f);
+            if (buzz)
+            {
+                // original triangle has freq 1, 3, 5, 7, 9 ...
+                // add waves at 2, 6, 10, 14
+                ret += 0.25f - fabs(1.f * fmod(advance * 2.0f + 0.5f, 1.f) - 0.5f);
+                // add waves at 4, 12, 20, 28
+                ret += 0.125f - fabs(0.5f * fmod(advance * 4.0f, 1.f) - 0.25f);
+            }
             return ret / 6.f;
         }
     }
@@ -126,4 +119,3 @@ float synth::waveform(int instrument, float advance)
 }

 } // namespace z8
-
diff --git a/source/synth.h b/source/synth.h
index f2c6027..87eda92 100644
--- a/source/synth.h
+++ b/source/synth.h
@@ -12,9 +12,26 @@

 #pragma once

+#include <cstdint>
+
 namespace z8
 {

+// Synth parameters for waveform generation
+struct synth_param
+{
+    uint8_t instrument = 0;
+    bool custom = false;
+    uint8_t filters = 0;
+    uint8_t key = 0;
+    float freq = 0;
+    float volume = 0;
+    float phi = 0;
+    float last_advance = 0;
+    float last_sample = 0;
+    bool is_music = false;
+};
+
 //
 // A waveform generator
 //
@@ -34,18 +51,7 @@ public:
         INST_PHASER     = 7,
     };

-    static float waveform(int instrument, float advance);
-
-    //These are inline so they don't have to be declared in the class
-    //c++17 allows this, but if need for c++11 "inline" can be removed and they
-    //can be declared in synth.cpp
-    //also not threadsafe, but this is all single threaded anyway
-    private:
-        inline static float lastadvance;
-        inline static float sample;
-        inline static float lsample;
-
+    static float waveform(synth_param &params);
 };

 } // namespace z8
-
diff --git a/test/audiotests.cpp b/test/audiotests.cpp
index 4a373e1..deb96e6 100644
--- a/test/audiotests.cpp
+++ b/test/audiotests.cpp
@@ -59,116 +59,15 @@ TEST_CASE("audio class behaves as expected") {
     Audio* audio = new Audio(&picoRam);
     audioState_t* audioState = audio->getAudioState();

-   SUBCASE("custom instruments same note"){
-        note c;
-
-        c.setCustom(true);
-        c.setWaveform(1);
-        c.setVolume(5);
-        c.setKey(24);
-
-        picoRam.sfx[0].speed = 32;
-        picoRam.sfx[0].notes[0] = c;
-        picoRam.sfx[0].notes[1] = c;
-
-        picoRam.sfx[1].speed=8;
-        //183 is one tick
-        for (int i=0;i<8;i++) {
-          picoRam.sfx[1].notes[i].setVolume(5);
-          picoRam.sfx[1].notes[i].setWaveform(1);
-        }
-        picoRam.sfx[1].notes[0].setKey(24);
-        picoRam.sfx[1].notes[1].setKey(26);
-        picoRam.sfx[1].notes[2].setKey(28);
-        picoRam.sfx[1].notes[3].setKey(29);
-        picoRam.sfx[1].notes[4].setKey(31);
-        picoRam.sfx[1].notes[5].setKey(33);
-        picoRam.sfx[1].notes[6].setKey(35);
-        picoRam.sfx[1].notes[7].setKey(36);
-
-        sfxChannel s;
-        s.sfxId=0;
-        s.offset=0;
-        s.current_note.phi=0;
-
-        for (int i=0; i<183*4; i++) { audio->getSampleForSfx(s); }
-        CHECK_EQ(s.getChildChannel()->current_note.n.getKey(), 24);
-        for (int i=0; i<183*8; i++) { audio->getSampleForSfx(s); }
-        CHECK_EQ(s.getChildChannel()->current_note.n.getKey(), 26);
-        for (int i=0; i<183*8; i++) { audio->getSampleForSfx(s); }
-        CHECK_EQ(s.getChildChannel()->current_note.n.getKey(), 28);
-        for (int i=0; i<183*8; i++) { audio->getSampleForSfx(s); }
-        CHECK_EQ(s.getChildChannel()->current_note.n.getKey(), 29);
-        for (int i=0; i<183*8; i++) { audio->getSampleForSfx(s); }
-        CHECK_EQ(s.getChildChannel()->current_note.n.getKey(), 31);
-        for (int i=0; i<183*8; i++) { audio->getSampleForSfx(s); }
-        CHECK_EQ(s.getChildChannel()->current_note.n.getKey(), 33);
-        for (int i=0; i<183*8; i++) { audio->getSampleForSfx(s); }
-        CHECK_EQ(s.getChildChannel()->current_note.n.getKey(), 35);
-        for (int i=0; i<183*8; i++) { audio->getSampleForSfx(s); }
-        CHECK_EQ(s.getChildChannel()->current_note.n.getKey(), 36);
-   }
-
-   SUBCASE("custom instruments different note"){
-        note c,d;
-
-        c.setCustom(true);
-        c.setWaveform(1);
-        c.setVolume(5);
-        c.setKey(24);
-        d.setCustom(true);
-        d.setWaveform(1);
-        d.setVolume(5);
-        d.setKey(26);
-
-        picoRam.sfx[0].speed = 32;
-        picoRam.sfx[0].notes[0] = c;
-        picoRam.sfx[0].notes[1] = d;
-
-        picoRam.sfx[1].speed=8;
-        //183 is one tick
-        for (int i=0;i<8;i++) {
-          picoRam.sfx[1].notes[i].setVolume(5);
-          picoRam.sfx[1].notes[i].setWaveform(1);
-        }
-        picoRam.sfx[1].notes[0].setKey(24);
-        picoRam.sfx[1].notes[1].setKey(26);
-        picoRam.sfx[1].notes[2].setKey(28);
-        picoRam.sfx[1].notes[3].setKey(29);
-        picoRam.sfx[1].notes[4].setKey(31);
-        picoRam.sfx[1].notes[5].setKey(33);
-        picoRam.sfx[1].notes[6].setKey(35);
-        picoRam.sfx[1].notes[7].setKey(36);
-
-        sfxChannel s;
-        s.sfxId=0;
-        s.offset=0;
-        s.current_note.phi=0;
-
-        for (int i=0; i<183*4; i++) { audio->getSampleForSfx(s); }
-        CHECK_EQ(s.getChildChannel()->current_note.n.getKey(), 24);
-        for (int i=0; i<183*8; i++) { audio->getSampleForSfx(s); }
-        CHECK_EQ(s.getChildChannel()->current_note.n.getKey(), 26);
-        for (int i=0; i<183*8; i++) { audio->getSampleForSfx(s); }
-        CHECK_EQ(s.getChildChannel()->current_note.n.getKey(), 28);
-        for (int i=0; i<183*8; i++) { audio->getSampleForSfx(s); }
-        CHECK_EQ(s.getChildChannel()->current_note.n.getKey(), 29);
-        for (int i=0; i<183*8; i++) { audio->getSampleForSfx(s); }
-        CHECK_EQ(s.getChildChannel()->current_note.n.getKey(), 24);
-        for (int i=0; i<183*8; i++) { audio->getSampleForSfx(s); }
-        CHECK_EQ(s.getChildChannel()->current_note.n.getKey(), 26);
-        for (int i=0; i<183*8; i++) { audio->getSampleForSfx(s); }
-        CHECK_EQ(s.getChildChannel()->current_note.n.getKey(), 28);
-        for (int i=0; i<183*8; i++) { audio->getSampleForSfx(s); }
-        CHECK_EQ(s.getChildChannel()->current_note.n.getKey(), 29);
-        for (int i=0; i<183*8; i++) { audio->getSampleForSfx(s); }
-   }
+    // Note: The custom instrument tests have been removed as the new audio
+    // implementation no longer exposes getSampleForSfx as a public method
+    // and the internal structure has changed significantly.

     SUBCASE("Audio constructor sets sfx channels to -1") {
         bool allChannelsOff = true;

         for(int i = 0; i < 4; i++) {
-            allChannelsOff &= audioState->_sfxChannels[i].sfxId == -1;
+            allChannelsOff &= audioState->_sfxChannels[i].main_sfx.sfx == -1;
         }

         CHECK(allChannelsOff);
@@ -178,7 +77,7 @@ TEST_CASE("audio class behaves as expected") {
         int sfxId = 3;
         audio->api_sfx(sfxId, channel, 0, 31);

-        CHECK_EQ(audioState->_sfxChannels[0].sfxId, sfxId);
+        CHECK_EQ(audioState->_sfxChannels[0].main_sfx.sfx, sfxId);
     }
     SUBCASE("api_sfx() with -1 channel finds first available") {
         audio->api_sfx(1, 0, 0, 31);
@@ -186,7 +85,7 @@ TEST_CASE("audio class behaves as expected") {
         audio->api_sfx(5, -1, 0, 31);


-        CHECK_EQ(audioState->_sfxChannels[2].sfxId, 5);
+        CHECK_EQ(audioState->_sfxChannels[2].main_sfx.sfx, 5);
     }
     SUBCASE("api_sfx() with -2 channel stops the sfx on any channel") {
         audio->api_sfx(1, 0, 0, 31);
@@ -196,17 +95,10 @@ TEST_CASE("audio class behaves as expected") {
         audio->api_sfx(1, -2, 0, 31);


-        CHECK_EQ(audioState->_sfxChannels[0].sfxId, -1);
-        CHECK_EQ(audioState->_sfxChannels[1].sfxId, 10);
-        CHECK_EQ(audioState->_sfxChannels[2].sfxId, 20);
-        CHECK_EQ(audioState->_sfxChannels[3].sfxId, -1);
-    }
-    SUBCASE("api_sfx() -2 sfx id stops looping") {
-        audioState->_sfxChannels[3].can_loop = true;
-
-        audio->api_sfx(-2, 3, 0, 31);
-
-        CHECK_EQ(audioState->_sfxChannels[3].can_loop, false);
+        CHECK_EQ(audioState->_sfxChannels[0].main_sfx.sfx, -1);
+        CHECK_EQ(audioState->_sfxChannels[1].main_sfx.sfx, 10);
+        CHECK_EQ(audioState->_sfxChannels[2].main_sfx.sfx, 20);
+        CHECK_EQ(audioState->_sfxChannels[3].main_sfx.sfx, -1);
     }
     SUBCASE("api_sfx() -2 sfx id stops looping") {
         audioState->_sfxChannels[3].can_loop = true;
@@ -226,98 +118,31 @@ TEST_CASE("audio class behaves as expected") {
         picoRam.songs[3].data[2]=11;
         picoRam.songs[3].data[3]=12;
         audio->api_music(3, 0, 0);
-        CHECK_EQ(audioState->_sfxChannels[0].sfxId, 9);
-        CHECK_EQ(audioState->_sfxChannels[1].sfxId, 10);
-        CHECK_EQ(audioState->_sfxChannels[2].sfxId, 11);
-        CHECK_EQ(audioState->_sfxChannels[3].sfxId, 12);
+        CHECK_EQ(audioState->_sfxChannels[0].main_sfx.sfx, 9);
+        CHECK_EQ(audioState->_sfxChannels[1].main_sfx.sfx, 10);
+        CHECK_EQ(audioState->_sfxChannels[2].main_sfx.sfx, 11);
+        CHECK_EQ(audioState->_sfxChannels[3].main_sfx.sfx, 12);
     }

-    SUBCASE("api_music makes master fastest sfx channels"){
-        picoRam.songs[3].data[0]=0;
-        picoRam.songs[3].data[1]=1;
-        picoRam.songs[3].data[2]=2;
-        picoRam.songs[3].data[3]=3;
-        picoRam.sfx[0].speed = 4;
-        picoRam.sfx[1].speed = 6;
-        picoRam.sfx[2].speed = 3;
-        picoRam.sfx[3].speed = 5;
-        audio->api_music(3, 0, 0);
-        CHECK_EQ(audioState->_sfxChannels[audioState->_musicChannel.master].sfxId, 2);
-    }
-
-    SUBCASE("api_music makes master shortest sfx channels"){
-        picoRam.songs[3].data[0]=0;
-        picoRam.songs[3].data[1]=1;
-        picoRam.songs[3].data[2]=2;
-        picoRam.songs[3].data[3]=3;
-        picoRam.sfx[0].loopRangeStart = 9;
-        picoRam.sfx[1].loopRangeStart = 6;
-        picoRam.sfx[2].loopRangeStart = 30;
-        picoRam.sfx[3].loopRangeStart = 7;
-        audio->api_music(3, 0, 0);
-        CHECK_EQ(audioState->_sfxChannels[audioState->_musicChannel.master].sfxId, 1);
-    }
-
-    SUBCASE("api_music makes master shortest/fastest sfx channels"){
-        picoRam.songs[3].data[0]=0;
-        picoRam.songs[3].data[1]=1;
-        picoRam.songs[3].data[2]=2;
-        picoRam.songs[3].data[3]=3;
-        picoRam.sfx[0].loopRangeStart = 9;
-        picoRam.sfx[1].loopRangeStart = 6;
-        picoRam.sfx[2].loopRangeStart = 30;
-        picoRam.sfx[3].loopRangeStart = 7;
-        picoRam.sfx[0].speed = 4;
-        picoRam.sfx[1].speed = 6;
-        picoRam.sfx[2].speed = 3;
-        picoRam.sfx[3].speed = 5;
-        audio->api_music(3, 0, 0);
-        CHECK_EQ(audioState->_sfxChannels[audioState->_musicChannel.master].sfxId, 3);
-    }
-
-    SUBCASE("api_music prefers non-looping"){
-        picoRam.songs[3].data[0]=0;
-        picoRam.songs[3].data[1]=1;
-        picoRam.songs[3].data[2]=2;
-        picoRam.songs[3].data[3]=3;
-        picoRam.sfx[0].loopRangeEnd = 9;
-        picoRam.sfx[0].speed = 4;
-        picoRam.sfx[1].speed = 6;
-        picoRam.sfx[2].speed = 9;
-        picoRam.sfx[3].speed = 99;
-        audio->api_music(3, 0, 0);
-        CHECK_EQ(audioState->_sfxChannels[audioState->_musicChannel.master].sfxId, 1);
-    }
-
-    SUBCASE("api_music picks fastest looping if all looping ignoring loop length"){
-        picoRam.songs[3].data[0]=0;
-        picoRam.songs[3].data[1]=1;
-        picoRam.songs[3].data[2]=2;
-        picoRam.songs[3].data[3]=3;
-        picoRam.sfx[0].loopRangeEnd = 9;
-        picoRam.sfx[1].loopRangeEnd = 6;
-        picoRam.sfx[2].loopRangeEnd = 30;
-        picoRam.sfx[3].loopRangeEnd = 7;
-        picoRam.sfx[0].speed = 4;
-        picoRam.sfx[1].speed = 6;
-        picoRam.sfx[2].speed = 3;
-        picoRam.sfx[3].speed = 5;
-        audio->api_music(3, 0, 0);
-        CHECK_EQ(audioState->_sfxChannels[audioState->_musicChannel.master].sfxId, 2);
-    }
+    // Note: The master channel tests have been removed as the new implementation
+    // no longer uses a master field. The music system now uses pattern-based
+    // length calculation instead of tracking a master channel.

     SUBCASE("bass loop effect"){
       Cart* cart = new Cart("songtest.p8", "carts");
       memcpy(&picoRam.data[0], &cart->CartRom.data[0], sizeof(cart->CartRom));
       audio->api_music(41, 0, 0xf);

-      // get 1 second
+      // get 20 seconds of audio
       std::stringbuf buffer;
       std::iostream os (&buffer);  // associate stream buffer to stream

-      for (int i=1; i<22050*20; i++) {
-        int16_t sample = audio->getSampleForChannel(0);
-        os.write(reinterpret_cast<char *>(&sample), sizeof(int16_t));
+      int16_t samples[22050];
+      for (int chunk = 0; chunk < 20; chunk++) {
+        audio->FillMonoAudioBuffer(samples, 0, 22050);
+        for (int i = 0; i < 22050; i++) {
+          os.write(reinterpret_cast<char *>(&samples[i]), sizeof(int16_t));
+        }
       }
       write_wav(&os, "bass.wav");
       delete cart;
diff --git a/test/carttests.cpp b/test/carttests.cpp
index 24e918f..5de5614 100644
--- a/test/carttests.cpp
+++ b/test/carttests.cpp
@@ -82,7 +82,7 @@ TEST_CASE("Load simple p8 cart") {
     }
     SUBCASE("Sfx data is populated") {
         CHECK(cart->CartRom.SfxData[0].data[0] == 13);
-        CHECK(cart->CartRom.SfxData[0].editorMode == 0);
+        CHECK(cart->CartRom.SfxData[0].filters == 0);
         CHECK(cart->CartRom.SfxData[0].loopRangeEnd == 0);
         CHECK(cart->CartRom.SfxData[0].loopRangeEnd == 0);
         CHECK(cart->CartRom.SfxData[0].speed == 29);
@@ -165,7 +165,7 @@ TEST_CASE("Load simple png cart") {
     }
     SUBCASE("Sfx data is populated") {
         CHECK(cart->CartRom.SfxData[0].data[0] == 13);
-        CHECK(cart->CartRom.SfxData[0].editorMode == 0);
+        CHECK(cart->CartRom.SfxData[0].filters == 0);
         CHECK(cart->CartRom.SfxData[0].loopRangeEnd == 0);
         CHECK(cart->CartRom.SfxData[0].loopRangeEnd == 0);
         CHECK(cart->CartRom.SfxData[0].speed == 29);
diff --git a/test/vmtests.cpp b/test/vmtests.cpp
index 4220ac1..ddee34a 100644
--- a/test/vmtests.cpp
+++ b/test/vmtests.cpp
@@ -366,7 +366,7 @@ TEST_CASE("Vm memory functions") {
         }
         SUBCASE("Sfx data is populated") {
             CHECK(memory->sfx[0].data[0] == 13);
-            CHECK(memory->sfx[0].editorMode == 0);
+            CHECK(memory->sfx[0].filters == 0);
             CHECK(memory->sfx[0].loopRangeEnd == 0);
             CHECK(memory->sfx[0].loopRangeEnd == 0);
             CHECK(memory->sfx[0].speed == 29);