1mod 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#[derive(Clone, Debug, Eq, PartialEq)]
48pub struct ComposeError {
49 pub path: String,
51 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#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
74#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
75#[serde(deny_unknown_fields)]
76pub struct LoudnessTarget {
77 pub target_lufs: f64,
79 #[serde(default = "default_ceiling")]
81 pub true_peak_ceiling_dbtp: f64,
82}
83
84pub const DEFAULT_TRUE_PEAK_CEILING_DBTP: f64 = -1.0;
86
87const fn default_ceiling() -> f64 {
88 DEFAULT_TRUE_PEAK_CEILING_DBTP
89}
90
91#[derive(Clone, Debug, PartialEq, Serialize)]
93pub struct Compiled {
94 pub project: Project,
96 pub assets: BTreeMap<String, String>,
98 pub loudness: Option<LoudnessTarget>,
100 pub warnings: Vec<Warning>,
102}
103
104#[derive(Clone, Debug, PartialEq, Eq)]
106pub struct Warning {
107 pub code: &'static alpha2_diagnose::Code,
109 pub path: String,
111 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
127pub 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
158pub fn parse_spec(json: &str) -> Result<VideoSpec, ComposeError> {
163 parse(json, "spec")
164}
165
166pub 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
181pub 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 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
210pub 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
226pub 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
238fn 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
269pub 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
282pub fn data_schema_json(template: &str) -> Result<String, ComposeError> {
287 Ok(template::data_schema(&json_value(template, "template")?)?.to_string())
288}
289
290pub 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#[must_use]
314pub fn templates_json() -> String {
315 serde_json::Value::Array(library::TEMPLATES.clone()).to_string()
316}