Преглед изворни кода

Merge branch 'feature/fpc190m-codec'

# Conflicts:
#	scripts/build-local.sh
Ka1-S пре 3 недеља
родитељ
комит
f18bb38ea2
9 измењених фајлова са 955 додато и 81 уклоњено
  1. 1 0
      CMakeLists.txt
  2. 11 0
      docs/analise/REA_rodada9.md
  3. 0 0
      scripts/build-local.sh
  4. 0 0
      scripts/build-windows-zig.sh
  5. 38 81
      src/core/FlSamplers.cpp
  6. 519 0
      src/core/Fpc.cpp
  7. 133 0
      src/core/Fpc.h
  8. 251 0
      tests/Fpc190mTests.inc
  9. 2 0
      tests/tests.cpp

+ 1 - 0
CMakeLists.txt

@@ -92,6 +92,7 @@ add_library(lynx_core STATIC
     src/core/FlEffects.cpp
     src/core/Effector.cpp
     src/core/FlSamplers.cpp
+    src/core/Fpc.cpp
     src/core/FlSynths.cpp
     src/core/FlSytrus.cpp
     src/core/FlGenerators.cpp

+ 11 - 0
docs/analise/REA_rodada9.md

@@ -78,6 +78,17 @@ Top-level chunks (`FUN_0086d4c0`):
 Old versions (< 0xF424B) stored a pad counter and one block per pad without chunks
 (`FUN_0086c5e0`); they do not appear in the demos.
 
+**Versions in FL 2026's own files (round 190m) [DATA]:** 65 states in `Data` — `0x1E84E403` (2,000,100; 61 states),
+`0x1E848E` (2,000,014; 4 `.fst` kits) and `0xF424B` (1,000,011; the five kits in `System/FL Mobile/Instruments`).
+All three use the `id:u32 size:u64` container. What changes at 2,000,014 is the **text**: pad names, layer paths and
+the loop name are UTF-16LE from there on and one byte per character in 1,000,011 (this corrects the note above about
+chunk sizes). Every state has the same chunk order: 32 × `2`, then `1`, `3`, `5`, `4` (each optional); a pad is
+`0x64 0x65 0x66`, its layers, `0x67 0x68` twice, `0x6A`; a pad without a sample still has one layer with an empty
+path. `src/core/Fpc.{h,cpp}` reads and writes all of them byte for byte (test
+`fpc190m_fl_kits_and_projects_round_trip_byte_for_byte`), and `Empty.fst` is `fpc::emptyKit()`. Envelope blob:
+`u32 1, u32 3, u32 n`, `n × 24` bytes, 36-byte tail, in all 4,160 envelopes; the pan envelope has **one** point
+(0, 0.5, tension 0.2) by default, the volume envelope four.
+
 ### 1.2 Pad (chunk `2`, reader/writer `FUN_0086cc50`)
 
 | id | Size | Content |

Разлика између датотеке није приказан због своје велике величине
+ 0 - 0
scripts/build-local.sh


Разлика између датотеке није приказан због своје велике величине
+ 0 - 0
scripts/build-windows-zig.sh


+ 38 - 81
src/core/FlSamplers.cpp

@@ -1,5 +1,7 @@
 #include "core/FlSamplers.h"
 
+#include "core/Fpc.h"
+
 #include <algorithm>
 #include <cctype>
 #include <cmath>
@@ -64,34 +66,6 @@ std::string ascii (const Chunk& c)
     return s;
 }
 
