foxygit / fake-08-xbox360 Log in
commit 6089539a059d2d251e7b444d3cf74d46312010e5
Author:     Jon Bell <jondbell@protonmail.com>
AuthorDate: Sun May 3 14:17:46 2020 -0600
Commit:     Jon Bell <jondbell@protonmail.com>
CommitDate: Sun May 3 14:17:46 2020 -0600

    Basic sfx test working (ish)
---
 source/Audio.cpp      | 148 ++++++++++++++++++++++++++++++++++++++++++++++++++
 source/Audio.h        |   5 ++
 source/cart.cpp       |   2 +-
 source/console.cpp    |  26 +--------
 source/main.cpp       |   2 +-
 source/picoluaapi.cpp |  17 +++++-
 source/picoluaapi.h   |   2 +-
 source/synth.cpp      |  84 ++++++++++++++++++++++++++++
 source/synth.h        |  41 ++++++++++++++
 9 files changed, 299 insertions(+), 28 deletions(-)

diff --git a/source/Audio.cpp b/source/Audio.cpp
index 82f3ead..aa93214 100644
--- a/source/Audio.cpp
+++ b/source/Audio.cpp
@@ -1,11 +1,19 @@
 #include "Audio.h"
+#include "synth.h"

 #include <string>
 #include <sstream>
+#include <cmath>

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

+Audio::Audio(){
+    for(int i = 0; i < 4; i++) {
+        _sfxChannels[i].sfxId = -1;
+    }
+}
+
 void Audio::setMusic(std::string musicString){
     std::istringstream s(musicString);
     std::string line;
@@ -134,3 +142,143 @@ void Audio::api_music(uint8_t pattern, int16_t fade_len, int16_t mask){


 }
+
+
+
+//todo: figure out where to store this
+#define SAMPLERATE 22050
+//----------------------------------------------------------------------------
+void fill_buffer(void *audioBuffer,size_t offset, size_t size, int frequency ) {
+//----------------------------------------------------------------------------
+
+	uint32_t *dest = (uint32_t*)audioBuffer;
+
+	for (size_t i=0; i<size; i++) {
+
+		int16_t sample = INT16_MAX * sin(frequency*(2*M_PI)*(offset+i)/SAMPLERATE);
+
+		dest[i] = (sample<<16) | (sample & 0xffff);
+	}
+}
+
+
+void Audio::FillAudioBuffer(void *audioBuffer, size_t offset, size_t size){
+
+    uint32_t *buffer = (uint32_t *)audioBuffer;
+
+    for (size_t i = 0; i < size; ++i){
+        int16_t sample = 0;
+
+        for (int c = 0; c < 4; ++c) {
+            sample += this->getSampleForChannel(c);
+            //int16_t sample = INT16_MAX * sin(440*(2*M_PI)*(offset+i)/SAMPLERATE);
+
+
+        }
+        buffer[i] = (sample<<16) | (sample & 0xffff);
+    }
+}
+
+static float key_to_freq(float key)
+{
+    using std::exp2;
+    return 440.f * exp2((key - 33.f) / 12.f);
+}
+
+
+
+//adapted from zepto8 sfx.cpp (wtfpl license)
+int16_t Audio::getSampleForChannel(int channel){
+    using std::fabs, std::fmod, std::floor, std::max;
+
+    int const samples_per_second = 22050;
+
+    int16_t sample = 0;
+
+    const int index = _sfxChannels[channel].sfxId;
+
+    if (index < 0 || index > 63) {
+        //no (valid) sfx here. return silence
+        return 0;
+    }
+
+    struct sfx const &sfx = _sfx[index];
+
+    // Speed must be 1—255 otherwise the SFX is invalid
+    int const speed = max(1, (int)sfx.speed);
+
+    float const offset = _sfxChannels[channel].offset;
+    float const phi = _sfxChannels[channel].phi;
+
+    // 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 = 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 && _sfxChannels[channel].can_loop) {
+        next_offset = fmod(next_offset - sfx.loopRangeStart, loop_range)
+                    + sfx.loopRangeStart;
+    }
+
+    int const note_id = (int)floor(offset);
+    int const next_note_id = (int)floor(next_offset);
+
+    uint8_t key = sfx.notes[note_id].pitch;
+    float volume = sfx.notes[note_id].volume / 7.f;
+    float freq = key_to_freq(key);
+
+    if (volume == 0.f){
+        //volume all the way off. return silence, but make sure to set stuff
+        _sfxChannels[channel].offset = next_offset;
+
+        if (next_offset >= 32.f){
+            _sfxChannels[channel].sfxId = -1;
+        }
+        else if (next_note_id != note_id){
+            _sfxChannels[channel].prev_key = sfx.notes[note_id].pitch;
+            _sfxChannels[channel].prev_vol = sfx.notes[note_id].volume / 7.f;
+        }
+
+        return 0;
+    }
+
+    //TODO: apply effects
+    //int const fx = sfx.notes[note_id].effect;
+
+
+
+    // Play note
+
+    float waveform = z8::synth::waveform(sfx.notes[note_id].waveform, phi);
+
+    // Apply master music volume from fade in/out
+    // FIXME: check whether this should be done after distortion
+    //if (m_state.channels[chan].is_music) {
+    //    volume *= m_state.music.volume;
+    //}
+
+    sample = (int16_t)(32767.99f * volume * waveform);
+
+    // TODO: Apply hardware effects
+    //if (m_ram.hw_state.distort & (1 << chan)) {
+    //    sample = sample / 0x1000 * 0x1249;
+    //}
+
+    _sfxChannels[channel].phi = phi + freq / samples_per_second;
+
+    _sfxChannels[channel].offset = next_offset;
+
+    if (next_offset >= 32.f){
+        _sfxChannels[channel].sfxId = -1;
+    }
+    else if (next_note_id != note_id){
+        _sfxChannels[channel].prev_key = sfx.notes[note_id].pitch;
+        _sfxChannels[channel].prev_vol = sfx.notes[note_id].volume / 7.f;
+    }
+
+    return sample;
+}
diff --git a/source/Audio.h b/source/Audio.h
index acd6ef9..05d3f7b 100644
--- a/source/Audio.h
+++ b/source/Audio.h
@@ -127,13 +127,18 @@ class Audio {

     musicChannel _musicChannel;
     sfxChannel _sfxChannels[4];
+
+    int16_t getSampleForChannel(int channel);

     public:
+    Audio();

     void setSfx(std::string sfxString);
     void setMusic(std::string musicString);

     void api_sfx(uint8_t sfx, int channel, int offset);
     void api_music(uint8_t pattern, int16_t fade_len, int16_t mask);
+
+    void FillAudioBuffer(void *audioBuffer,size_t offset, size_t size);
 };

