mod compile;
mod de;
mod facts;
mod library;
mod lower;
#[cfg(feature = "schema")]
mod schema;
pub mod spec;
mod svg_path;
pub mod template;
#[cfg(test)]
mod tests;
mod theme;
use std::collections::BTreeMap;
use std::fmt;
use std::sync::Arc;
use alpha2_model::Project;
use serde::{Deserialize, Serialize};
pub use facts::{Facts, MediaFacts, RequiredMedia, Requirements, kind_of_path, requirements};
#[cfg(feature = "schema")]
pub use schema::{
COMPOSE_CORE_SCHEMA_ID, COMPOSE_SCHEMA_ID, compose_core_json_schema, compose_json_schema,
};
pub use spec::{COMPOSE_VERSION, VideoSpec};
pub use theme::THEMES;
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ComposeError {
pub path: String,
pub message: String,
}
impl ComposeError {
pub(crate) fn new(path: &str, message: impl Into<String>) -> Self {
Self {
path: path.to_owned(),
message: message.into(),
}
}
}
impl fmt::Display for ComposeError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "{}: {}", self.path, self.message)
}
}
impl std::error::Error for ComposeError {}
#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Serialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
#[serde(deny_unknown_fields)]
pub struct LoudnessTarget {
pub target_lufs: f64,
#[serde(default = "default_ceiling")]
pub true_peak_ceiling_dbtp: f64,
}
pub const DEFAULT_TRUE_PEAK_CEILING_DBTP: f64 = -1.0;
const fn default_ceiling() -> f64 {
DEFAULT_TRUE_PEAK_CEILING_DBTP
}
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct Compiled {
pub project: Project,
pub assets: BTreeMap<String, String>,
pub loudness: Option<LoudnessTarget>,
pub warnings: Vec<String>,
}
pub fn compile(
spec: &VideoSpec,
facts: &Facts,
fonts: &[Arc<[u8]>],
) -> Result<Compiled, ComposeError> {
if let Some(loudness) = spec.loudness {
let (target, ceiling) = match loudness {
spec::Loudness::Lufs(target) => (target, default_ceiling()),
spec::Loudness::Target(target) => (target.target_lufs, target.true_peak_ceiling_dbtp),
};
if !(-60.0..=0.0).contains(&target) || !(-20.0..=0.0).contains(&ceiling) {
return Err(ComposeError::new(
"spec.loudness",
format!(
"{target} LUFS under {ceiling} dBTP: the target is -60..=0 LUFS and the ceiling -20..=0 dBTP"
),
));
}
}
compile::compile(spec, facts, fonts)
}
pub fn parse_spec(json: &str) -> Result<VideoSpec, ComposeError> {
parse(json, "spec")
}
pub fn parse_facts(json: &str) -> Result<Facts, ComposeError> {
parse(json, "facts")
}
fn parse<T: serde::de::DeserializeOwned>(json: &str, root: &str) -> Result<T, ComposeError> {
let value =
serde_json::from_str(json).map_err(|error| ComposeError::new(root, error.to_string()))?;
de::from_value(value)
.map_err(|located| ComposeError::new(&de::join(root, &located.path), located.message))
}
pub fn compile_json(spec: &str, facts: &str, fonts: &[Arc<[u8]>]) -> Result<String, ComposeError> {
let spec = parse_spec(&expand_builtins(spec)?)?;
let facts = parse_facts(facts)?;
let compiled = compile(&spec, &facts, fonts)?;
let project = compiled
.project
.to_json()
.map_err(|error| ComposeError::new("spec", error.to_string()))?;
Ok(format!(
"{{\"project\":{project},\"assets\":{},\"loudness\":{},\"warnings\":{}}}",
part(&compiled.assets),
part(&compiled.loudness),
part(&compiled.warnings),
))
}
fn part<T: Serialize>(value: &T) -> String {
serde_json::to_string(value).expect("assets, loudness and warnings serialize")
}
pub fn media_facts_json(fingerprint: &str) -> Result<String, ComposeError> {
let fingerprint: alpha2_model::MediaFingerprint = parse(fingerprint, "fingerprint")?;
Ok(
serde_json::to_string(&MediaFacts::from_fingerprint(&fingerprint))
.expect("facts serialize"),
)
}
pub fn requirements_json(spec: &str) -> Result<String, ComposeError> {
let spec = parse_spec(&expand_builtins(spec)?)?;
Ok(serde_json::to_string(&requirements(&spec)).expect("requirements serialize"))
}
fn expand_builtins(spec: &str) -> Result<String, ComposeError> {
let value: serde_json::Value =
serde_json::from_str(spec).map_err(|error| ComposeError::new("spec", error.to_string()))?;
Ok(template::bind(
&value,
&serde_json::Value::Null,
&template::BindOptions::default(),
)?
.to_string())
}
fn json_value(json: &str, root: &str) -> Result<serde_json::Value, ComposeError> {
serde_json::from_str(json).map_err(|error| ComposeError::new(root, error.to_string()))
}
fn bind_options(options: &str) -> Result<template::BindOptions, ComposeError> {
let options = json_value(options, "options")?;
Ok(template::BindOptions {
theme: options
.get("theme")
.filter(|theme| !theme.is_null())
.cloned(),
templates: options
.get("templates")
.and_then(serde_json::Value::as_array)
.cloned()
.unwrap_or_default(),
})
}
pub fn bind_json(document: &str, data: &str, options: &str) -> Result<String, ComposeError> {
let bound = template::bind(
&json_value(document, "template")?,
&json_value(data, "data")?,
&bind_options(options)?,
)?;
Ok(bound.to_string())
}
pub fn data_schema_json(template: &str) -> Result<String, ComposeError> {
Ok(template::data_schema(&json_value(template, "template")?)?.to_string())
}
pub fn lint_json(template: &str, data: &str, options: &str) -> Result<String, ComposeError> {
let data = if data.trim().is_empty() {
None
} else {
Some(json_value(data, "data")?)
};
let issues = template::lint(
&json_value(template, "template")?,
data.as_ref(),
&bind_options(options)?.templates,
);
Ok(serde_json::to_string(&issues).expect("issues serialize"))
}
#[must_use]
pub fn templates_json() -> String {
serde_json::Value::Array(library::TEMPLATES.clone()).to_string()
}