Skip to main content

alpha2_compose/
lib.rs

1//! Compose specs: a video described by intent, compiled into a plain project document.
2//!
3//! [`compile`] turns a [`VideoSpec`] into an [`alpha2_model::Project`] that
4//! [`alpha2_model::Project::validate`] accepts, plus the export options the project does not
5//! hold.
6//!
7//! Compiling is pure and reads no files. Facts about the files a spec names come in as
8//! [`Facts`], gathered by a binding from [`requirements`]. The same spec, facts, fonts and
9//! compiler version give a byte-identical project.
10//!
11//! A spec has no logic. A [`template`] adds parameters, `$if`, `$switch`, `$each` and `{{name}}`,
12//! which binding removes. Components that take any number of inputs are Rust code here.
13
14mod compile;
15mod de;
16pub mod diagnose;
17mod facts;
18mod library;
19mod lower;
20#[cfg(feature = "schema")]
21mod schema;
22pub mod spec;
23mod svg_path;
24pub mod template;
25#[cfg(test)]
26mod tests;
27mod theme;
28
29use std::collections::BTreeMap;
30use std::fmt;
31use std::sync::Arc;
32
33use alpha2_model::Project;
34use serde::{Deserialize, Serialize};
35
36pub use diagnose::{diagnose_json, diagnose_json_with_fonts, diagnose_spec, diagnose_template};
37pub use facts::{Facts, MediaFacts, RequiredMedia, Requirements, kind_of_path, requirements};
38#[cfg(feature = "schema")]
39pub use schema::{
40    COMPOSE_CORE_SCHEMA_ID, COMPOSE_SCHEMA_ID, compose_core_json_schema, compose_json_schema,
41    compose_shape_json,
42};
43pub use spec::{COMPOSE_VERSION, VideoSpec};
44pub use theme::THEMES;
45
46/// Why a spec does not compile, and where.
47#[derive(Clone, Debug, Eq, PartialEq)]
48pub struct ComposeError {
49    /// Where in the spec, as `spec.body.children[2].path`.
50    pub path: String,
51    /// What is wrong there.
52    pub message: String,
53}
54
55impl ComposeError {
56    pub(crate) fn new(path: &str, message: impl Into<String>) -> Self {
57        Self {
58            path: path.to_owned(),
59            message: message.into(),
60        }
61    }
62}
63
64impl fmt::Display for ComposeError {
65    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
66        write!(formatter, "{}: {}", self.path, self.message)
67    }
68}
69
70impl std::error::Error for ComposeError {}
71
72/// The loudness an export normalizes to.
73#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
74#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
75#[serde(deny_unknown_fields)]
76pub struct LoudnessTarget {
77    /// Integrated loudness, -60..=0 LUFS.
78    pub target_lufs: f64,
79    /// True-peak ceiling, -20..=0 dBTP. Default -1.
80    #[serde(default = "default_ceiling")]
81    pub true_peak_ceiling_dbtp: f64,
82}
83
84/// The true-peak ceiling a loudness target without one takes, in dBTP: EBU R128's.
85pub const DEFAULT_TRUE_PEAK_CEILING_DBTP: f64 = -1.0;
86
87const fn default_ceiling() -> f64 {
88    DEFAULT_TRUE_PEAK_CEILING_DBTP
89}
90
91/// A compiled spec: the project, and what an export of it needs besides.
92#[derive(Clone, Debug, PartialEq, Serialize)]
93pub struct Compiled {
94    /// The project document.
95    pub project: Project,
96    /// Each media source's file, by source id: an export's assets.
97    pub assets: BTreeMap<String, String>,
98    /// The loudness the spec asks an export to normalize to.
99    pub loudness: Option<LoudnessTarget>,
100    /// What the compiler did not do as asked, and why.
101    pub warnings: Vec<Warning>,
102}
103
104/// Something the compiler did not do as asked, and where. Serialized as `path: message`.
105#[derive(Clone, Debug, PartialEq, Eq)]
106pub struct Warning {
107    /// The diagnostic code of its kind.
108    pub code: &'static alpha2_diagnose::Code,
109    /// Where in the spec, as `spec.body.children[2]`.
110    pub path: String,
111    /// What was not done, and why.
112    pub message: String,
113}
114
115impl fmt::Display for Warning {
116    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
117        write!(formatter, "{}: {}", self.path, self.message)
118    }
119}
120
121impl Serialize for Warning {
122    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
123        serializer.collect_str(self)
124    }
125}
126
127/// Compiles `spec` with `facts` about its files.
128///
129/// `fonts` are the font files an export registers, in fallback order; with them, text that
130/// must fit is measured and shrunk to fit.
131///
132/// A spec either compiles to a project that [`Project::from_json`] loads, or fails here.
133///
134/// # Errors
135/// Returns where in the spec, and why, it cannot be compiled.
136pub fn compile(
137    spec: &VideoSpec,
138    facts: &Facts,
139    fonts: &[Arc<[u8]>],
140) -> Result<Compiled, ComposeError> {
141    if let Some(loudness) = spec.loudness {
142        let (target, ceiling) = match loudness {
143            spec::Loudness::Lufs(target) => (target, default_ceiling()),
144            spec::Loudness::Target(target) => (target.target_lufs, target.true_peak_ceiling_dbtp),
145        };
146        if !(-60.0..=0.0).contains(&target) || !(-20.0..=0.0).contains(&ceiling) {
147            return Err(ComposeError::new(
148                "spec.loudness",
149                format!(
150                    "{target} LUFS under {ceiling} dBTP: the target is -60..=0 LUFS and the ceiling -20..=0 dBTP"
151                ),
152            ));
153        }
154    }
155    compile::compile(spec, facts, fonts)
156}
157
158/// Parses a spec from JSON, naming where an unparsable value lies.
159///
160/// # Errors
161/// Returns the place and the parser's reason.
162pub fn parse_spec(json: &str) -> Result<VideoSpec, ComposeError> {
163    parse(json, "spec")
164}
165
166/// Parses facts from JSON.
167///
168/// # Errors
169/// Returns the place and the parser's reason.
170pub fn parse_facts(json: &str) -> Result<Facts, ComposeError> {
171    parse(json, "facts")
172}
173
174fn parse<T: serde::de::DeserializeOwned>(json: &str, root: &str) -> Result<T, ComposeError> {
175    let value =
176        serde_json::from_str(json).map_err(|error| ComposeError::new(root, error.to_string()))?;
177    de::from_value(value)
178        .map_err(|located| ComposeError::new(&de::join(root, &located.path), located.message))
179}
180
181/// [`compile`] across a JSON boundary. The result is `{project, assets, loudness, warnings}`.
182///
183/// # Errors
184/// Returns where in the spec or facts, and why, they do not parse or compile, and refuses a
185/// project longer than a project document may be at `spec`.
186///
187/// # Panics
188/// Never; the parts besides the project always serialize.
189pub fn compile_json(spec: &str, facts: &str, fonts: &[Arc<[u8]>]) -> Result<String, ComposeError> {
190    let spec = parse_spec(&expand_builtins(spec)?)?;
191    let facts = parse_facts(facts)?;
192    let compiled = compile(&spec, &facts, fonts)?;
193    let project = compiled
194        .project
195        .to_json()
196        .map_err(|error| ComposeError::new("spec", error.to_string()))?;
197    // The same bytes as serializing `Compiled` whole, with the project written through its cap.
198    Ok(format!(
199        "{{\"project\":{project},\"assets\":{},\"loudness\":{},\"warnings\":{}}}",
200        part(&compiled.assets),
201        part(&compiled.loudness),
202        part(&compiled.warnings),
203    ))
204}
205
206fn part<T: Serialize>(value: &T) -> String {
207    serde_json::to_string(value).expect("assets, loudness and warnings serialize")
208}
209
210/// [`MediaFacts::from_fingerprint`] across a JSON boundary: a host's fingerprint of a file in,
211/// its facts out.
212///
213/// # Errors
214/// Returns where the fingerprint does not parse.
215///
216/// # Panics
217/// Never; facts always serialize.
218pub fn media_facts_json(fingerprint: &str) -> Result<String, ComposeError> {
219    let fingerprint: alpha2_model::MediaFingerprint = parse(fingerprint, "fingerprint")?;
220    Ok(
221        serde_json::to_string(&MediaFacts::from_fingerprint(&fingerprint))
222            .expect("facts serialize"),
223    )
224}
225
226/// [`requirements`] across a JSON boundary.
227///
228/// # Errors
229/// Returns where in the spec, and why, it does not parse.
230///
231/// # Panics
232/// Never; requirements always serialize.
233pub fn requirements_json(spec: &str) -> Result<String, ComposeError> {
234    let spec = parse_spec(&expand_builtins(spec)?)?;
235    Ok(serde_json::to_string(&requirements(&spec)).expect("requirements serialize"))
236}
237
238/// `spec` with its 1st-party template nodes expanded (`alpha2/` ids and their bare names).
239fn expand_builtins(spec: &str) -> Result<String, ComposeError> {
240    let value: serde_json::Value =
241        serde_json::from_str(spec).map_err(|error| ComposeError::new("spec", error.to_string()))?;
242    Ok(template::bind(
243        &value,
244        &serde_json::Value::Null,
245        &template::BindOptions::default(),
246    )?
247    .to_string())
248}
249
250fn json_value(json: &str, root: &str) -> Result<serde_json::Value, ComposeError> {
251    serde_json::from_str(json).map_err(|error| ComposeError::new(root, error.to_string()))
252}
253
254fn bind_options(options: &str) -> Result<template::BindOptions, ComposeError> {
255    let options = json_value(options, "options")?;
256    Ok(template::BindOptions {
257        theme: options
258            .get("theme")
259            .filter(|theme| !theme.is_null())
260            .cloned(),
261        templates: options
262            .get("templates")
263            .and_then(serde_json::Value::as_array)
264            .cloned()
265            .unwrap_or_default(),
266    })
267}
268
269/// [`template::bind`] across a JSON boundary: `options` is `{theme?, templates?}`.
270///
271/// # Errors
272/// Returns where in the template, data or options, and why, they do not bind.
273pub fn bind_json(document: &str, data: &str, options: &str) -> Result<String, ComposeError> {
274    let bound = template::bind(
275        &json_value(document, "template")?,
276        &json_value(data, "data")?,
277        &bind_options(options)?,
278    )?;
279    Ok(bound.to_string())
280}
281
282/// [`template::data_schema`] across a JSON boundary.
283///
284/// # Errors
285/// Returns where the template does not parse.
286pub fn data_schema_json(template: &str) -> Result<String, ComposeError> {
287    Ok(template::data_schema(&json_value(template, "template")?)?.to_string())
288}
289
290/// [`template::lint`] across a JSON boundary: `data` may be empty for none, and `options` is
291/// `{templates?}`. Returns the diagnostics as a JSON list.
292///
293/// # Errors
294/// Returns where the template, data or options are not JSON.
295///
296/// # Panics
297/// Never; issues always serialize.
298pub fn lint_json(template: &str, data: &str, options: &str) -> Result<String, ComposeError> {
299    let data = if data.trim().is_empty() {
300        None
301    } else {
302        Some(json_value(data, "data")?)
303    };
304    let issues = template::lint(
305        &json_value(template, "template")?,
306        data.as_ref(),
307        &bind_options(options)?.templates,
308    );
309    Ok(serde_json::to_string(&issues).expect("issues serialize"))
310}
311
312/// The 1st-party `alpha2/` templates, as a JSON list.
313#[must_use]
314pub fn templates_json() -> String {
315    serde_json::Value::Array(library::TEMPLATES.clone()).to_string()
316}