diff --git a/source/cart.cpp b/source/cart.cpp
index 69d47a8..c184926 100644
--- a/source/cart.cpp
+++ b/source/cart.cpp
@@ -127,7 +127,7 @@ Cart::Cart(std::string filename){
     const char * patched = getPatchedLua(LuaString.c_str());

     LuaString = patched;
-
+

     #if _TEST
     //run tests to make sure cart is parsed correctly
diff --git a/source/console.cpp b/source/console.cpp
index 08ab431..e0738cf 100644
--- a/source/console.cpp
+++ b/source/console.cpp
@@ -34,7 +34,7 @@ Console::Console(){

     //this can probably go away when I'm loading actual carts and just have to expose api to lua
     Logger::Write("Initializing global api\n");
-    initPicoApi(_graphics, _input, this);
+    initPicoApi(_graphics, _input, this, _audio);
     //initGlobalApi(_graphics);

     _targetFps = 30;
@@ -249,29 +249,9 @@ void Console::FlipBuffer_SAO(
     }
 }

-//todo: figure out where to store this
-#define SAMPLERATE 22050
-//----------------------------------------------------------------------------
-void fill_buffer(void *audioBuffer,size_t offset, size_t size, int frequency ) {
-//----------------------------------------------------------------------------

-	uint32_t *dest = (uint32_t*)audioBuffer;
-
-	for (size_t i=0; i<size; i++) {
-
-		int16_t sample = INT16_MAX * sin(frequency*(2*M_PI)*(offset+i)/SAMPLERATE);
-
-		dest[i] = (sample<<16) | (sample & 0xffff);
-	}
-}
-
-void Console::FillAudioBuffer(void *audioBuffer,size_t offset, size_t size){
-    int frequency = 0;
-    if (_input->btn(4)) {
-        frequency = 440;
-    }
-
-    fill_buffer(audioBuffer, offset, size, frequency);
+void Console::FillAudioBuffer(void *audioBuffer, size_t offset, size_t size){
+   _audio->FillAudioBuffer(audioBuffer, offset, size);
 }


diff --git a/source/main.cpp b/source/main.cpp
index ecba6b8..6f5b664 100644
--- a/source/main.cpp
+++ b/source/main.cpp
@@ -206,7 +206,7 @@ int main(int argc, char* argv[])
 	Logger::Write("Cart Loaded\n");

 	#else
-	console->LoadCart("testcart.p8");
+	console->LoadCart("twosfx.p8");
 	#endif

 	// Main loop
diff --git a/source/picoluaapi.cpp b/source/picoluaapi.cpp
index 7ea825b..d080c65 100644
--- a/source/picoluaapi.cpp
+++ b/source/picoluaapi.cpp
@@ -15,11 +15,13 @@ extern "C" {
 Graphics* _graphicsForLuaApi;
 Input* _inputForLuaApi;
 Console* _consoleForLuaApi;
+Audio* _audioForLuaApi;

-void initPicoApi(Graphics* graphics, Input* input, Console* console){
+void initPicoApi(Graphics* graphics, Input* input, Console* console, Audio* audio){
     _graphicsForLuaApi = graphics;
     _inputForLuaApi = input;
     _consoleForLuaApi = console;
+    _audioForLuaApi = audio;
 }

 int noop(const char * name) {
@@ -555,7 +557,18 @@ int music(lua_State *L) {
 }

 int sfx(lua_State *L) {
-    return noop("sfx");
+    double n = lua_tonumber(L,1);
+    short channel = -1;
+    if (lua_gettop(L) > 1) {
+        channel = (short)lua_tonumber(L, 2);
+    }
+    short offset = 0;
+    if (lua_gettop(L) > 2) {
+        offset = (short)lua_tonumber(L, 3);
+    }
+
+    _audioForLuaApi->api_sfx((short)n, channel, offset);
+    return 0;
 }

 //Memory
diff --git a/source/picoluaapi.h b/source/picoluaapi.h
index 0e714ab..6b3bf2f 100644
--- a/source/picoluaapi.h
+++ b/source/picoluaapi.h
@@ -13,7 +13,7 @@ extern "C" {
 #include "console.h"

 //this can probably go away when I'm loading actual carts and just have to expose api to lua
-void initPicoApi(Graphics* graphics, Input* input, Console* console);
+void initPicoApi(Graphics* graphics, Input* input, Console* console, Audio* audio);

 //graphics api
 int cls(lua_State *L);
diff --git a/source/synth.cpp b/source/synth.cpp
new file mode 100644
index 0000000..c807bd2
--- /dev/null
+++ b/source/synth.cpp
@@ -0,0 +1,84 @@
+//
+//  ZEPTO-8 — Fantasy console emulator
+//
+//  Copyright © 2017—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.
+//
+
+#include "synth.h"
+
+//#include <lol/noise> // lol::perlin_noise
+#include <cmath>     // std::fabs, std::fmod
+
+namespace z8
+{
+
+float synth::waveform(int instrument, float advance)
+{
+    using std::fabs, std::fmod;
+
+    float t = fmod(advance, 1.f);
+    float ret = 0.f;
+
+    // Multipliers were measured from PICO-8 WAV exports. Waveforms are
+    // inferred from those exports by guessing what the original formulas
+    // could be.
+    switch (instrument)
+    {
+        case INST_TRIANGLE:
+            return 0.5f * (fabs(4.f * t - 2.0f) - 1.0f);
+        case INST_TILTED_SAW:
+        {
+            static float const a = 0.9f;
+            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);
+        case INST_SQUARE:
+            return t < 0.5f ? 0.25f : -0.25f;
+        case INST_PULSE:
+            return t < 1.f / 3 ? 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);
+            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));
+
+            return ret * 0.4f;
+        }
+        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);
+            return ret / 6.f;
+        }
+    }
+
+    return 0.0f;
+}
+
+} // namespace z8
+
diff --git a/source/synth.h b/source/synth.h
new file mode 100644
index 0000000..c299e9c
--- /dev/null
+++ b/source/synth.h
@@ -0,0 +1,41 @@
+//
+//  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
+{
+
+//
+// A waveform generator
+//
+
+class synth
+{
+public:
+    enum
+    {
+        INST_TRIANGLE   = 0, // Triangle signal
+        INST_TILTED_SAW = 1, // Slanted triangle
+        INST_SAW        = 2, // Sawtooth
+        INST_SQUARE     = 3, // Square signal
+        INST_PULSE      = 4, // Asymmetric square signal
+        INST_ORGAN      = 5, // Some triangle stuff again
+        INST_NOISE      = 6,
+        INST_PHASER     = 7,
+    };
+
+    static float waveform(int instrument, float advance);
+};
+
+} // namespace z8
+