Files
bananarchy/src/dwm-plugins/monotone.h
T

1063 lines
32 KiB
C++
Raw Normal View History

// SPDX-License-Identifier: GPL-2.0-only
// Bananarchy Monophonic Ringtone Parser & Synthesizer
// Supports Nokia RTTTL (.rtttl), Nokia Ringtone (.nrt), Extended RTTTL (.rtx),
// Ericsson eMelody (.emy), and IrDA iMelody (.imy).
#ifndef DWM_PLUGINS_MONOTONE_H
#define DWM_PLUGINS_MONOTONE_H
#include <algorithm>
#include <cctype>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
namespace bananarchy {
enum class MonotoneFormat {
Unknown = 0,
Rtttl = 1,
Nrt = 2,
Rtx = 3,
EMelody = 4,
IMelody = 5,
};
enum class MonotoneStyle {
Normal = 0, // S0 / N: natural articulation gap at end of note
Continuous = 1, // S1 / C: legato (no gap between consecutive notes)
Staccato = 2, // S2 / S: staccato (short crisp notes)
};
struct MonotoneNote {
double freqHz = 0.0; // 0.0 = rest / pause
int durationMs = 0; // total note slot duration in ms
int toneMs = 0; // audible tone duration in ms
int midiNote = -1; // -1 for rest, else MIDI note number (69 = A4 = 440Hz)
int volume = 12; // 0..15 relative volume
std::string label; // compact note token, e.g. "8E6", "4F#5", "8P"
bool vibeOn = false;
bool ledOn = false;
};
struct MonotoneSong {
MonotoneFormat format = MonotoneFormat::Unknown;
std::string formatTag; // "NRT", "RTTTL", "RTX", "EMY", "IMY"
std::string name; // parsed melody name or filename stem
std::string composer; // optional COMPOSER header (.emy / .imy)
int bpm = 120; // tempo in beats per minute
int defaultOctave = 5;
int defaultDuration = 4;
int loopCount = 0; // RTX l= loop parameter
MonotoneStyle style = MonotoneStyle::Normal;
int totalDurationMs = 0;
int pitchedNoteCount = 0;
std::vector<MonotoneNote> notes;
std::string rawMelody;
};
inline std::string monoToLower(const std::string& s) {
std::string out = s;
for (char& c : out) {
c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
}
return out;
}
inline std::string monoToUpper(const std::string& s) {
std::string out = s;
for (char& c : out) {
c = static_cast<char>(std::toupper(static_cast<unsigned char>(c)));
}
return out;
}
inline std::string monoTrim(const std::string& s) {
size_t b = 0;
while (b < s.size() &&
std::isspace(static_cast<unsigned char>(s[b]))) {
++b;
}
size_t e = s.size();
while (e > b &&
std::isspace(static_cast<unsigned char>(s[e - 1]))) {
--e;
}
return s.substr(b, e - b);
}
inline std::string monoGetExtLower(const std::string& pathOrName) {
size_t sl = pathOrName.rfind('/');
size_t dot = pathOrName.rfind('.');
if (dot == std::string::npos || (sl != std::string::npos && dot < sl) ||
dot + 1 >= pathOrName.size()) {
return "";
}
return monoToLower(pathOrName.substr(dot + 1));
}
inline std::string monoFilenameStem(const std::string& pathOrName) {
size_t sl = pathOrName.rfind('/');
std::string base =
(sl == std::string::npos) ? pathOrName : pathOrName.substr(sl + 1);
size_t dot = base.rfind('.');
if (dot != std::string::npos && dot > 0) {
base = base.substr(0, dot);
}
for (char& c : base) {
if (c == '_' || c == '-') c = ' ';
}
return monoTrim(base);
}
inline bool isMonotoneExt(const std::string& extLower) {
std::string e = monoToLower(extLower);
return e == "nrt" || e == "rtttl" || e == "rtx" ||
e == "emy" || e == "imy";
}
inline bool isMonotoneFile(const std::string& pathOrName,
std::string* extUpperOut = nullptr) {
std::string ext = monoGetExtLower(pathOrName);
if (!isMonotoneExt(ext)) return false;
if (extUpperOut) {
*extUpperOut = monoToUpper(ext);
}
return true;
}
inline MonotoneFormat monotoneFormatFromExt(const std::string& extLower) {
std::string e = monoToLower(extLower);
if (e == "nrt") return MonotoneFormat::Nrt;
if (e == "rtttl") return MonotoneFormat::Rtttl;
if (e == "rtx") return MonotoneFormat::Rtx;
if (e == "emy") return MonotoneFormat::EMelody;
if (e == "imy") return MonotoneFormat::IMelody;
return MonotoneFormat::Unknown;
}
inline const char* monotoneFormatTag(MonotoneFormat fmt) {
switch (fmt) {
case MonotoneFormat::Nrt: return "NRT";
case MonotoneFormat::Rtttl: return "RTTTL";
case MonotoneFormat::Rtx: return "RTX";
case MonotoneFormat::EMelody: return "EMY";
case MonotoneFormat::IMelody: return "IMY";
default: return "TONE";
}
}
inline const char* monotoneFormatLabel(MonotoneFormat fmt) {
switch (fmt) {
case MonotoneFormat::Nrt: return "Nokia NRT (RTTTL)";
case MonotoneFormat::Rtttl: return "Nokia RTTTL";
case MonotoneFormat::Rtx: return "Nokia RTX";
case MonotoneFormat::EMelody: return "Ericsson eMelody";
case MonotoneFormat::IMelody: return "IrDA iMelody";
default: return "Monophonic Ringtone";
}
}
inline const char* monotoneStyleLabel(MonotoneStyle st) {
switch (st) {
case MonotoneStyle::Continuous: return "Legato";
case MonotoneStyle::Staccato: return "Staccato";
default: return "Natural";
}
}
inline int noteCharToSemitone(char lowCh, bool* isRestOut = nullptr) {
if (isRestOut) *isRestOut = false;
switch (lowCh) {
case 'c': return 0;
case 'd': return 2;
case 'e': return 4;
case 'f': return 5;
case 'g': return 7;
case 'a': return 9;
case 'b':
case 'h': return 11;
case 'p':
case 'r':
if (isRestOut) *isRestOut = true;
return -1;
default:
return -2;
}
}
inline const char* semitoneToNoteName(int semi) {
static const char* kNames[12] = {
"C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"
};
int idx = ((semi % 12) + 12) % 12;
return kNames[idx];
}
inline int computeToneDurationMs(int slotMs, MonotoneStyle style) {
if (slotMs <= 0) return 0;
if (style == MonotoneStyle::Continuous) {
return slotMs;
}
if (style == MonotoneStyle::Staccato) {
return std::max(12, (slotMs * 52) / 100);
}
int gap = std::clamp(slotMs / 10, 8, 32);
return std::max(12, slotMs - gap);
}
inline MonotoneNote makeMonotoneNote(int midi, int durDivisor, int slotMs,
MonotoneStyle style, int volume = 12,
bool vibeOn = false, bool ledOn = false) {
MonotoneNote n;
n.durationMs = std::clamp(slotMs, 12, 12000);
n.volume = std::clamp(volume, 0, 15);
n.vibeOn = vibeOn;
n.ledOn = ledOn;
std::string dStr = (durDivisor > 0) ? std::to_string(durDivisor) : "";
if (midi < 0 || n.volume == 0) {
n.freqHz = 0.0;
n.toneMs = 0;
n.midiNote = -1;
n.label = dStr + "P";
return n;
}
midi = std::clamp(midi, 24, 119);
n.midiNote = midi;
n.freqHz = 440.0 * std::pow(2.0, static_cast<double>(midi - 69) / 12.0);
n.toneMs = computeToneDurationMs(n.durationMs, style);
int oct = (midi / 12) - 1;
int semi = midi % 12;
n.label = dStr + semitoneToNoteName(semi) + std::to_string(oct);
return n;
}
inline void applyRtttlControlPair(const std::string& rawPair,
int* curDur, int* curOct, int* curBpm,
MonotoneStyle* curStyle, int* loopCount) {
auto eq = rawPair.find('=');
if (eq == std::string::npos) return;
std::string k = monoToLower(monoTrim(rawPair.substr(0, eq)));
std::string v = monoToLower(monoTrim(rawPair.substr(eq + 1)));
if (k.empty() || v.empty()) return;
int val = std::atoi(v.c_str());
if (k == "d" && val >= 1 && val <= 128) {
*curDur = val;
} else if (k == "o" && val >= 0 && val <= 8) {
*curOct = val;
} else if (k == "b" && val >= 10 && val <= 900) {
*curBpm = val;
} else if (k == "l" && val >= 0 && val <= 64) {
*loopCount = val;
} else if (k == "s") {
if (v[0] == 'c' || v[0] == '1') {
*curStyle = MonotoneStyle::Continuous;
} else if (v[0] == 's' || v[0] == '2') {
*curStyle = MonotoneStyle::Staccato;
} else {
*curStyle = MonotoneStyle::Normal;
}
}
}
inline bool parseRtttlContent(const std::string& rawContent,
MonotoneFormat fmtHint,
const std::string& fallbackName,
MonotoneSong* outSong) {
if (!outSong) return false;
*outSong = MonotoneSong{};
outSong->format =
(fmtHint == MonotoneFormat::Nrt || fmtHint == MonotoneFormat::Rtx)
? fmtHint
: MonotoneFormat::Rtttl;
std::string cleaned;
std::istringstream iss(rawContent);
std::string line;
int colonCount = 0;
while (std::getline(iss, line)) {
if (!line.empty() && line.back() == '\r') line.pop_back();
if (cleaned.empty() && line.size() >= 3 &&
static_cast<unsigned char>(line[0]) == 0xEF &&
static_cast<unsigned char>(line[1]) == 0xBB &&
static_cast<unsigned char>(line[2]) == 0xBF) {
line.erase(0, 3);
}
std::string tr = monoTrim(line);
if (tr.empty()) continue;
if (cleaned.empty() &&
(tr[0] == '#' || tr[0] == ';' || tr.rfind("//", 0) == 0)) {
continue;
}
int lineColons = 0;
for (char c : tr) {
if (c == ':') ++lineColons;
}
if (!cleaned.empty() && colonCount >= 2 && lineColons >= 1) {
// Stop at the start of a second RTTTL tune in a multi-tune file
break;
}
colonCount += lineColons;
if (!cleaned.empty() && cleaned.back() != ',' && cleaned.back() != ':' &&
tr.front() != ',' && tr.front() != ':') {
cleaned.push_back(',');
}
cleaned += tr;
}
if (cleaned.empty()) return false;
std::string namePart;
std::string ctrlPart;
std::string notesPart;
size_t c1 = cleaned.find(':');
if (c1 == std::string::npos) {
notesPart = cleaned;
} else {
size_t c2 = cleaned.find(':', c1 + 1);
if (c2 == std::string::npos) {
std::string first = cleaned.substr(0, c1);
std::string second = cleaned.substr(c1 + 1);
if (first.find('=') != std::string::npos) {
ctrlPart = first;
} else {
namePart = first;
}
notesPart = second;
} else {
namePart = cleaned.substr(0, c1);
ctrlPart = cleaned.substr(c1 + 1, c2 - c1 - 1);
notesPart = cleaned.substr(c2 + 1);
}
}
int curDur = 4;
int curOct = 6;
int curBpm = 63;
int loopCount = 0;
MonotoneStyle curStyle = MonotoneStyle::Normal;
{
std::string tok;
for (size_t i = 0; i <= ctrlPart.size(); ++i) {
char c = (i < ctrlPart.size()) ? ctrlPart[i] : ',';
if (c == ',' || c == ';') {
if (!tok.empty()) {
applyRtttlControlPair(tok, &curDur, &curOct, &curBpm, &curStyle,
&loopCount);
tok.clear();
}
} else {
tok.push_back(c);
}
}
}
outSong->name = monoTrim(namePart);
if (outSong->name.empty()) {
outSong->name = fallbackName.empty() ? "Nokia Ringtone" : fallbackName;
}
outSong->bpm = curBpm;
outSong->defaultDuration = curDur;
outSong->defaultOctave = curOct;
outSong->style = curStyle;
outSong->loopCount = loopCount;
outSong->rawMelody = monoTrim(notesPart);
int octOffset = (curOct <= 2) ? 3 : 0;
std::string tok;
for (size_t i = 0; i <= notesPart.size(); ++i) {
char c = (i < notesPart.size()) ? notesPart[i] : ',';
if (c == ',' || c == ';') {
std::string t = monoTrim(tok);
tok.clear();
if (t.empty()) continue;
if (t.find('=') != std::string::npos) {
applyRtttlControlPair(t, &curDur, &curOct, &curBpm, &curStyle,
&loopCount);
if (outSong->format == MonotoneFormat::Rtttl) {
outSong->format = MonotoneFormat::Rtx;
}
continue;
}
size_t pos = 0;
int parsedDur = 0;
while (pos < t.size() &&
std::isdigit(static_cast<unsigned char>(t[pos]))) {
parsedDur = parsedDur * 10 + (t[pos] - '0');
++pos;
}
int dur = (parsedDur > 0) ? parsedDur : curDur;
dur = std::clamp(dur, 1, 128);
char noteCh = 0;
int accidental = 0;
int dots = 0;
int parsedOct = -1;
while (pos < t.size()) {
char ch = static_cast<char>(
std::tolower(static_cast<unsigned char>(t[pos])));
if (noteCh == 0 &&
((ch >= 'a' && ch <= 'h') || ch == 'p' || ch == 'r')) {
noteCh = ch;
} else if (ch == '#' || ch == '_') {
accidental = 1;
} else if (ch == '&') {
accidental = -1;
} else if (ch == 'b' && noteCh != 0 && noteCh != 'p' &&
noteCh != 'r') {
accidental = -1;
} else if (ch == '.') {
++dots;
} else if (std::isdigit(static_cast<unsigned char>(ch)) &&
parsedOct < 0) {
parsedOct = ch - '0';
}
++pos;
}
if (noteCh == 0) continue;
bool isRest = false;
int semi = noteCharToSemitone(noteCh, &isRest);
if (semi == -2) continue;
double wholeMs = 240000.0 / static_cast<double>(std::max(10, curBpm));
double slotMs = wholeMs / static_cast<double>(dur);
if (dots == 1) slotMs *= 1.5;
else if (dots >= 2) slotMs *= 1.75;
int midi = -1;
if (!isRest) {
int oct = ((parsedOct >= 0) ? parsedOct : curOct) + octOffset;
oct = std::clamp(oct, 2, 8);
midi = (oct + 1) * 12 + semi + accidental;
}
MonotoneNote note = makeMonotoneNote(
midi, dur, static_cast<int>(slotMs + 0.5), curStyle, 13);
outSong->totalDurationMs += note.durationMs;
if (note.midiNote >= 0) {
++outSong->pitchedNoteCount;
}
outSong->notes.push_back(note);
if (outSong->notes.size() >= 2048) break;
} else {
tok.push_back(c);
}
}
outSong->formatTag = monotoneFormatTag(outSong->format);
return !outSong->notes.empty();
}
inline std::string expandMelodyRepeats(const std::string& src, int depth = 0) {
if (depth > 4 || src.empty()) return src;
std::string out;
out.reserve(std::min<size_t>(16384, src.size() * 2));
size_t i = 0;
while (i < src.size() && out.size() < 16384) {
if (src[i] == '(') {
int pDepth = 1;
size_t j = i + 1;
while (j < src.size() && pDepth > 0) {
if (src[j] == '(') ++pDepth;
else if (src[j] == ')') --pDepth;
++j;
}
std::string inner =
(pDepth == 0) ? src.substr(i + 1, j - i - 2) : src.substr(i + 1);
int repeats = 2;
size_t atPos = inner.rfind('@');
if (atPos != std::string::npos) {
std::string repStr = inner.substr(atPos + 1);
inner = inner.substr(0, atPos);
int parsedRep = std::atoi(repStr.c_str());
if (parsedRep == 0) {
repeats = 2; // @0 is infinite repeat in iMelody; play twice for WAV
} else {
repeats = std::clamp(parsedRep, 1, 8);
}
}
std::string expandedInner = expandMelodyRepeats(inner, depth + 1);
for (int r = 0; r < repeats && out.size() < 16384; ++r) {
out += expandedInner;
}
i = j;
} else {
out.push_back(src[i]);
++i;
}
}
return out;
}
inline bool matchAsciiKeywordNoCase(const std::string& s, size_t pos,
const char* kw) {
size_t klen = std::strlen(kw);
if (pos + klen > s.size()) return false;
for (size_t i = 0; i < klen; ++i) {
if (std::tolower(static_cast<unsigned char>(s[pos + i])) !=
std::tolower(static_cast<unsigned char>(kw[i]))) {
return false;
}
}
return true;
}
inline bool parseMelodyHeaderAndBody(const std::string& rawContent,
MonotoneFormat fmtHint,
const std::string& fallbackName,
MonotoneSong* outSong) {
if (!outSong) return false;
*outSong = MonotoneSong{};
outSong->format =
(fmtHint == MonotoneFormat::EMelody) ? MonotoneFormat::EMelody
: MonotoneFormat::IMelody;
outSong->bpm = 120;
outSong->defaultOctave = 5;
outSong->defaultDuration = (outSong->format == MonotoneFormat::EMelody) ? 8 : 4;
outSong->style = MonotoneStyle::Normal;
int initVol = 12;
std::string melodyBuf;
std::string rawLinesFallback;
bool inMelody = false;
bool sawAnyHeader = false;
std::istringstream iss(rawContent);
std::string line;
while (std::getline(iss, line)) {
if (!line.empty() && line.back() == '\r') line.pop_back();
if (rawLinesFallback.empty() && line.size() >= 3 &&
static_cast<unsigned char>(line[0]) == 0xEF &&
static_cast<unsigned char>(line[1]) == 0xBB &&
static_cast<unsigned char>(line[2]) == 0xBF) {
line.erase(0, 3);
}
std::string tr = monoTrim(line);
if (tr.empty()) continue;
std::string up = monoToUpper(tr);
if (up.rfind("BEGIN:IMELODY", 0) == 0) {
outSong->format = MonotoneFormat::IMelody;
sawAnyHeader = true;
inMelody = false;
} else if (up.rfind("BEGIN:EMELODY", 0) == 0) {
outSong->format = MonotoneFormat::EMelody;
sawAnyHeader = true;
inMelody = false;
} else if (up.rfind("END:IMELODY", 0) == 0 ||
up.rfind("END:EMELODY", 0) == 0) {
inMelody = false;
break;
} else if (up.rfind("VERSION:", 0) == 0 ||
up.rfind("FORMAT:", 0) == 0) {
sawAnyHeader = true;
inMelody = false;
} else if (up.rfind("NAME:", 0) == 0) {
outSong->name = monoTrim(tr.substr(5));
sawAnyHeader = true;
inMelody = false;
} else if (up.rfind("COMPOSER:", 0) == 0) {
outSong->composer = monoTrim(tr.substr(9));
sawAnyHeader = true;
inMelody = false;
} else if (up.rfind("BEAT:", 0) == 0) {
int b = std::atoi(monoTrim(tr.substr(5)).c_str());
if (b >= 20 && b <= 900) outSong->bpm = b;
sawAnyHeader = true;
inMelody = false;
} else if (up.rfind("STYLE:", 0) == 0) {
std::string sv = monoToUpper(monoTrim(tr.substr(6)));
if (sv == "S1" || sv == "1") {
outSong->style = MonotoneStyle::Continuous;
} else if (sv == "S2" || sv == "2") {
outSong->style = MonotoneStyle::Staccato;
} else {
outSong->style = MonotoneStyle::Normal;
}
sawAnyHeader = true;
inMelody = false;
} else if (up.rfind("VOLUME:", 0) == 0) {
std::string vv = monoToUpper(monoTrim(tr.substr(7)));
if (!vv.empty() && vv[0] == 'V') vv.erase(0, 1);
if (!vv.empty() && std::isdigit(static_cast<unsigned char>(vv[0]))) {
initVol = std::clamp(std::atoi(vv.c_str()), 1, 15);
}
sawAnyHeader = true;
inMelody = false;
} else if (up.rfind("MELODY:", 0) == 0) {
melodyBuf += monoTrim(tr.substr(7));
sawAnyHeader = true;
inMelody = true;
} else {
if (inMelody) {
melodyBuf += tr;
} else if (!sawAnyHeader && tr[0] != ';') {
rawLinesFallback += tr;
}
}
}
if (melodyBuf.empty()) {
melodyBuf = rawLinesFallback;
}
if (outSong->name.empty()) {
outSong->name = fallbackName.empty() ? "Melody Ringtone" : fallbackName;
}
outSong->rawMelody = melodyBuf;
outSong->formatTag = monotoneFormatTag(outSong->format);
std::string s = expandMelodyRepeats(melodyBuf);
if (s.empty()) return false;
int curVol = initVol;
MonotoneStyle curStyle = outSong->style;
bool curVibe = false;
bool curLed = false;
size_t i = 0;
while (i < s.size() && outSong->notes.size() < 2048) {
unsigned char uc = static_cast<unsigned char>(s[i]);
if (std::isspace(uc) || s[i] == ',' || s[i] == '(' || s[i] == ')') {
++i;
continue;
}
// Check special iMelody/eMelody device keywords first so their letters
// (b, a, c, e, d, f) are never misread as musical notes.
if (matchAsciiKeywordNoCase(s, i, "ledon")) {
curLed = true;
i += 5;
continue;
}
if (matchAsciiKeywordNoCase(s, i, "ledoff")) {
curLed = false;
i += 6;
continue;
}
if (matchAsciiKeywordNoCase(s, i, "vibeon")) {
curVibe = true;
i += 6;
continue;
}
if (matchAsciiKeywordNoCase(s, i, "vibeoff")) {
curVibe = false;
i += 7;
continue;
}
if (matchAsciiKeywordNoCase(s, i, "backon")) {
i += 6;
continue;
}
if (matchAsciiKeywordNoCase(s, i, "backoff")) {
i += 7;
continue;
}
// Volume modifier: V+, V-, V0..V15
if ((s[i] == 'v' || s[i] == 'V') && i + 1 < s.size()) {
char nx = s[i + 1];
if (nx == '+') {
curVol = std::min(15, curVol + 1);
i += 2;
continue;
} else if (nx == '-') {
curVol = std::max(1, curVol - 1);
i += 2;
continue;
} else if (std::isdigit(static_cast<unsigned char>(nx))) {
i += 1;
int v = 0;
while (i < s.size() &&
std::isdigit(static_cast<unsigned char>(s[i]))) {
v = v * 10 + (s[i] - '0');
++i;
}
curVol = std::clamp(v, 0, 15);
continue;
}
}
// Inline style modifier: S0, S1, S2
if ((s[i] == 's' || s[i] == 'S') && i + 1 < s.size() &&
s[i + 1] >= '0' && s[i + 1] <= '2') {
char sc = s[i + 1];
if (sc == '1') curStyle = MonotoneStyle::Continuous;
else if (sc == '2') curStyle = MonotoneStyle::Staccato;
else curStyle = MonotoneStyle::Normal;
i += 2;
continue;
}
// Skip stray @repeat suffixes if any
if (s[i] == '@') {
++i;
while (i < s.size() &&
std::isdigit(static_cast<unsigned char>(s[i]))) {
++i;
}
continue;
}
// Parse note prefix modifiers (+, -, *oct, #, &)
int octShift = 0;
int explicitOct = -1;
int accidental = 0;
while (i < s.size()) {
if (s[i] == '+') {
++octShift;
++i;
} else if (s[i] == '-') {
--octShift;
++i;
} else if (s[i] == '*' && i + 1 < s.size() &&
s[i + 1] >= '0' && s[i + 1] <= '8') {
explicitOct = s[i + 1] - '0';
i += 2;
} else if (s[i] == '#') {
accidental = 1;
++i;
} else if (s[i] == '&') {
accidental = -1;
++i;
} else {
break;
}
}
if (i >= s.size()) break;
char rawNoteCh = s[i];
char lowNoteCh = static_cast<char>(
std::tolower(static_cast<unsigned char>(rawNoteCh)));
bool isUpperNote =
std::isupper(static_cast<unsigned char>(rawNoteCh)) != 0;
bool isRest = false;
int semi = noteCharToSemitone(lowNoteCh, &isRest);
if (semi == -2) {
++i;
continue;
}
++i;
// Optional postfix sharp if followed by duration digit, dot, or end
if (i < s.size() && s[i] == '#') {
if (i + 1 >= s.size() ||
std::isdigit(static_cast<unsigned char>(s[i + 1])) ||
s[i + 1] == '.' || s[i + 1] == ':' || s[i + 1] == ';') {
accidental = 1;
++i;
}
}
// Duration digit: 0=whole, 1=half, 2=quarter, 3=eighth, 4=16th, 5=32nd
int durDivisor = 4;
if (i < s.size() && s[i] >= '0' && s[i] <= '5') {
int durCode = s[i] - '0';
durDivisor = (1 << durCode);
++i;
} else if (outSong->format == MonotoneFormat::EMelody) {
// Classic Ericsson eMelody: uppercase = 1/4 (long), lowercase = 1/8 (short)
durDivisor = isUpperNote ? 4 : 8;
} else {
durDivisor = 4;
}
// Optional duration specifier (., :, ;)
double durMult = 1.0;
if (i < s.size()) {
if (s[i] == '.') {
durMult = 1.5;
++i;
} else if (s[i] == ':') {
durMult = 1.75;
++i;
} else if (s[i] == ';') {
durMult = 2.0 / 3.0;
++i;
}
}
double wholeMs =
240000.0 / static_cast<double>(std::max(20, outSong->bpm));
double slotMs =
(wholeMs / static_cast<double>(durDivisor)) * durMult;
int midi = -1;
if (!isRest) {
int baseOct = (explicitOct >= 0) ? (explicitOct + 1) : 5;
int oct = std::clamp(baseOct + octShift, 2, 8);
midi = (oct + 1) * 12 + semi + accidental;
}
MonotoneNote note = makeMonotoneNote(
midi, durDivisor, static_cast<int>(slotMs + 0.5), curStyle, curVol,
curVibe, curLed);
outSong->totalDurationMs += note.durationMs;
if (note.midiNote >= 0) {
++outSong->pitchedNoteCount;
}
outSong->notes.push_back(note);
}
return !outSong->notes.empty();
}
inline bool parseMonotoneString(const std::string& content,
MonotoneFormat fmtHint,
const std::string& fallbackName,
MonotoneSong* outSong) {
if (!outSong) return false;
std::string up = monoToUpper(content);
MonotoneFormat fmt = fmtHint;
if (up.find("BEGIN:IMELODY") != std::string::npos) {
fmt = MonotoneFormat::IMelody;
} else if (up.find("BEGIN:EMELODY") != std::string::npos) {
fmt = MonotoneFormat::EMelody;
} else if (fmt == MonotoneFormat::Unknown) {
if (up.find("MELODY:") != std::string::npos) {
fmt = MonotoneFormat::IMelody;
} else {
fmt = MonotoneFormat::Rtttl;
}
}
if (fmt == MonotoneFormat::IMelody || fmt == MonotoneFormat::EMelody) {
if (parseMelodyHeaderAndBody(content, fmt, fallbackName, outSong)) {
return true;
}
return parseRtttlContent(content, fmt, fallbackName, outSong);
}
if (parseRtttlContent(content, fmt, fallbackName, outSong)) {
return true;
}
return parseMelodyHeaderAndBody(content, fmt, fallbackName, outSong);
}
inline bool parseMonotoneFile(const std::string& path,
MonotoneSong* outSong) {
std::ifstream ifs(path, std::ios::binary);
if (!ifs) return false;
std::ostringstream oss;
oss << ifs.rdbuf();
std::string content = oss.str();
if (content.empty()) return false;
std::string ext = monoGetExtLower(path);
MonotoneFormat fmt = monotoneFormatFromExt(ext);
std::string fallbackName = monoFilenameStem(path);
return parseMonotoneString(content, fmt, fallbackName, outSong);
}
inline bool synthesizeMonotoneWav(const MonotoneSong& song,
const std::string& wavOutPath,
int loops = 1) {
if (song.notes.empty()) return false;
loops = std::clamp(loops, 1, 20);
constexpr int kSampleRate = 48000;
constexpr int kChannels = 2;
constexpr int kTableSize = 2048;
constexpr int kTableMask = kTableSize - 1;
// Build base sine table once
static float sSinTable[kTableSize];
static bool sSinInit = false;
if (!sSinInit) {
for (int i = 0; i < kTableSize; ++i) {
sSinTable[i] = static_cast<float>(
std::sin((2.0 * 3.14159265358979323846 * i) / kTableSize));
}
sSinInit = true;
}
int singleLoopSamples = 0;
for (const auto& n : song.notes) {
singleLoopSamples += (n.durationMs * kSampleRate) / 1000;
}
int interLoopGapSamples = (loops > 1) ? (kSampleRate / 5) : 0; // 200ms gap
int tailSamples = (kSampleRate * 30) / 1000; // 30ms tail
int totalFrames =
singleLoopSamples * loops + interLoopGapSamples * (loops - 1) + tailSamples;
if (totalFrames <= 0 || totalFrames > kSampleRate * 180) {
totalFrames = std::clamp(totalFrames, kSampleRate / 10, kSampleRate * 180);
}
std::vector<int16_t> pcm;
pcm.reserve(static_cast<size_t>(totalFrames) * kChannels);
float noteWave[kTableSize];
int lastMidi = -999;
for (int lp = 0; lp < loops; ++lp) {
for (const auto& n : song.notes) {
int slotFrames = (n.durationMs * kSampleRate) / 1000;
int toneFrames = std::min(slotFrames, (n.toneMs * kSampleRate) / 1000);
if (slotFrames <= 0) continue;
if (n.freqHz <= 20.0 || n.midiNote < 0 || toneFrames <= 0 ||
n.volume <= 0) {
pcm.insert(pcm.end(), static_cast<size_t>(slotFrames) * kChannels, 0);
continue;
}
// Rebuild band-limited mobile buzzer harmonic wavetable when pitch changes
if (n.midiNote != lastMidi) {
lastMidi = n.midiNote;
struct HarmSpec {
int mult;
float amp;
};
static const HarmSpec kHarms[] = {
{1, 1.00f},
{2, 0.32f},
{3, 0.46f},
{4, 0.12f},
{5, 0.22f},
{7, 0.10f},
};
std::fill(std::begin(noteWave), std::end(noteWave), 0.0f);
for (const auto& h : kHarms) {
if (n.freqHz * h.mult < 18000.0) {
for (int ti = 0; ti < kTableSize; ++ti) {
noteWave[ti] +=
h.amp * sSinTable[(ti * h.mult) & kTableMask];
}
}
}
float peak = 0.01f;
for (int ti = 0; ti < kTableSize; ++ti) {
peak = std::max(peak, std::fabs(noteWave[ti]));
}
float invPeak = 1.0f / peak;
for (int ti = 0; ti < kTableSize; ++ti) {
noteWave[ti] *= invPeak;
}
}
uint32_t phase = 0;
uint32_t phaseStep = static_cast<uint32_t>(
(n.freqHz * 4294967296.0) / static_cast<double>(kSampleRate) + 0.5);
int attackFrames = std::min(toneFrames / 3, (kSampleRate * 2) / 1000);
int releaseFrames = std::min(toneFrames / 3, (kSampleRate * 3) / 1000);
float baseGain =
(static_cast<float>(std::clamp(n.volume, 1, 15)) / 15.0f) * 24000.0f;
for (int f = 0; f < toneFrames; ++f) {
float env = 1.0f;
if (attackFrames > 0 && f < attackFrames) {
env = static_cast<float>(f) / static_cast<float>(attackFrames);
} else if (releaseFrames > 0 && f >= toneFrames - releaseFrames) {
env = static_cast<float>(toneFrames - 1 - f) /
static_cast<float>(releaseFrames);
} else {
// Subtle natural piezo decay over long notes
float prog = static_cast<float>(f) / static_cast<float>(toneFrames);
env = 1.0f - 0.14f * prog;
}
float sampleF =
noteWave[(phase >> 21) & kTableMask] * baseGain * env;
int16_t s16 = static_cast<int16_t>(
std::clamp(sampleF, -32760.0f, 32760.0f));
pcm.push_back(s16);
pcm.push_back(s16);
phase += phaseStep;
}
int silenceFrames = slotFrames - toneFrames;
if (silenceFrames > 0) {
pcm.insert(pcm.end(), static_cast<size_t>(silenceFrames) * kChannels, 0);
}
if (pcm.size() >= static_cast<size_t>(kSampleRate * 180 * kChannels)) {
break;
}
}
if (lp + 1 < loops && interLoopGapSamples > 0) {
pcm.insert(pcm.end(),
static_cast<size_t>(interLoopGapSamples) * kChannels, 0);
}
}
if (tailSamples > 0) {
pcm.insert(pcm.end(), static_cast<size_t>(tailSamples) * kChannels, 0);
}
std::ofstream ofs(wavOutPath, std::ios::binary | std::ios::trunc);
if (!ofs) return false;
uint32_t dataBytes = static_cast<uint32_t>(pcm.size() * sizeof(int16_t));
uint32_t riffSize = 36 + dataBytes;
uint32_t fmtChunkSize = 16;
uint16_t audioFormat = 1; // PCM
uint16_t numChannels = kChannels;
uint32_t sampleRate = kSampleRate;
uint32_t byteRate = kSampleRate * kChannels * sizeof(int16_t);
uint16_t blockAlign = kChannels * sizeof(int16_t);
uint16_t bitsPerSample = 16;
auto writeLe16 = [&](uint16_t v) {
char b[2] = {
static_cast<char>(v & 0xFF),
static_cast<char>((v >> 8) & 0xFF),
};
ofs.write(b, 2);
};
auto writeLe32 = [&](uint32_t v) {
char b[4] = {
static_cast<char>(v & 0xFF),
static_cast<char>((v >> 8) & 0xFF),
static_cast<char>((v >> 16) & 0xFF),
static_cast<char>((v >> 24) & 0xFF),
};
ofs.write(b, 4);
};
ofs.write("RIFF", 4);
writeLe32(riffSize);
ofs.write("WAVE", 4);
ofs.write("fmt ", 4);
writeLe32(fmtChunkSize);
writeLe16(audioFormat);
writeLe16(numChannels);
writeLe32(sampleRate);
writeLe32(byteRate);
writeLe16(blockAlign);
writeLe16(bitsPerSample);
ofs.write("data", 4);
writeLe32(dataBytes);
ofs.write(reinterpret_cast<const char*>(pcm.data()),
static_cast<std::streamsize>(dataBytes));
ofs.flush();
return ofs.good();
}
inline bool synthesizeMonotoneFileToWav(const std::string& inputPath,
const std::string& wavOutPath,
int loops = 1,
MonotoneSong* outSong = nullptr) {
MonotoneSong localSong;
MonotoneSong* target = outSong ? outSong : &localSong;
if (!parseMonotoneFile(inputPath, target)) {
return false;
}
return synthesizeMonotoneWav(*target, wavOutPath, loops);
}
} // namespace bananarchy
#endif // DWM_PLUGINS_MONOTONE_H