DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
StateBlob.h
1// DSPark -- Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi -- MIT License
3
4#pragma once
5
35#include <algorithm>
36#include <cassert>
37#include <cmath>
38#include <cstdint>
39#include <cstdio>
40#include <cstring>
41#include <limits>
42#include <string>
43#include <vector>
44
45namespace dspark {
46
47// ============================================================================
48// StateWriter
49// ============================================================================
50
53{
54public:
59 StateWriter(uint32_t processorId, uint16_t processorVersion)
60 {
61 blob_.reserve(256);
62 append("DSPK", 4);
63 appendU16(kFormatVersion);
64 appendU32(processorId);
65 appendU16(processorVersion);
66 countPos_ = blob_.size();
67 appendU16(0); // patched by blob()
68 }
69
71 void write(const char* key, float value)
72 {
73 uint32_t bits = 0;
74 std::memcpy(&bits, &value, 4);
75 writeEntry(key, 0, bits);
76 }
77
79 void write(const char* key, int32_t value)
80 {
81 writeEntry(key, 1, static_cast<uint32_t>(value));
82 }
83
85 void write(const char* key, bool value)
86 {
87 writeEntry(key, 2, value ? 1u : 0u);
88 }
89
91 void write(const char* key, const std::vector<uint8_t>& nested)
92 {
93 const size_t len = std::strlen(key);
94 assert(len <= 255 && "state key longer than 255 chars");
95 assert(count_ < 0xFFFF && "state entry count overflows u16");
96 if (len > 255 || count_ == 0xFFFF) { overflow_ = true; return; }
97 blob_.push_back(static_cast<uint8_t>(len));
98 append(key, len);
99 blob_.push_back(3);
100 appendU32(static_cast<uint32_t>(nested.size()));
101 blob_.insert(blob_.end(), nested.begin(), nested.end());
102 ++count_;
103 }
104
112 [[nodiscard]] std::vector<uint8_t> blob() const
113 {
114 if (overflow_) return {};
115 std::vector<uint8_t> out = blob_;
116 out[countPos_] = static_cast<uint8_t>(count_ & 0xFF);
117 out[countPos_ + 1] = static_cast<uint8_t>((count_ >> 8) & 0xFF);
118 return out;
119 }
120
121private:
122 static constexpr uint16_t kFormatVersion = 1;
123
124 void writeEntry(const char* key, uint8_t type, uint32_t payload)
125 {
126 const size_t len = std::strlen(key);
127 assert(len <= 255 && "state key longer than 255 chars");
128 assert(count_ < 0xFFFF && "state entry count overflows u16");
129 if (len > 255 || count_ == 0xFFFF) { overflow_ = true; return; }
130 blob_.push_back(static_cast<uint8_t>(len));
131 append(key, len);
132 blob_.push_back(type);
133 appendU32(payload);
134 ++count_;
135 }
136
137 void append(const char* data, size_t n)
138 {
139 blob_.insert(blob_.end(), data, data + n);
140 }
141 void appendU16(uint16_t v)
142 {
143 blob_.push_back(static_cast<uint8_t>(v & 0xFF));
144 blob_.push_back(static_cast<uint8_t>(v >> 8));
145 }
146 void appendU32(uint32_t v)
147 {
148 for (int i = 0; i < 4; ++i)
149 blob_.push_back(static_cast<uint8_t>((v >> (8 * i)) & 0xFF));
150 }
151
152 std::vector<uint8_t> blob_;
153 size_t countPos_ = 0;
154 uint16_t count_ = 0;
155 bool overflow_ = false;
156};
157
158// ============================================================================
159// StateReader
160// ============================================================================
161
171{
172public:
173 StateReader(const uint8_t* data, size_t size)
174 {
175 if (data == nullptr || size < 14 || std::memcmp(data, "DSPK", 4) != 0)
176 return;
177 const uint16_t fmt = readU16(data + 4);
178 if (fmt != 1) return;
179 processorId_ = readU32(data + 6);
180 processorVersion_ = readU16(data + 10);
181 const uint16_t count = readU16(data + 12);
182
183 size_t pos = 14;
184 for (uint16_t i = 0; i < count; ++i)
185 {
186 if (pos + 1 > size) return;
187 const size_t keyLen = data[pos++];
188 if (pos + keyLen + 5 > size) return;
189 Entry e;
190 e.key.assign(reinterpret_cast<const char*>(data + pos), keyLen);
191 pos += keyLen;
192 e.type = data[pos++];
193 e.payload = readU32(data + pos);
194 pos += 4;
195 if (e.type == 3) // nested blob: payload is its byte length
196 {
197 // Subtraction form: `pos + e.payload > size` would wrap on
198 // 32-bit size_t (WASM) for a corrupt length near UINT32_MAX
199 // and pass the check into a giant out-of-bounds read.
200 if (e.payload > size - pos) return;
201 e.bytes.assign(data + pos, data + pos + e.payload);
202 pos += e.payload;
203 }
204 entries_.push_back(std::move(e));
205 }
206 valid_ = true;
207 }
208
209 [[nodiscard]] bool isValid() const noexcept { return valid_; }
210 [[nodiscard]] uint32_t processorId() const noexcept { return processorId_; }
211 [[nodiscard]] uint16_t processorVersion() const noexcept { return processorVersion_; }
212
214 [[nodiscard]] float read(const char* key, float defaultValue) const
215 {
216 if (const Entry* e = find(key, 0))
217 {
218 float v = 0.0f;
219 std::memcpy(&v, &e->payload, 4);
220 return v;
221 }
222 return defaultValue;
223 }
224
226 [[nodiscard]] int32_t read(const char* key, int32_t defaultValue) const
227 {
228 if (const Entry* e = find(key, 1))
229 return static_cast<int32_t>(e->payload);
230 return defaultValue;
231 }
232
234 [[nodiscard]] bool read(const char* key, bool defaultValue) const
235 {
236 if (const Entry* e = find(key, 2))
237 return e->payload != 0;
238 return defaultValue;
239 }
240
242 [[nodiscard]] std::vector<uint8_t> readBlob(const char* key) const
243 {
244 if (const Entry* e = find(key, 3))
245 return e->bytes;
246 return {};
247 }
248
250 struct Entry
251 {
252 std::string key;
253 uint8_t type = 0;
254 uint32_t payload = 0;
255 std::vector<uint8_t> bytes;
256 };
257 [[nodiscard]] const std::vector<Entry>& entries() const noexcept { return entries_; }
258
259private:
260 [[nodiscard]] const Entry* find(const char* key, uint8_t type) const
261 {
262 for (const auto& e : entries_)
263 if (e.type == type && e.key == key)
264 return &e;
265 return nullptr;
266 }
267
268 static uint16_t readU16(const uint8_t* p)
269 {
270 return static_cast<uint16_t>(p[0] | (p[1] << 8));
271 }
272 static uint32_t readU32(const uint8_t* p)
273 {
274 return static_cast<uint32_t>(p[0]) | (static_cast<uint32_t>(p[1]) << 8)
275 | (static_cast<uint32_t>(p[2]) << 16) | (static_cast<uint32_t>(p[3]) << 24);
276 }
277
278 bool valid_ = false;
279 uint32_t processorId_ = 0;
280 uint16_t processorVersion_ = 0;
281 std::vector<Entry> entries_;
282};
283
284// ============================================================================
285// JSON helpers (the blob's flat-object subset, zero dependencies)
286// ============================================================================
287
288namespace detail {
289
292constexpr int kMaxStateJsonDepth = 32;
293
299inline void appendStateJsonString(std::string& out, const std::string& s)
300{
301 out += '"';
302 for (const unsigned char c : s)
303 {
304 switch (c)
305 {
306 case '"': out += "\\\""; break;
307 case '\\': out += "\\\\"; break;
308 case '\b': out += "\\b"; break;
309 case '\f': out += "\\f"; break;
310 case '\n': out += "\\n"; break;
311 case '\r': out += "\\r"; break;
312 case '\t': out += "\\t"; break;
313 default:
314 if (c < 0x20)
315 {
316 char esc[7];
317 std::snprintf(esc, sizeof(esc), "\\u%04x", static_cast<unsigned>(c));
318 out += esc;
319 }
320 else
321 {
322 out += static_cast<char>(c);
323 }
324 break;
325 }
326 }
327 out += '"';
328}
329
333inline void appendStateJsonNumber(std::string& out, float v)
334{
335 if (!std::isfinite(v)) { out += '0'; return; }
336 char num[48];
337 std::snprintf(num, sizeof(num), "%.9g", static_cast<double>(v));
338 for (char* c = num; *c != '\0'; ++c)
339 if (*c == ',') *c = '.'; // locale decimal comma -> JSON dot
340 out += num;
341}
342
344inline const char* parseStateJsonNumber(const char* s, const char* end, double& out) noexcept
345{
346 bool negative = false;
347 if (s < end && (*s == '-' || *s == '+'))
348 {
349 negative = (*s == '-');
350 ++s;
351 }
352 double v = 0.0;
353 bool any = false;
354 while (s < end && *s >= '0' && *s <= '9')
355 {
356 v = v * 10.0 + (*s - '0');
357 ++s;
358 any = true;
359 }
360 if (s < end && *s == '.')
361 {
362 ++s;
363 double f = 0.1;
364 while (s < end && *s >= '0' && *s <= '9')
365 {
366 v += (*s - '0') * f;
367 f *= 0.1;
368 ++s;
369 any = true;
370 }
371 }
372 if (!any) return nullptr;
373 if (s < end && (*s == 'e' || *s == 'E'))
374 {
375 ++s;
376 bool expNegative = false;
377 if (s < end && (*s == '-' || *s == '+'))
378 {
379 expNegative = (*s == '-');
380 ++s;
381 }
382 int e = 0;
383 bool eAny = false;
384 while (s < end && *s >= '0' && *s <= '9')
385 {
386 e = e * 10 + (*s - '0');
387 ++s;
388 eAny = true;
389 if (e > 308) { e = 309; } // saturate
390 }
391 if (!eAny) return nullptr;
392 double scale = 1.0;
393 for (int k = 0; k < (e > 309 ? 309 : e); ++k)
394 scale *= 10.0;
395 v = expNegative ? v / scale : v * scale;
396 }
397 out = negative ? -v : v;
398 return s;
399}
400
401inline std::string stateToJsonImpl(const std::vector<uint8_t>& blob, int depth)
402{
403 if (depth >= kMaxStateJsonDepth) return "{}";
404
405 StateReader r(blob.data(), blob.size());
406 if (!r.isValid()) return "{}";
407
408 std::string out = "{\"id\":" + std::to_string(r.processorId())
409 + ",\"version\":" + std::to_string(r.processorVersion())
410 + ",\"params\":{";
411 bool first = true;
412 for (const auto& e : r.entries())
413 {
414 if (!first) out += ',';
415 first = false;
416 appendStateJsonString(out, e.key);
417 out += ':';
418 if (e.type == 0)
419 {
420 float v = 0.0f;
421 std::memcpy(&v, &e.payload, 4);
422 appendStateJsonNumber(out, v);
423 }
424 else if (e.type == 1)
425 {
426 out += std::to_string(static_cast<int32_t>(e.payload));
427 }
428 else if (e.type == 3)
429 {
430 out += stateToJsonImpl(e.bytes, depth + 1); // nested state: recurse
431 }
432 else
433 {
434 out += (e.payload != 0) ? "true" : "false";
435 }
436 }
437 out += "}}";
438 return out;
439}
440
441inline std::vector<uint8_t> stateFromJsonImpl(const std::string& json, int depth)
442{
443 if (depth >= kMaxStateJsonDepth) return {};
444
445 auto skipWs = [&](size_t& p) { while (p < json.size() && (json[p] == ' ' || json[p] == '\n'
446 || json[p] == '\t' || json[p] == '\r')) ++p; };
447 auto expect = [&](size_t& p, char c) {
448 skipWs(p);
449 if (p >= json.size() || json[p] != c) return false;
450 ++p;
451 return true;
452 };
453 auto parseString = [&](size_t& p, std::string& out) {
454 skipWs(p);
455 if (p >= json.size() || json[p] != '"') return false;
456 ++p;
457 out.clear();
458 while (p < json.size() && json[p] != '"')
459 {
460 char c = json[p++];
461 if (c == '\\') // unescape the sequences appendStateJsonString emits
462 {
463 if (p >= json.size()) return false;
464 const char e = json[p++];
465 switch (e)
466 {
467 case '"': out += '"'; break;
468 case '\\': out += '\\'; break;
469 case '/': out += '/'; break;
470 case 'b': out += '\b'; break;
471 case 'f': out += '\f'; break;
472 case 'n': out += '\n'; break;
473 case 'r': out += '\r'; break;
474 case 't': out += '\t'; break;
475 case 'u':
476 {
477 if (p + 4 > json.size()) return false;
478 unsigned code = 0;
479 for (int k = 0; k < 4; ++k)
480 {
481 const char h = json[p++];
482 code <<= 4;
483 if (h >= '0' && h <= '9') code |= unsigned(h - '0');
484 else if (h >= 'a' && h <= 'f') code |= unsigned(h - 'a' + 10);
485 else if (h >= 'A' && h <= 'F') code |= unsigned(h - 'A' + 10);
486 else return false;
487 }
488 // Keys are ASCII by convention; emit the low byte (control
489 // chars round-trip, higher planes are out of contract).
490 out += static_cast<char>(code & 0xFF);
491 break;
492 }
493 default: return false; // unknown escape -> reject
494 }
495 }
496 else
497 {
498 out += c;
499 }
500 }
501 if (p >= json.size()) return false;
502 ++p;
503 return true;
504 };
505 auto parseNumber = [&](size_t& p, double& out) {
506 skipWs(p);
507 const char* start = json.c_str() + p;
508 const char* endOfJson = json.c_str() + json.size();
509 const char* stop = parseStateJsonNumber(start, endOfJson, out);
510 if (stop == nullptr) return false;
511 p = static_cast<size_t>(stop - json.c_str());
512 return true;
513 };
514
515 size_t p = 0;
516 std::string key;
517 double num = 0.0;
518 uint32_t id = 0;
519 uint16_t version = 0;
520
521 if (!expect(p, '{')) return {};
522 struct Param { std::string key; uint8_t type; uint32_t payload;
523 std::vector<uint8_t> bytes; };
524 std::vector<Param> params;
525
526 while (true)
527 {
528 if (!parseString(p, key) || !expect(p, ':')) return {};
529 if (key == "id" && parseNumber(p, num))
530 {
531 // Range-check before every float->int conversion: an out-of-range
532 // conversion is undefined behaviour, and this parser reads
533 // untrusted preset text.
534 if (!(num >= 0.0 && num <= 4294967295.0)) return {};
535 id = static_cast<uint32_t>(num);
536 }
537 else if (key == "version" && parseNumber(p, num))
538 {
539 if (!(num >= 0.0 && num <= 65535.0)) return {};
540 version = static_cast<uint16_t>(num);
541 }
542 else if (key == "params")
543 {
544 if (!expect(p, '{')) return {};
545 skipWs(p);
546 if (p < json.size() && json[p] == '}') { ++p; }
547 else
548 {
549 while (true)
550 {
551 std::string pk;
552 if (!parseString(p, pk) || !expect(p, ':')) return {};
553 skipWs(p);
554 Param prm { pk, 0, 0, {} };
555 if (p < json.size() && json[p] == '{')
556 {
557 // Nested state object: balance braces, recurse.
558 size_t braceDepth = 0, end = p;
559 for (; end < json.size(); ++end)
560 {
561 if (json[end] == '{') ++braceDepth;
562 else if (json[end] == '}' && --braceDepth == 0) { ++end; break; }
563 }
564 if (braceDepth != 0) return {};
565 prm.type = 3;
566 prm.bytes = stateFromJsonImpl(json.substr(p, end - p), depth + 1);
567 if (prm.bytes.empty()) return {};
568 p = end;
569 }
570 else if (json.compare(p, 4, "true") == 0)
571 {
572 prm.type = 2; prm.payload = 1; p += 4;
573 }
574 else if (json.compare(p, 5, "false") == 0)
575 {
576 prm.type = 2; prm.payload = 0; p += 5;
577 }
578 else if (parseNumber(p, num))
579 {
580 // Integers without fraction round-trip as int32 too;
581 // store as float (type 0) plus int mirror when exact.
582 // Beyond the float range the double->float conversion
583 // is undefined: reject such text as malformed. "%.9g"
584 // prints FLT_MAX as 3.40282347e+38, a hair above
585 // FLT_MAX, and every double below FLT_MAX plus half
586 // an ulp denotes FLT_MAX: accept that band and clamp.
587 constexpr double kFloatMax = static_cast<double>(
588 std::numeric_limits<float>::max());
589 constexpr double kFloatLimit = 3.4028235677973366e38;
590 if (!(std::abs(num) < kFloatLimit))
591 return {};
592 const auto f = static_cast<float>(std::clamp(num, -kFloatMax, kFloatMax));
593 std::memcpy(&prm.payload, &f, 4);
594 prm.type = 0;
595 if (num >= -2147483648.0 && num <= 2147483647.0
596 && num == static_cast<double>(static_cast<int32_t>(num)))
597 {
598 params.push_back({ pk, 1,
599 static_cast<uint32_t>(static_cast<int32_t>(num)), {} });
600 }
601 }
602 else return {};
603 params.push_back(std::move(prm));
604 skipWs(p);
605 if (p < json.size() && json[p] == ',') { ++p; continue; }
606 break;
607 }
608 if (!expect(p, '}')) return {};
609 }
610 }
611 else return {};
612 skipWs(p);
613 if (p < json.size() && json[p] == ',') { ++p; continue; }
614 break;
615 }
616 if (!expect(p, '}')) return {};
617 skipWs(p);
618 if (p != json.size()) return {}; // trailing text is malformed input
619 // The binary format holds at most 65535 entries with keys of 255 bytes.
620 if (params.size() > 0xFFFF) return {};
621 for (const auto& prm : params)
622 if (prm.key.size() > 255) return {};
623
624 StateWriter w(id, version);
625 for (const auto& prm : params)
626 {
627 if (prm.type == 0)
628 {
629 float v = 0.0f;
630 std::memcpy(&v, &prm.payload, 4);
631 w.write(prm.key.c_str(), v);
632 }
633 else if (prm.type == 1)
634 {
635 w.write(prm.key.c_str(), static_cast<int32_t>(prm.payload));
636 }
637 else if (prm.type == 3)
638 {
639 w.write(prm.key.c_str(), prm.bytes);
640 }
641 else
642 {
643 w.write(prm.key.c_str(), prm.payload != 0);
644 }
645 }
646 return w.blob();
647}
648
649} // namespace detail
650
652[[nodiscard]] inline std::string stateToJson(const std::vector<uint8_t>& blob)
653{
654 return detail::stateToJsonImpl(blob, 0);
655}
656
666[[nodiscard]] inline std::vector<uint8_t> stateFromJson(const std::string& json)
667{
668 return detail::stateFromJsonImpl(json, 0);
669}
670
672[[nodiscard]] constexpr uint32_t stateId(const char (&tag)[5]) noexcept
673{
674 // Bytes, not chars: a (theoretical) non-ASCII tag char would sign-extend
675 // and smear across the other lanes.
676 return static_cast<uint32_t>(static_cast<uint8_t>(tag[0]))
677 | (static_cast<uint32_t>(static_cast<uint8_t>(tag[1])) << 8)
678 | (static_cast<uint32_t>(static_cast<uint8_t>(tag[2])) << 16)
679 | (static_cast<uint32_t>(static_cast<uint8_t>(tag[3])) << 24);
680}
681
682} // namespace dspark
Tolerant reader: missing keys yield defaults, unknown keys are skipped.
Definition StateBlob.h:171
std::vector< uint8_t > readBlob(const char *key) const
Reads a nested blob; empty when the key is absent.
Definition StateBlob.h:242
StateReader(const uint8_t *data, size_t size)
Definition StateBlob.h:173
int32_t read(const char *key, int32_t defaultValue) const
Reads an int32, or defaultValue when the key is absent.
Definition StateBlob.h:226
uint16_t processorVersion() const noexcept
Definition StateBlob.h:211
float read(const char *key, float defaultValue) const
Reads a float, or defaultValue when the key is absent.
Definition StateBlob.h:214
bool isValid() const noexcept
Definition StateBlob.h:209
uint32_t processorId() const noexcept
Definition StateBlob.h:210
const std::vector< Entry > & entries() const noexcept
Definition StateBlob.h:257
bool read(const char *key, bool defaultValue) const
Reads a bool, or defaultValue when the key is absent.
Definition StateBlob.h:234
Serializes key/value parameters into a versioned blob.
Definition StateBlob.h:53
void write(const char *key, const std::vector< uint8_t > &nested)
Writes a nested blob (composite processors: bands, slots...).
Definition StateBlob.h:91
StateWriter(uint32_t processorId, uint16_t processorVersion)
Definition StateBlob.h:59
std::vector< uint8_t > blob() const
Finalizes and returns the blob.
Definition StateBlob.h:112
void write(const char *key, float value)
Writes a float parameter.
Definition StateBlob.h:71
void write(const char *key, bool value)
Writes a boolean parameter.
Definition StateBlob.h:85
void write(const char *key, int32_t value)
Writes an integer parameter (enums, counts, modes).
Definition StateBlob.h:79
const char * parseStateJsonNumber(const char *s, const char *end, double &out) noexcept
Locale-independent number parse over [s, end); nullptr on failure.
Definition StateBlob.h:344
std::string stateToJsonImpl(const std::vector< uint8_t > &blob, int depth)
Definition StateBlob.h:401
std::vector< uint8_t > stateFromJsonImpl(const std::string &json, int depth)
Definition StateBlob.h:441
void appendStateJsonNumber(std::string &out, float v)
Locale-independent float rendering ("%.9g" with a forced dot). Non-finite payloads (NaN/Inf – e....
Definition StateBlob.h:333
constexpr int kMaxStateJsonDepth
Definition StateBlob.h:292
void appendStateJsonString(std::string &out, const std::string &s)
Appends a JSON string literal, escaping the characters JSON forbids. Keys follow the [A-Za-z0-9....
Definition StateBlob.h:299
Main namespace for the DSPark framework.
std::string stateToJson(const std::vector< uint8_t > &blob)
Renders a state blob as a flat JSON object string.
Definition StateBlob.h:652
constexpr uint32_t stateId(const char(&tag)[5]) noexcept
Builds a FOURCC processor id, e.g. dspark::stateId("COMP").
Definition StateBlob.h:672
std::vector< uint8_t > stateFromJson(const std::string &json)
Parses the JSON produced by stateToJson() back into a blob.
Definition StateBlob.h:666
Access for generic tooling (JSON rendering, preset browsers).
Definition StateBlob.h:251
std::vector< uint8_t > bytes
Nested blob content (type 3).
Definition StateBlob.h:255