-std::string utf16 (const Chunk& c)
-{
-    std::string out;
-
-    for (std::size_t i = 0; i + 1 < c.size; i += 2)
-    {
-        const auto ch = (std::uint32_t) c.data[i] | ((std::uint32_t) c.data[i + 1] << 8);
-
-        if (ch == 0)
-            break;
-        if (ch < 0x80)
-            out += (char) ch;
-        else if (ch < 0x800)
-        {
-            out += (char) (0xC0 | (ch >> 6));
-            out += (char) (0x80 | (ch & 0x3F));
-        }
-        else
-        {
-            out += (char) (0xE0 | (ch >> 12));
-            out += (char) (0x80 | ((ch >> 6) & 0x3F));
-            out += (char) (0x80 | (ch & 0x3F));
-        }
-    }
-
-    return out;
-}
-
 double l11 (double x) // (11^x − 1)/10: FL's volume curves
 {
     return (std::pow (11.0, std::clamp (x, 0.0, 2.0)) - 1.0) / 10.0;
@@ -109,73 +83,56 @@ float fpcVolume (int v)
 
 std::optional<std::vector<DrumPad>> fpcPads (const std::vector<std::uint8_t>& d)
 {
-    if (d.size() < 16)
-        return std::nullopt;
+    const auto kit = fpc::read (d);
 
-    std::uint32_t version = 0;
-    std::memcpy (&version, d.data(), 4);
-
-    if (version < 0xF424B || version > 0x1E84E403) // old formats without chunks: not handled
+    if (! kit)
         return std::nullopt;
 
-    std::vector<DrumPad> pads;
+    // as the importer always read FPC's strings: up to a NUL
+    const auto text = [] (std::u16string s) {
+        s.erase (std::find (s.begin(), s.end(), u'\0'), s.end());
+        return fpc::toUtf8 (s);
+    };
 
-    forEachChunk (d.data() + 4, d.size() - 4, [&] (const Chunk& top) {
-        if (top.id != 2) // pad
-            return;
+    std::vector<DrumPad> pads;
 
+    for (const auto& source : kit->pads)
+    {
         DrumPad pad;
-        bool muted = false;
-
-        forEachChunk (top.data, top.size, [&] (const Chunk& c) {
-            if (c.id == 0x64) // 16 × i32 parameters
-            {
-                // FPC's own law, and the constant 1/(2·√2) its output carries (measured against FL's renders of
-                // pad / layer volume and pan variants of FL's render test, REA_rodada170i §7)
-                pad.gain = fpcVolume (std::clamp (i32 (c, 0), 0, 128)) * 0.35355339059327373f;
-                pad.pan = std::clamp (i32 (c, 1), -128, 128) / 128.0f;
-                muted = (i32 (c, 2) & 1) != 0;
-                pad.key = std::clamp (i32 (c, 3), 0, 127);
-                pad.mixerOffset = std::clamp (i32 (c, 4), -99, 103);
-                pad.cutGroup = i32 (c, 5) >= 0 ? i32 (c, 5) + 1 : 0; // −1 = none; 0 becomes group 1
-                pad.cutBy = i32 (c, 6) >= 0 ? i32 (c, 6) + 1 : 0;
-                pad.tune = std::clamp (i32 (c, 7), -128, 128) * 9.375f / 100.0f;
-            }
-            else if (c.id == 0x65)
-                pad.name = utf16 (c);
-            else if (c.id == 0x69) // layer
-            {
-                SampleZone layer;
-                bool hasPath = false;
+        // FPC's own law, and the constant 1/(2·√2) its output carries (measured against FL's renders of
+        // pad / layer volume and pan variants of FL's render test, REA_rodada170i §7)
+        pad.gain = fpcVolume (std::clamp (source.volume, 0, 128)) * 0.35355339059327373f;
+        pad.pan = std::clamp (source.pan, -128, 128) / 128.0f;
+        pad.key = std::clamp (source.note, 0, 127);
+        pad.mixerOffset = std::clamp (source.output, -99, 103);
+        pad.cutGroup = source.cut >= 0 ? source.cut + 1 : 0; // −1 = none; 0 becomes group 1
+        pad.cutBy = source.cutBy >= 0 ? source.cutBy + 1 : 0;
+        pad.tune = std::clamp (source.tune, -128, 128) * 9.375f / 100.0f;
+        pad.name = text (source.name);
+
+        for (const auto& from : source.layers)
+        {
+            SampleZone layer;
+            layer.path = text (from.path);
 
-                forEachChunk (c.data, c.size, [&] (const Chunk& l) {
-                    if (l.id == 0x12C)
-                    {
-                        layer.path = utf16 (l);
-                        hasPath = ! layer.path.empty();
-                    }
-                    else if (l.id == 0x12D)
-                    {
-                        layer.gain = fpcVolume (std::clamp (i32 (l, 0), 0, 127));
-                        layer.lowVelocity = std::clamp (i32 (l, 2), 0, 127);
-                        const auto high = std::clamp (i32 (l, 3), 0, 127); // exclusive, except 127
-                        layer.highVelocity = high >= 127 ? 127 : std::max (layer.lowVelocity, high - 1);
-                        layer.tune = std::clamp (i32 (l, 5), -128, 128) * 9.375f / 100.0f;
-                    }
-                });
+            if (layer.path.empty())
+                continue;
 
-                if (hasPath)
-                    pad.layers.push_back (std::move (layer));
-            }
-        });
+            layer.gain = fpcVolume (std::clamp (from.volume, 0, 127));
+            layer.lowVelocity = std::clamp (from.velocityLow, 0, 127);
+            const auto high = std::clamp (from.velocityHigh, 0, 127); // exclusive, except 127
+            layer.highVelocity = high >= 127 ? 127 : std::max (layer.lowVelocity, high - 1);
+            layer.tune = std::clamp (from.tune, -128, 128) * 9.375f / 100.0f;
+            pad.layers.push_back (std::move (layer));
+        }
 
-        if (! pad.layers.empty() && ! muted)
+        if (! pad.layers.empty() && ! source.muted())
         {
             if (pad.name.empty())
                 pad.name = "Pad " + std::to_string (pads.size() + 1);
             pads.push_back (std::move (pad));
         }
-    });
+    }
 
     if (pads.empty())
         return std::nullopt;

+ 519 - 0
src/core/Fpc.cpp

@@ -0,0 +1,519 @@
+#include "core/Fpc.h"
+
+#include <algorithm>
+#include <cstring>
+
+namespace lynx::fpc
+{
+namespace
+{
+// Chunk ids (REA_rodada9 §1.1–1.4)
+constexpr std::uint32_t idLoop = 1, idPad = 2, idOption3 = 3, idUiState = 4, idOption5 = 5;
+constexpr std::uint32_t idPadParams = 0x64, idPadName = 0x65, idPadTrigger = 0x66, idEnvIndex = 0x67, idEnvBody = 0x68,
+                        idLayer = 0x69, idPadEnd = 0x6A;
+constexpr std::uint32_t idLayerPath = 0x12C, idLayerParams = 0x12D, idLayerEnd = 0x12E;
+
+constexpr std::size_t envelopeHead = 12, envelopePoint = 24, envelopeTail = 36;
+
+// Text is UTF-16 from version 2,000,014 on (FL's own kits: 2,000,014 and 2,000,100) and one byte per character
+// before (FL Mobile's instrument kits: 1,000,011). A version of 0x200000 or more carries a build byte below the
+// number (0x1E84E403 = 2,000,100, build 3). Chunk sizes are 64-bit in all of them.
+bool wideText (std::uint32_t version) noexcept
+{
+    return (version >= 0x200000 ? version >> 8 : version) >= 2000014;
+}
+
+struct View
+{
+    std::uint32_t id = 0;
+    const std::uint8_t* data = nullptr;
+    std::size_t size = 0;
+};
+
+// The chunks of a container, in order. Stops at a chunk that runs past the end.
+std::vector<View> chunksOf (const std::uint8_t* p, std::size_t n)
+{
+    std::vector<View> out;
+    constexpr std::size_t head = 12;
+    std::size_t pos = 0;
+
+    while (pos + head <= n)
+    {
+        View c;
+        std::uint64_t size = 0;
+        std::memcpy (&c.id, p + pos, 4);
+
+        std::memcpy (&size, p + pos + 4, 8);
+        pos += head;
+
+        if (size > n - pos)
+            break;
+
+        c.data = p + pos;
+        c.size = (std::size_t) size;
+        out.push_back (c);
+        pos += c.size;
+    }
+
+    return out;
+}
+
+std::vector<std::uint8_t> bytesOf (const View& c)
+{
+    return c.size == 0 ? std::vector<std::uint8_t>() : std::vector<std::uint8_t> (c.data, c.data + c.size);
+}
+
+std::u16string textOf (const View& c, bool wide)
+{
+    if (! wide)
+        return std::u16string (c.data, c.data + c.size); // each byte as its own character
+
+    std::u16string s (c.size / 2, u'\0');
+
+    for (std::size_t i = 0; i < s.size(); ++i)
+        s[i] = (char16_t) ((std::uint32_t) c.data[i * 2] | ((std::uint32_t) c.data[i * 2 + 1] << 8));
+
+    return s;
+}
+
+std::vector<std::int32_t> intsOf (const View& c)
+{
+    std::vector<std::int32_t> v (c.size / 4);
+    if (! v.empty())
+        std::memcpy (v.data(), c.data, v.size() * 4);
+    return v;
+}
+
+RawChunk rawOf (const View& c, int position)
+{
+    return { position, c.id, bytesOf (c) };
+}
+
+void readEnvelopeBody (const View& c, Envelope& e)
+{
+    std::uint32_t count = 0;
+
+    if (c.size >= envelopeHead + envelopeTail)
+        std::memcpy (&count, c.data + 8, 4);
+
+    if (c.size < envelopeHead + envelopeTail || (c.size - envelopeHead - envelopeTail) / envelopePoint != count
+        || (c.size - envelopeHead - envelopeTail) % envelopePoint != 0)
+    {
+        e.unparsed = bytesOf (c);
+        return;
+    }
+
+    std::memcpy (&e.headA, c.data, 4);
+    std::memcpy (&e.headB, c.data + 4, 4);
+    e.points.resize (count);
+
+    for (std::size_t i = 0; i < count; ++i)
+    {
+        const auto* p = c.data + envelopeHead + i * envelopePoint;
+        std::memcpy (&e.points[i].time, p, 8);
+        std::memcpy (&e.points[i].value, p + 8, 8);
+        std::memcpy (&e.points[i].tension, p + 16, 4);
+        std::memcpy (&e.points[i].type, p + 20, 4);
+    }
+
+    std::memcpy (e.tail.data(), c.data + envelopeHead + count * envelopePoint, envelopeTail);
+}
+
+Layer readLayer (const View& chunk, bool wide)
+{
+    Layer layer;
+    const auto list = chunksOf (chunk.data, chunk.size);
+    bool hasPath = false, hasParams = false;
+
+    for (std::size_t i = 0; i < list.size(); ++i)
+    {
+        const auto& c = list[i];
+
+        if (c.id == idLayerPath && ! hasPath && (! wide || c.size % 2 == 0))
+        {
+            layer.path = textOf (c, wide);
+            hasPath = true;
+        }
+        else if (c.id == idLayerParams && ! hasParams && c.size >= 28 && c.size % 4 == 0)
+        {
+            const auto v = intsOf (c);
+            layer.volume = v[0];
+            layer.pan = v[1];
+            layer.velocityLow = v[2];
+            layer.velocityHigh = v[3];
+            layer.flags = v[4];
+            layer.tune = v[5];
+            layer.region = v[6];
+            layer.moreParams.assign (v.begin() + 7, v.end());
+            hasParams = true;
+        }
+        else if (c.id == idLayerEnd && c.size == 0 && i + 1 == list.size())
+        {
+        }
+        else
+            layer.extra.push_back (rawOf (c, (int) i));
+    }
+
+    return layer;
+}
+
+Pad readPad (const View& chunk, bool wide)
+{
+    Pad pad;
+    const auto list = chunksOf (chunk.data, chunk.size);
+    bool hasParams = false, hasName = false, hasTrigger = false, envelopeOpen = false;
+
+    for (std::size_t i = 0; i < list.size(); ++i)
+    {
+        const auto& c = list[i];
+
+        if (c.id == idPadParams && ! hasParams && c.size >= 64 && c.size % 4 == 0)
+        {
+            const auto v = intsOf (c);
+            pad.volume = v[0];
+            pad.pan = v[1];
+            pad.flags = v[2];
+            pad.note = v[3];
+            pad.output = v[4];
+            pad.cut = v[5];
+            pad.cutBy = v[6];
+            pad.tune = v[7];
+            pad.colour = v[8];
+            pad.icon = v[9];
+            std::copy (v.begin() + 10, v.begin() + 16, pad.reserved.begin());
+            pad.moreParams.assign (v.begin() + 16, v.end());
+            hasParams = true;
+        }
+        else if (c.id == idPadName && ! hasName && (! wide || c.size % 2 == 0))
+        {
+            pad.name = textOf (c, wide);
+            hasName = true;
+        }
+        else if (c.id == idPadTrigger && ! hasTrigger && c.size == 32)
+        {
+            std::memcpy (pad.trigger.data(), c.data, 32);
+            hasTrigger = true;
+        }
+        else if (c.id == idLayer && pad.envelopes.empty())
+            pad.layers.push_back (readLayer (c, wide));
+        else if (c.id == idEnvIndex && c.size == 8 && ! envelopeOpen)
+        {
+            Envelope e;
+            std::memcpy (&e.index, c.data, 4);
+            std::memcpy (&e.indexReserved, c.data + 4, 4);
+            pad.envelopes.push_back (std::move (e));
+            envelopeOpen = true;
+        }
+        else if (c.id == idEnvBody && envelopeOpen)
+        {
+            readEnvelopeBody (c, pad.envelopes.back());
+            envelopeOpen = false;
+        }
+        else if (c.id == idPadEnd && c.size == 0 && i + 1 == list.size())
+        {
+        }
+        else
+            pad.extra.push_back (rawOf (c, (int) i));
+    }
+
+    return pad;
+}
+
+// ---------------------------------------------------------------------------------------------------------------
+// Writing
+
+using Bytes = std::vector<std::uint8_t>;
+
+struct Item
+{
+    std::uint32_t id = 0;
+    Bytes body;
+};
+
+template <typename T>
+void put (Bytes& out, const T& value)
+{
+    const auto* p = reinterpret_cast<const std::uint8_t*> (&value);
+    out.insert (out.end(), p, p + sizeof (T));
+}
+
+Bytes textBytes (const std::u16string& s, bool wide)
+{
+    Bytes out;
+    out.reserve (s.size() * 2);
+
+    for (const auto ch : s)
+    {
+        if (wide)
+        {
+            out.push_back ((std::uint8_t) (ch & 0xFF));
+            out.push_back ((std::uint8_t) (ch >> 8));
+        }
+        else
+            out.push_back (ch < 0x100 ? (std::uint8_t) ch : (std::uint8_t) '?');
+    }
+
+    return out;
+}
+
+// The known chunks in FL's order, with the unknown ones put back at the index they were read at
+Bytes container (std::vector<Item> items, const std::vector<RawChunk>& extra)
+{
+    for (const auto& x : extra)
+        items.insert (items.begin() + std::clamp (x.position, 0, (int) items.size()), Item { x.id, x.body });
+
+    Bytes out;
+
+    for (const auto& item : items)
+    {
+        put (out, item.id);
+        put (out, (std::uint64_t) item.body.size());
+
+        out.insert (out.end(), item.body.begin(), item.body.end());
+    }
+
+    return out;
+}
+
+Bytes layerBytes (const Layer& layer, bool wide)
+{
+    Bytes params;
+    for (const auto v : { layer.volume, layer.pan, layer.velocityLow, layer.velocityHigh, layer.flags, layer.tune, layer.region })
+        put (params, v);
+    for (const auto v : layer.moreParams)
+        put (params, v);
+
+    return container ({ { idLayerPath, textBytes (layer.path, wide) }, { idLayerParams, std::move (params) }, { idLayerEnd, {} } }, layer.extra);
+}
+
+Bytes envelopeBytes (const Envelope& e)
+{
+    if (! e.unparsed.empty())
+        return e.unparsed;
+
+    Bytes out;
+    put (out, e.headA);
+    put (out, e.headB);
+    put (out, (std::uint32_t) e.points.size());
+
+    for (const auto& p : e.points)
+    {
+        put (out, p.time);
+        put (out, p.value);
+        put (out, p.tension);
+        put (out, p.type);
+    }
+
+    for (const auto v : e.tail)
+        put (out, v);
+
+    return out;
+}
+
+Bytes padBytes (const Pad& pad, bool wide)
+{
+    Bytes params;
+    for (const auto v : { pad.volume, pad.pan, pad.flags, pad.note, pad.output, pad.cut, pad.cutBy, pad.tune, pad.colour, pad.icon })
+        put (params, v);
+    for (const auto v : pad.reserved)
+        put (params, v);
+    for (const auto v : pad.moreParams)
+        put (params, v);
+
+    Bytes trigger;
+    for (const auto v : pad.trigger)
+        put (trigger, v);
+
+    std::vector<Item> items { { idPadParams, std::move (params) }, { idPadName, textBytes (pad.name, wide) }, { idPadTrigger, std::move (trigger) } };
+
+    for (const auto& layer : pad.layers)
+        items.push_back ({ idLayer, layerBytes (layer, wide) });
+
+    for (const auto& e : pad.envelopes)
+    {
+        Bytes index;
+        put (index, e.index);
+        put (index, e.indexReserved);
+        items.push_back ({ idEnvIndex, std::move (index) });
+        items.push_back ({ idEnvBody, envelopeBytes (e) });
+    }
+
+    items.push_back ({ idPadEnd, {} });
+    return container (std::move (items), pad.extra);
+}
+} // namespace
+
+std::optional<Kit> read (const std::vector<std::uint8_t>& state)
+{
+    if (state.size() < 16)
+        return std::nullopt;
+
+    Kit kit;
+    std::memcpy (&kit.version, state.data(), 4);
+
+    if (kit.version < oldestVersion || kit.version > newestVersion)
+        return std::nullopt;
+
+    const bool wide = wideText (kit.version);
+    const auto list = chunksOf (state.data() + 4, state.size() - 4);
+    bool afterPads = false;
+
+    for (std::size_t i = 0; i < list.size(); ++i)
+    {
+        const auto& c = list[i];
+
+        if (c.id == idPad && ! afterPads)
+        {
+            kit.pads.push_back (readPad (c, wide));
+            continue;
+        }
+
+        if (c.id == idLoop && ! kit.midiLoop && (! wide || c.size % 2 == 0) && ! kit.option3 && ! kit.option5 && ! kit.uiState)
+            kit.midiLoop = textOf (c, wide);
+        else if (c.id == idOption3 && ! kit.option3 && ! kit.option5 && ! kit.uiState)
+            kit.option3 = bytesOf (c);
+        else if (c.id == idOption5 && ! kit.option5 && ! kit.uiState)
+            kit.option5 = bytesOf (c);
+        else if (c.id == idUiState && ! kit.uiState)
+            kit.uiState = bytesOf (c);
+        else
+            kit.extra.push_back (rawOf (c, (int) i));
+
+        afterPads = true;
+    }
+
+    return kit;
+}
+
+std::vector<std::uint8_t> write (const Kit& kit)
+{
+    const bool wide = wideText (kit.version);
+    std::vector<Item> items;
+
+    for (const auto& pad : kit.pads)
+        items.push_back ({ idPad, padBytes (pad, wide) });
+
+    if (kit.midiLoop)
+        items.push_back ({ idLoop, textBytes (*kit.midiLoop, wide) });
+    if (kit.option3)
+        items.push_back ({ idOption3, *kit.option3 });
+    if (kit.option5)
+        items.push_back ({ idOption5, *kit.option5 });
+    if (kit.uiState)
+        items.push_back ({ idUiState, *kit.uiState });
+
+    Bytes out;
+    put (out, kit.version);
+    const auto body = container (std::move (items), kit.extra);
+    out.insert (out.end(), body.begin(), body.end());
+    return out;
+}
+
+Kit emptyKit()
+{
+    // FL's Empty.fst (FL Studio 2026)
+    static constexpr int notes[32] = { 37, 36, 42, 54, 40, 38, 46, 44, 48, 47, 45, 43, 49, 55, 51, 53,
+                                       60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75 };
+    Envelope volume;
+    volume.index = 0;
+    volume.points = { { 0.0, 0.0, 0.0f, 0 }, { 0.75, 1.0, 0.2f, 0x1000000 }, { 1.5, 0.5, 0.2f, 0x1000000 }, { 0.25, 0.0, 0.2f, 0x1000000 } };
+    volume.tail = { 0, 0, 1, -1, 2, 128, 128, 0, 128 };
+
+    Envelope pan;
+    pan.index = 1;
+    pan.points = { { 0.0, 0.5, 0.2f, 0 } };
+
+    Kit kit;
+
+    for (const int note : notes)
+    {
+        Pad pad;
+        pad.note = note;
+        pad.layers.emplace_back();
+        pad.envelopes = { volume, pan };
+        kit.pads.push_back (std::move (pad));
+    }
+
+    kit.midiLoop = u"World Loops\\Polka\\fpc_polka_10.mid";
+    kit.option3 = std::vector<std::uint8_t> { 1 };
+    kit.uiState = std::vector<std::uint8_t> (32, 0);
+    return kit;
+}
+
+std::string toUtf8 (const std::u16string& text)
+{
+    std::string out;
+
+    for (std::size_t i = 0; i < text.size(); ++i)
+    {
+        std::uint32_t ch = text[i];
+
+        if (ch >= 0xD800 && ch < 0xDC00 && i + 1 < text.size() && text[i + 1] >= 0xDC00 && text[i + 1] < 0xE000)
+            ch = 0x10000 + ((ch - 0xD800) << 10) + ((std::uint32_t) text[++i] - 0xDC00);
+
+        if (ch < 0x80)
+            out += (char) ch;
+        else if (ch < 0x800)
+        {
+            out += (char) (0xC0 | (ch >> 6));
+            out += (char) (0x80 | (ch & 0x3F));
+        }
+        else if (ch < 0x10000)
+        {
+            out += (char) (0xE0 | (ch >> 12));
+            out += (char) (0x80 | ((ch >> 6) & 0x3F));
+            out += (char) (0x80 | (ch & 0x3F));
+        }
+        else
+        {
+            out += (char) (0xF0 | (ch >> 18));
+            out += (char) (0x80 | ((ch >> 12) & 0x3F));
+            out += (char) (0x80 | ((ch >> 6) & 0x3F));
+            out += (char) (0x80 | (ch & 0x3F));
+        }
+    }
+
+    return out;
+}
+
+std::u16string fromUtf8 (const std::string& text)
+{
+    std::u16string out;
+    std::size_t i = 0;
+
+    while (i < text.size())
+    {
+        const auto b = (std::uint8_t) text[i];
+        const int extra = b < 0x80 ? 0 : (b >> 5) == 6 ? 1 : (b >> 4) == 14 ? 2 : (b >> 3) == 30 ? 3 : -1;
+        std::uint32_t ch = extra == 0 ? b : extra == 1 ? (b & 0x1Fu) : extra == 2 ? (b & 0x0Fu) : (b & 0x07u);
+        bool ok = extra >= 0 && i + (std::size_t) extra < text.size();
+
+        for (int k = 1; ok && k <= extra; ++k)
+        {
+            const auto c = (std::uint8_t) text[i + (std::size_t) k];
+            ok = (c >> 6) == 2;
+            ch = (ch << 6) | (c & 0x3Fu);
+        }
+
+        if (! ok || ch > 0x10FFFF)
+        {
+            out += (char16_t) 0xFFFD;
+            ++i;
+            continue;
+        }
+
+        i += (std::size_t) extra + 1;
+
+        if (ch < 0x10000)
+            out += (char16_t) ch;
+        else
+        {
+            ch -= 0x10000;
+            out += (char16_t) (0xD800 + (ch >> 10));
+            out += (char16_t) (0xDC00 + (ch & 0x3FF));
+        }
+    }
+
+    return out;
+}
+} // namespace lynx::fpc

+ 133 - 0
src/core/Fpc.h

@@ -0,0 +1,133 @@
+#pragma once
+
+// FL's FPC (pad drum sampler): its plugin state (the 0xD5 record of an .flp channel or an .fst kit), read and
+// written. Format in docs/analise/REA_rodada9.md §1 (clean-room). A state that is read and written back without
+// an edit is the same bytes: every chunk is kept, the ones LYNX does not know as raw bytes in their place.
+
+#include <array>
+#include <cstdint>
+#include <optional>
+#include <string>
+#include <vector>
+
+namespace lynx::fpc
+{
+// A chunk LYNX does not interpret. `position` is its index in the chunk list of its container, so the writer puts
+// it back where it was.
+struct RawChunk
+{
+    int position = 0;
+    std::uint32_t id = 0;
+    std::vector<std::uint8_t> body;
+
+    bool operator== (const RawChunk&) const = default;
+};
+
+struct EnvelopePoint
+{
+    double time = 0.0;  // seconds after the previous point
+    double value = 0.0; // 0…1
+    float tension = 0.0f;
+    std::uint32_t type = 0;
+
+    bool operator== (const EnvelopePoint&) const = default;
+};
+
+// A pad's volume (index 0) or pan (index 1) envelope
+struct Envelope
+{
+    std::int32_t index = 0, indexReserved = 0;        // chunk 0x67
+    std::uint32_t headA = 1, headB = 3;               // chunk 0x68: two constants, then the point count
+    std::vector<EnvelopePoint> points;
+    std::array<std::int32_t, 9> tail { 0, 0, -1, -1, -1, 128, 128, 0, 128 }; // sustain / loop points and four constants
+    std::vector<std::uint8_t> unparsed;               // the 0x68 body when it does not have that layout (then the rest is unused)
+
+    bool operator== (const Envelope&) const = default;
+};
+
+struct Layer
+{
+    std::u16string path; // with FL's variables, e.g. %FLStudioFactoryData%
+    // chunk 0x12D (7 × i32 in every state seen)
+    std::int32_t volume = 127;       // 0…127
+    std::int32_t pan = 0;            // −128…128
+    std::int32_t velocityLow = 0;    // inclusive
+    std::int32_t velocityHigh = 127; // exclusive, except 127
+    std::int32_t flags = 1;          // bit 0 always set; bit 1 = reverse (hypothesis)
+    std::int32_t tune = 0;           // −128…128, × 9.375 cents
+    std::int32_t region = -1;        // −1 = the whole sample, else the index of a region of the WAV
+    std::vector<std::int32_t> moreParams; // values after the seventh, if a later version adds some
+    std::vector<RawChunk> extra;
+
+    bool operator== (const Layer&) const = default;
+};
+
+enum class LayerMode : std::int32_t
+{
+    random = 0,
+    randomAvoidPrevious = 1,
+    cycleBackward = 2,
+    cycle = 3
+};
+
+struct Pad
+{
+    // chunk 0x64 (16 × i32)
+    std::int32_t volume = 99; // 0…128
+    std::int32_t pan = 0;     // −128…128
+    std::int32_t flags = 0;   // bit 0 mute, bit 1 solo, bit 2 (not decoded), bit 3 one layer at a time (`mode`)
+    std::int32_t note = 60;   // the MIDI note that triggers the pad
+    std::int32_t output = 0;  // mixer track offset, −99…103
+    std::int32_t cut = -1;    // group this pad cuts, −1 = none
+    std::int32_t cutBy = -1;  // group that cuts this pad, −1 = none
+    std::int32_t tune = 0;    // −128…128, × 9.375 cents
+    std::int32_t colour = 0;
+    std::int32_t icon = 0;
+    std::array<std::int32_t, 6> reserved {};
+    std::vector<std::int32_t> moreParams;
+
+    std::u16string name;                                       // chunk 0x65
+    std::array<std::int32_t, 8> trigger { 1, 0, 0, 0, 0, 0, 0, 0 }; // chunk 0x66; [0] = LayerMode
+    std::vector<Layer> layers;                                 // chunks 0x69
+    std::vector<Envelope> envelopes;                           // chunk pairs 0x67 + 0x68
+    std::vector<RawChunk> extra;
+
+    bool muted() const noexcept { return (flags & 1) != 0; }
+    bool soloed() const noexcept { return (flags & 2) != 0; }
+    bool oneLayerAtATime() const noexcept { return (flags & 8) != 0; }
+    LayerMode mode() const noexcept { return (LayerMode) trigger[0]; }
+
+    bool operator== (const Pad&) const = default;
+};
+
+struct Kit
+{
+    std::uint32_t version = 0x1E84E403;
+    std::vector<Pad> pads;                           // chunks 2: bank A = pads 0…15, bank B = 16…31
+    std::optional<std::u16string> midiLoop;          // chunk 1: the last MIDI loop chosen in the loop browser
+    std::optional<std::vector<std::uint8_t>> option3; // chunk 3 (one byte, an editor option)
+    std::optional<std::vector<std::uint8_t>> option5; // chunk 5 (one byte, an editor option)
+    std::optional<std::vector<std::uint8_t>> uiState; // chunk 4 (32 bytes, editor state)
+    std::vector<RawChunk> extra;
+
+    bool operator== (const Kit&) const = default;
+};
+
+constexpr std::uint32_t oldestVersion = 0xF424B;   // 1,000,011: the first version with chunks (FL Mobile's kits; text of one byte per character)
+constexpr std::uint32_t newestVersion = 0x1E84E403; // what FL 2026 writes
+
+// The state as a kit; nothing when it is not an FPC state LYNX can read (too short, or a version outside
+// oldestVersion…newestVersion). A chunk that runs past the end ends its list there (a cut-off state keeps the
+// pads before the cut).
+std::optional<Kit> read (const std::vector<std::uint8_t>& state);
+
+// The kit as a state. write (*read (s)) == s for every state FL writes.
+std::vector<std::uint8_t> write (const Kit& kit);
+
+// FL's "Empty" kit: 32 pads without a sample on FL's default notes (bank A the General MIDI drum notes, bank B
+// C5 upwards), each with one empty layer and FL's default envelopes.
+Kit emptyKit();
+
+std::string toUtf8 (const std::u16string& text);
+std::u16string fromUtf8 (const std::string& text);
+} // namespace lynx::fpc

+ 251 - 0
tests/Fpc190mTests.inc

@@ -0,0 +1,251 @@
+// Round 190m: FPC's state codec (issue #135) — read and written byte for byte (docs/analise/REA_rodada9.md §1)
+
+namespace fpc190m
+{
+inline void put32 (std::vector<std::uint8_t>& out, std::uint32_t v)
+{
+    for (int i = 0; i < 4; ++i)
+        out.push_back ((std::uint8_t) (v >> (8 * i)));
+}
+
+// one chunk with FL's 64-bit size
+inline void chunk (std::vector<std::uint8_t>& out, std::uint32_t id, const std::vector<std::uint8_t>& body)
+{
+    put32 (out, id);
+    put32 (out, (std::uint32_t) body.size());
+    put32 (out, 0);
+    out.insert (out.end(), body.begin(), body.end());
+}
+
+// every FPC state in a folder of FL's (.fst kits and .flp projects)
+inline std::vector<std::pair<std::string, std::vector<std::uint8_t>>> statesIn (const std::filesystem::path& folder)
+{
+    std::vector<std::pair<std::string, std::vector<std::uint8_t>>> out;
+    std::error_code error;
+    if (! std::filesystem::is_directory (folder, error))
+        return out;
+    for (const auto& entry : std::filesystem::recursive_directory_iterator (folder, std::filesystem::directory_options::skip_permission_denied, error))
+    {
+        const auto ext = entry.path().extension();
+        if (ext != ".fst" && ext != ".flp")
+            continue;
+        std::ifstream in (entry.path(), std::ios::binary);
+        const std::vector<std::uint8_t> file ((std::istreambuf_iterator<char> (in)), {});
+        try
+        {
+            for (const auto& c : flp::parseProject (file, ext == ".fst").channels)
+                if (c.pluginName == "FPC" && ! c.pluginState.empty())
+                    out.emplace_back (entry.path().filename().string(), c.pluginState);
+        }
+        catch (const std::exception&)
+        {
+        }
+    }
+    return out;
+}
+} // namespace fpc190m
+
+TEST (fpc190m_empty_kit_reads_back_as_written)
+{
+    using namespace lynx;
+    const auto kit = fpc::emptyKit();
+    CHECK (kit.pads.size() == 32);
+    const auto bytes = fpc::write (kit);
+    const auto back = fpc::read (bytes);
+    CHECK (back.has_value());
+    if (! back)
+        return;
+    CHECK (*back == kit);
+    CHECK (fpc::write (*back) == bytes);
+    CHECK (back->pads[1].note == 36 && back->pads[16].note == 60);
+    CHECK (back->pads[0].layers.size() == 1 && back->pads[0].envelopes.size() == 2);
+    CHECK (back->pads[0].envelopes[0].points.size() == 4 && back->pads[0].envelopes[1].points.size() == 1);
+    CHECK (! fpcPads (bytes).has_value()); // no pad has a sample
+}
+
+TEST (fpc190m_an_edit_is_what_the_state_carries)
+{
+    using namespace lynx;
+    auto kit = fpc::emptyKit();
+    auto& pad = kit.pads[1];
+    pad.name = fpc::fromUtf8 ("Kick \xC3\xA9 \xF0\x9F\x98\x80");
+    pad.volume = 128;
+    pad.pan = -24;
+    pad.cut = 0;
+    pad.cutBy = 3;
+    pad.tune = 64;
+    pad.output = 2;
+    pad.flags = 8;
+    pad.trigger[0] = (std::int32_t) fpc::LayerMode::cycle;
+    pad.layers[0].path = u"%FLStudioFactoryData%\\Data\\Patches\\Packs\\Drums\\Kicks\\a.wav";
+    pad.layers[0].velocityHigh = 64;
+    fpc::Layer second;
+    second.path = u"C:\\b.wav";
+    second.velocityLow = 64;
+    second.volume = 99;
+    second.tune = -12;
+    pad.layers.push_back (second);
+    pad.envelopes[0].points[1].time = 0.125;
+    const auto back = fpc::read (fpc::write (kit));
+    CHECK (back.has_value());
+    if (! back)
+        return;
+    CHECK (*back == kit);
+    CHECK (fpc::toUtf8 (back->pads[1].name) == "Kick \xC3\xA9 \xF0\x9F\x98\x80");
+    CHECK (back->pads[1].oneLayerAtATime() && back->pads[1].mode() == fpc::LayerMode::cycle);
+    // the importer's view of the same state: one pad, two velocity zones
+    const auto pads = fpcPads (fpc::write (kit));
+    CHECK (pads.has_value());
+    if (! pads)
+        return;
+    CHECK (pads->size() == 1);
+    const auto& p = pads->front();
+    CHECK (p.key == 36 && p.cutGroup == 1 && p.cutBy == 4 && p.mixerOffset == 2 && p.layers.size() == 2);
+    CHECK (std::abs (p.tune - 6.0f) < 1e-6f && std::abs (p.pan + 0.1875f) < 1e-6f);
+    CHECK (p.layers[0].lowVelocity == 0 && p.layers[0].highVelocity == 63 && p.layers[1].lowVelocity == 64 && p.layers[1].highVelocity == 127);
+    CHECK (std::abs (p.layers[1].tune + 1.125f) < 1e-6f);
+}
+
+TEST (fpc190m_chunks_lynx_does_not_know_stay_in_place)
+{
+    using namespace lynx;
+    using fpc190m::chunk;
+    using fpc190m::put32;
+    // a state with a chunk of a later version in each list: the kit, a pad and a layer; and an envelope with another layout
+    std::vector<std::uint8_t> layer, pad, state;
+    chunk (layer, 0x12C, { 'a', 0, '.', 0, 'w', 0 });
+    chunk (layer, 0x777, { 1, 2, 3 });
+    std::vector<std::uint8_t> params;
+    for (const std::uint32_t v : { 100u, 0u, 0u, 127u, 1u, 0u, 0xFFFFFFFFu, 42u }) // an eighth value
+        put32 (params, v);
+    chunk (layer, 0x12D, params);
+    chunk (layer, 0x12E, {});
+    std::vector<std::uint8_t> padParams (64, 0);
+    padParams[0] = 99;
+    padParams[12] = 38;
+    chunk (pad, 0x888, { 9 });
+    chunk (pad, 0x64, padParams);
+    chunk (pad, 0x65, { 'S', 0 });
+    chunk (pad, 0x66, std::vector<std::uint8_t> (32, 0));
+    chunk (pad, 0x69, layer);
+    chunk (pad, 0x67, { 0, 0, 0, 0, 0, 0, 0, 0 });
+    chunk (pad, 0x68, { 5, 0, 0, 0, 6 }); // not the known layout
+    chunk (pad, 0x999, {});
+    chunk (pad, 0x6A, {});
+    put32 (state, fpc::newestVersion);
+    chunk (state, 2, pad);
+    chunk (state, 1, { 'x', 0 });
+    chunk (state, 0x55, { 7, 7 });
+    chunk (state, 3, { 1 });
+    chunk (state, 4, std::vector<std::uint8_t> (32, 3));
+    const auto kit = fpc::read (state);
+    CHECK (kit.has_value());
+    if (! kit)
+        return;
+    CHECK (fpc::write (*kit) == state);
+    CHECK (kit->pads.size() == 1 && kit->extra.size() == 1 && kit->extra[0].id == 0x55);
+    const auto& p = kit->pads[0];
+    CHECK (p.note == 38 && p.volume == 99 && p.extra.size() == 2 && p.layers.size() == 1 && p.envelopes.size() == 1);
+    CHECK (p.envelopes[0].unparsed.size() == 5 && p.envelopes[0].points.empty());
+    CHECK (p.layers[0].volume == 100 && p.layers[0].region == -1 && p.layers[0].moreParams == std::vector<std::int32_t> { 42 });
+    CHECK (p.layers[0].extra.size() == 1 && fpc::toUtf8 (p.layers[0].path) == "a.w");
+    // an edit keeps them too
+    auto edited = *kit;
+    edited.pads[0].volume = 64;
+    const auto back = fpc::read (fpc::write (edited));
+    CHECK (back.has_value() && *back == edited);
+}
+
+TEST (fpc190m_versions_and_broken_states)
+{
+    using namespace lynx;
+    auto kit = fpc::emptyKit();
+    kit.pads[0].layers[0].path = u"k.wav";
+    // the versions in FL's own files: 2,000,100, 2,000,014 and FL Mobile's 1,000,011 (text of one byte per character)
+    for (const std::uint32_t version : { 0x1E84E403u, 0x1E848Eu, 0xF424Bu })
+    {
+        kit.version = version;
+        const auto bytes = fpc::write (kit);
+        const auto back = fpc::read (bytes);
+        CHECK (back.has_value() && *back == kit && fpc::write (*back) == bytes);
+    }
+    kit.version = fpc::newestVersion;
+    const auto wide = fpc::write (kit);
+    kit.version = 0xF424B;
+    CHECK (fpc::write (kit).size() < wide.size());
+    // outside the range, too short, cut off anywhere, any byte changed: no crash, and a cut keeps the pads before it
+    auto bad = wide;
+    bad[3] = 0x7F;
+    CHECK (! fpc::read (bad).has_value());
+    CHECK (! fpc::read ({ 1, 2, 3 }).has_value());
+    for (std::size_t n = 16; n < wide.size(); n += 37)
+    {
+        const std::vector<std::uint8_t> cut (wide.begin(), wide.begin() + (std::ptrdiff_t) n);
+        const auto part = fpc::read (cut);
+        CHECK (part.has_value() && part->pads.size() <= 32);
+        if (part)
+            fpc::write (*part);
+        fpcPads (cut);
+    }
+    std::uint32_t seed = 190;
+    for (int i = 0; i < 400; ++i)
+    {
+        auto flipped = wide;
+        seed = seed * 1664525u + 1013904223u;
+        flipped[4 + (seed >> 8) % (flipped.size() - 4)] = (std::uint8_t) (seed >> 24);
+        if (const auto got = fpc::read (flipped))
+            fpc::write (*got);
+        fpcPads (flipped);
+    }
+    const std::vector<std::uint8_t> head (wide.begin(), wide.begin() + 2000);
+    const auto part = fpc::read (head);
+    CHECK (part.has_value() && part->pads.size() == 3); // an empty pad is 525 bytes
+}
+
+TEST (fpc190m_fl_kits_and_projects_round_trip_byte_for_byte)
+{
+    using namespace lynx;
+    const std::filesystem::path data (realFlpDir);
+    auto states = fpc190m::statesIn (data / "Patches" / "Plugin presets" / "Generators" / "FPC");
+    const auto kits = states.size();
+    for (const auto* folder : { "Demo projects", "System", "Projects" })
+        for (auto& s : fpc190m::statesIn (data / folder))
+            states.push_back (std::move (s));
+    if (states.empty())
+        return; // no FL Studio here
+    int exact = 0, pads = 0, layers = 0;
+    for (const auto& [name, state] : states)
+    {
+        const auto kit = fpc::read (state);
+        CHECK (kit.has_value());
+        if (! kit)
+            continue;
+        const bool same = fpc::write (*kit) == state;
+        if (! same)
+            std::printf ("  FPC state of %s is not written back as read\n", name.c_str());
+        exact += same ? 1 : 0;
+        CHECK (kit->pads.size() == 32 && kit->extra.empty());
+        for (const auto& pad : kit->pads)
+        {
+            ++pads;
+            layers += (int) pad.layers.size();
+            CHECK (pad.extra.empty() && pad.envelopes.size() == 2 && pad.moreParams.empty());
+            for (const auto& e : pad.envelopes)
+                CHECK (e.unparsed.empty() && ! e.points.empty());
+            for (const auto& layer : pad.layers)
+                CHECK (layer.extra.empty() && layer.moreParams.empty());
+        }
+    }
+    std::printf ("  FPC: %d states (%d kits) with %d pads and %d layers, %d written back byte for byte\n", (int) states.size(), (int) kits, pads, layers, exact);
+    CHECK (exact == (int) states.size());
+    CHECK (kits >= 21);
+    // FL's Empty kit is LYNX's empty kit
+    std::ifstream in (data / "Patches" / "Plugin presets" / "Generators" / "FPC" / "Empty.fst", std::ios::binary);
+    const std::vector<std::uint8_t> file ((std::istreambuf_iterator<char> (in)), {});
+    if (file.empty())
+        return;
+    const auto project = flp::parseProject (file, true);
+    CHECK (project.channels.size() == 1);
+    if (project.channels.size() == 1)
+        CHECK (project.channels[0].pluginState == fpc::write (fpc::emptyKit()));
+}

+ 2 - 0
tests/tests.cpp

@@ -53,6 +53,7 @@
 #include "core/ControlSurface.h"
 #include "core/VoltageController.h"
 #include "core/FlSamplers.h"
+#include "core/Fpc.h"
 #include "core/FlSynths.h"
 #include "core/Inflate.h"
 #include "core/WavPack.h"
@@ -17362,6 +17363,7 @@ TEST (fl_low_lifter_matches_fl_engine)
 #include "Merge180cTests.inc"
 #include "Slicer180cTests.inc"
 #include "Slicer190fTests.inc"
+#include "Fpc190mTests.inc"
 #include "PluginExport180bTests.inc"
 #include "FlExport180dTests.inc"
 #include "FlpMute182eTests.inc"

Неке датотеке нису приказане због велике количине промена