alpha2-engine 0.10.0

Player and exporter facade for alpha2.
Documentation
//! Loudness reports and normalization plans as the JSON every surface reads (`alpha2/loudness`).

use alpha2_audio::{LoudnessNormalization, LoudnessReport};

/// A report as the JSON `alpha2/loudness` reads.
#[must_use]
pub fn report_json(report: &LoudnessReport) -> String {
    report_value(report).to_string()
}

fn report_value(report: &LoudnessReport) -> serde_json::Value {
    serde_json::json!({
        "integratedLufs": report.integrated_lufs,
        "loudnessRangeLu": report.loudness_range_lu,
        "truePeakDbtp": report.true_peak_dbtp,
        "samplePeakDbfs": report.sample_peak_dbfs,
        "momentaryMaxLufs": report.momentary_max_lufs,
        "shortTermMaxLufs": report.short_term_max_lufs,
        "frames": report.frames,
    })
}

/// A report for a mix measured before its master limiter, plus `limiterThreshold` (linear,
/// `null` without a limiter), which a plan keeps the normalized mix under.
#[must_use]
pub fn mix_report_json(report: &LoudnessReport, limiter_threshold: Option<f64>) -> String {
    let mut value = report_value(report);
    value["limiterThreshold"] = serde_json::json!(limiter_threshold);
    value.to_string()
}

fn report_from_json(json: &str) -> Result<(LoudnessReport, Option<f64>), String> {
    let value: serde_json::Value = serde_json::from_str(json).map_err(|error| error.to_string())?;
    let Some(report) = value.as_object() else {
        return Err(
            "a loudness report is a JSON object; parse loudnessReport() before planning, and \
             measure with metering on"
                .to_owned(),
        );
    };
    let Some(frames) = report.get("frames").and_then(serde_json::Value::as_u64) else {
        return Err("a loudness report states the frames it measured".to_owned());
    };
    let limiter_threshold = match report.get("limiterThreshold") {
        None | Some(serde_json::Value::Null) => None,
        Some(threshold) => match threshold.as_f64() {
            Some(threshold) if threshold.is_finite() && threshold > 0.0 => Some(threshold),
            _ => {
                return Err(
                    "a loudness report's limiterThreshold is a positive number or null".to_owned(),
                );
            }
        },
    };
    let number = |key: &str| report.get(key).and_then(serde_json::Value::as_f64);
    Ok((
        LoudnessReport {
            integrated_lufs: number("integratedLufs"),
            loudness_range_lu: number("loudnessRangeLu"),
            true_peak_dbtp: number("truePeakDbtp"),
            sample_peak_dbfs: number("samplePeakDbfs"),
            momentary_max_lufs: number("momentaryMaxLufs"),
            short_term_max_lufs: number("shortTermMaxLufs"),
            frames,
        },
        limiter_threshold,
    ))
}

/// The gain that brings a measured mix (a report's JSON) to `target_lufs` without its true peak
/// passing `ceiling_dbtp` or its sample peak reaching the report's `limiterThreshold`. Returns
/// JSON `{ gainDb, integratedLufs, truePeakDbtp, peakLimited, limiterLimited }`, or `null` for a
/// mix silent below the absolute gate.
///
/// # Errors
/// Refuses a report that is not a JSON object with `frames`, or whose `limiterThreshold` is
/// neither a positive number nor `null`.
pub fn plan_normalization_json(
    report_json: &str,
    target_lufs: f64,
    ceiling_dbtp: f64,
) -> Result<String, String> {
    let (report, limiter_threshold) = report_from_json(report_json)?;
    Ok(
        LoudnessNormalization::plan(&report, target_lufs, ceiling_dbtp, limiter_threshold)
            .map_or_else(
                || "null".to_owned(),
                |plan| {
                    serde_json::json!({
                        "gainDb": plan.gain_db,
                        "integratedLufs": plan.integrated_lufs,
                        "truePeakDbtp": plan.true_peak_dbtp,
                        "peakLimited": plan.peak_limited,
                        "limiterLimited": plan.limiter_limited,
                    })
                    .to_string()
                },
            ),
    )
}