use std::borrow::Cow;
use serde::Serialize;
use crate::compiler::diagnostic::{Diagnostic, Severity};
use crate::synth::{OptionKind, Scope, SynthSpec};
#[derive(Debug, Clone, PartialEq)]
pub struct CheckReport {
pub ok: bool,
pub errors: usize,
pub warnings: usize,
pub diagnostics: Vec<Diagnostic>,
pub lang: &'static str,
pub messages: Vec<String>,
}
impl CheckReport {
pub fn new(diagnostics: Vec<Diagnostic>) -> Self {
let errors = diagnostics
.iter()
.filter(|d| d.severity == Severity::Error)
.count();
CheckReport {
ok: errors == 0,
errors,
warnings: diagnostics.len() - errors,
diagnostics,
lang: crate::text::DEFAULT_LANG,
messages: Vec::new(),
}
}
pub fn in_lang(mut self, lang: &'static str) -> Self {
self.lang = lang;
self
}
pub fn with_messages(mut self, mut f: impl FnMut(&Diagnostic) -> String) -> Self {
self.messages = self.diagnostics.iter().map(&mut f).collect();
self
}
}
impl Serialize for CheckReport {
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
use serde::ser::{SerializeSeq, SerializeStruct};
struct Diags<'a>(&'a [Diagnostic], &'a str, &'a [String]);
impl Serialize for Diags<'_> {
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
let mut seq = s.serialize_seq(Some(self.0.len()))?;
for (i, d) in self.0.iter().enumerate() {
let l = d.in_lang(self.1);
match self.2.get(i) {
Some(m) => seq.serialize_element(&l.with_message(m))?,
None => seq.serialize_element(&l)?,
}
}
seq.end()
}
}
let mut st = s.serialize_struct("CheckReport", 4)?;
st.serialize_field("ok", &self.ok)?;
st.serialize_field("errors", &self.errors)?;
st.serialize_field("warnings", &self.warnings)?;
st.serialize_field(
"diagnostics",
&Diags(&self.diagnostics, self.lang, &self.messages),
)?;
st.end()
}
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct SynthDescription {
pub name: &'static str,
pub aliases: &'static [&'static str],
pub description: Cow<'static, str>,
pub max_tracks: usize,
pub polyphony: u8,
pub default_tone: u8,
pub tones: Vec<ToneDescription>,
pub params: Vec<ParamDescription>,
pub options: Vec<OptionDescription>,
pub presets: Vec<PresetDescription>,
pub knobs: Vec<KnobDescription>,
pub library: Vec<LibraryToneDescription>,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct LibraryToneDescription {
pub name: &'static str,
pub kind: &'static str,
pub file: String,
pub description: Cow<'static, str>,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct KnobDescription {
pub name: &'static str,
pub label: Cow<'static, str>,
pub description: Cow<'static, str>,
pub targets: Vec<KnobTarget>,
pub steps: i32,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub struct KnobTarget {
pub param: &'static str,
pub per_step: i32,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct PresetDescription {
pub name: &'static str,
pub kind: &'static str,
pub description: Cow<'static, str>,
#[serde(rename = "macro")]
pub macro_line: String,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct ToneDescription {
pub id: u8,
pub description: Cow<'static, str>,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct ParamDescription {
pub name: &'static str,
pub min: u32,
pub max: u32,
pub default: u32,
pub scope: Scope,
pub description: Cow<'static, str>,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct OptionDescription {
pub name: &'static str,
pub values: String,
pub default: &'static str,
pub description: Cow<'static, str>,
}
fn option_values(k: &OptionKind, range: &str) -> String {
match k {
OptionKind::Range { min, max } => format!("{min}{range}{max}"),
OptionKind::Choice(c) => c.join(" / "),
}
}
pub fn synth_catalog(synths: &[&SynthSpec]) -> Vec<SynthDescription> {
synth_catalog_in(synths, crate::text::DEFAULT_LANG)
}
pub fn synth_catalog_in(synths: &[&SynthSpec], lang: &str) -> Vec<SynthDescription> {
synth_catalog_with(synths, lang, &mut |_| None)
}
pub fn synth_catalog_with(
synths: &[&SynthSpec],
lang: &str,
text: &mut dyn FnMut(&str) -> Option<String>,
) -> Vec<SynthDescription> {
let range: Cow<'static, str> = match text("term-range") {
Some(t) => Cow::Owned(t),
None => match crate::compiler::diagnostic::lookup(lang, "term-range") {
Some([crate::text::Seg::Lit(t)]) => Cow::Borrowed(t),
_ => Cow::Borrowed("-"),
},
};
use crate::synth::text_key;
let mut pick = |key: String, own: &'static str| -> Cow<'static, str> {
match text(&key) {
Some(t) => Cow::Owned(t),
None => Cow::Borrowed(own),
}
};
synths
.iter()
.map(|c| SynthDescription {
name: c.name,
aliases: c.aliases,
description: pick(text_key::synth(c.name), c.description(lang)),
max_tracks: c.max_tracks,
polyphony: c.polyphony,
default_tone: c.default_tone,
tones: c
.tones
.iter()
.map(|t| ToneDescription {
id: t.id,
description: pick(text_key::tone(c.name, t.id), c.tone_description(t.id, lang)),
})
.collect(),
params: c
.params
.iter()
.map(|p| ParamDescription {
name: p.name,
min: p.min,
max: p.max,
default: p.default,
scope: p.scope,
description: pick(
text_key::param(c.name, p.name),
c.param_description(p.name, lang),
),
})
.collect(),
options: c
.options
.iter()
.map(|o| OptionDescription {
name: o.name,
values: option_values(&o.kind, &range),
default: o.default,
description: pick(
text_key::option(c.name, o.name),
c.option_description(o.name, lang),
),
})
.collect(),
presets: c
.presets
.iter()
.map(|p| PresetDescription {
name: p.name,
kind: p.kind,
description: pick(
c.preset_text_key(p.name),
c.preset_description(p.name, lang),
),
macro_line: p.macro_line(),
})
.collect(),
knobs: c
.knobs
.iter()
.map(|k| KnobDescription {
name: k.name,
label: pick(text_key::knob(c.name, k.name), c.knob_label(k.name, lang)),
description: pick(
text_key::knob_help(c.name, k.name),
c.knob_description(k.name, lang),
),
targets: k
.targets
.iter()
.map(|&(param, per_step)| KnobTarget { param, per_step })
.collect(),
steps: crate::synth::KNOB_STEPS,
})
.collect(),
library: crate::synth::tones::tones(c)
.into_iter()
.map(|t| LibraryToneDescription {
name: t.name,
kind: t.kind,
file: t.path(),
description: pick(t.text_key(), c.library_description(t.name, lang)),
})
.collect(),
})
.collect()
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct BuildSizes {
pub total: usize,
pub header: usize,
pub envelopes: usize,
pub tracks: Vec<(String, usize)>,
pub uncompressed: usize,
}
impl BuildSizes {
pub fn new(song: &crate::Song, stats: &crate::export::binary::EncodeStats) -> Self {
BuildSizes {
total: stats.total,
header: stats.header,
envelopes: stats.envelopes,
tracks: song
.tracks
.iter()
.cloned()
.zip(stats.tracks.iter().copied())
.collect(),
uncompressed: stats.header + stats.uncompressed.iter().sum::<usize>(),
}
}
}
#[derive(Debug, Clone, PartialEq, serde::Serialize)]
pub struct AudioStats {
pub peak: f32,
pub rms: f32,
pub clipped_frames: usize,
pub silent: bool,
pub silent_head_secs: f64,
pub silent_tail_secs: f64,
}
const SILENCE: f32 = 1e-3;
pub fn audio_stats(samples: &[[f32; 2]], sample_rate: u32) -> AudioStats {
let mut peak = 0.0f32;
let mut sum_sq = 0.0f64;
let mut clipped = 0usize;
let mut first: Option<usize> = None;
let mut last = 0usize;
for (i, f) in samples.iter().enumerate() {
let m = f[0].abs().max(f[1].abs());
peak = peak.max(m);
sum_sq += f64::from(f[0]).powi(2) + f64::from(f[1]).powi(2);
if m >= 1.0 {
clipped += 1;
}
if m > SILENCE {
first.get_or_insert(i);
last = i;
}
}
let rms = if samples.is_empty() {
0.0
} else {
(sum_sq / (samples.len() as f64 * 2.0)).sqrt() as f32
};
let sr = f64::from(sample_rate.max(1));
match first {
None => AudioStats {
peak,
rms,
clipped_frames: clipped,
silent: true,
silent_head_secs: samples.len() as f64 / sr,
silent_tail_secs: 0.0,
},
Some(f) => AudioStats {
peak,
rms,
clipped_frames: clipped,
silent: false,
silent_head_secs: f as f64 / sr,
silent_tail_secs: (samples.len() - 1 - last) as f64 / sr,
},
}
}
pub mod tools {
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Texts {
pub get_spec: &'static str,
pub list_synths: &'static str,
pub check_mml: &'static str,
pub describe_mml: &'static str,
pub build_mml: &'static str,
pub render_mml: &'static str,
pub edit_timbre: &'static str,
pub measure_tone: &'static str,
pub get_tones: &'static str,
pub format_mml: &'static str,
pub guide: &'static str,
}
fn get(key: &str, lang: &str) -> &'static str {
match crate::compiler::diagnostic::lookup(lang, key) {
Some([crate::text::Seg::Lit(t)]) => t,
_ => "",
}
}
pub fn for_lang(lang: &str) -> Texts {
let lang = if crate::is_japanese(lang) { "ja" } else { "en" };
Texts {
get_spec: get("tool-get-spec", lang),
list_synths: get("tool-list-synths", lang),
check_mml: get("tool-check-mml", lang),
describe_mml: get("tool-describe-mml", lang),
build_mml: get("tool-build-mml", lang),
render_mml: get("tool-render-mml", lang),
edit_timbre: get("tool-edit-timbre", lang),
measure_tone: get("tool-measure-tone", lang),
get_tones: get("tool-get-tones", lang),
format_mml: get("tool-format-mml", lang),
guide: get("tool-guide", lang),
}
}
pub fn param(name: &str, lang: &str) -> Option<&'static str> {
let lang = if crate::is_japanese(lang) { "ja" } else { "en" };
let t = get(&format!("tool-param-{}", name.replace('_', "-")), lang);
(!t.is_empty()).then_some(t)
}
}