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