Skip to main content

alpha2_engine/
loudness.rs

1//! Loudness reports and normalization plans as the JSON every surface reads (`alpha2/loudness`).
2
3use alpha2_audio::{LoudnessNormalization, LoudnessReport};
4
5/// A report as the JSON `alpha2/loudness` reads.
6#[must_use]
7pub fn report_json(report: &LoudnessReport) -> String {
8    report_value(report).to_string()
9}
10
11fn report_value(report: &LoudnessReport) -> serde_json::Value {
12    serde_json::json!({
13        "integratedLufs": report.integrated_lufs,
14        "loudnessRangeLu": report.loudness_range_lu,
15        "truePeakDbtp": report.true_peak_dbtp,
16        "samplePeakDbfs": report.sample_peak_dbfs,
17        "momentaryMaxLufs": report.momentary_max_lufs,
18        "shortTermMaxLufs": report.short_term_max_lufs,
19        "frames": report.frames,
20    })
21}
22
23/// A report for a mix measured before its master limiter, plus `limiterThreshold` (linear,
24/// `null` without a limiter), which a plan keeps the normalized mix under.
25#[must_use]
26pub fn mix_report_json(report: &LoudnessReport, limiter_threshold: Option<f64>) -> String {
27    let mut value = report_value(report);
28    value["limiterThreshold"] = serde_json::json!(limiter_threshold);
29    value.to_string()
30}
31
32fn report_from_json(json: &str) -> Result<(LoudnessReport, Option<f64>), String> {
33    let value: serde_json::Value = serde_json::from_str(json).map_err(|error| error.to_string())?;
34    let Some(report) = value.as_object() else {
35        return Err(
36            "a loudness report is a JSON object; parse loudnessReport() before planning, and \
37             measure with metering on"
38                .to_owned(),
39        );
40    };
41    let Some(frames) = report.get("frames").and_then(serde_json::Value::as_u64) else {
42        return Err("a loudness report states the frames it measured".to_owned());
43    };
44    let limiter_threshold = match report.get("limiterThreshold") {
45        None | Some(serde_json::Value::Null) => None,
46        Some(threshold) => match threshold.as_f64() {
47            Some(threshold) if threshold.is_finite() && threshold > 0.0 => Some(threshold),
48            _ => {
49                return Err(
50                    "a loudness report's limiterThreshold is a positive number or null".to_owned(),
51                );
52            }
53        },
54    };
55    let number = |key: &str| report.get(key).and_then(serde_json::Value::as_f64);
56    Ok((
57        LoudnessReport {
58            integrated_lufs: number("integratedLufs"),
59            loudness_range_lu: number("loudnessRangeLu"),
60            true_peak_dbtp: number("truePeakDbtp"),
61            sample_peak_dbfs: number("samplePeakDbfs"),
62            momentary_max_lufs: number("momentaryMaxLufs"),
63            short_term_max_lufs: number("shortTermMaxLufs"),
64            frames,
65        },
66        limiter_threshold,
67    ))
68}
69
70/// The gain that brings a measured mix (a report's JSON) to `target_lufs` without its true peak
71/// passing `ceiling_dbtp` or its sample peak reaching the report's `limiterThreshold`. Returns
72/// JSON `{ gainDb, integratedLufs, truePeakDbtp, peakLimited, limiterLimited }`, or `null` for a
73/// mix silent below the absolute gate.
74///
75/// # Errors
76/// Refuses a report that is not a JSON object with `frames`, or whose `limiterThreshold` is
77/// neither a positive number nor `null`.
78pub fn plan_normalization_json(
79    report_json: &str,
80    target_lufs: f64,
81    ceiling_dbtp: f64,
82) -> Result<String, String> {
83    let (report, limiter_threshold) = report_from_json(report_json)?;
84    Ok(
85        LoudnessNormalization::plan(&report, target_lufs, ceiling_dbtp, limiter_threshold)
86            .map_or_else(
87                || "null".to_owned(),
88                |plan| {
89                    serde_json::json!({
90                        "gainDb": plan.gain_db,
91                        "integratedLufs": plan.integrated_lufs,
92                        "truePeakDbtp": plan.true_peak_dbtp,
93                        "peakLimited": plan.peak_limited,
94                        "limiterLimited": plan.limiter_limited,
95                    })
96                    .to_string()
97                },
98            ),
99    )
100}