lumen-engine 0.2.2

Core composition model and rendering orchestration for Lumen.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
//! JSON deserialization for Lumen compositions.
//!
//! Parses a JSON object into a [`Composition`] containing a validated [`Graph`]
//! of renderer-agnostic nodes and connections.
//!
//! # Modules
//!
//! - [`property`] — JSON value → [`PropertyValue`](crate::node::PropertyValue) conversion
//! - [`node`] — per-node-type construction, property application, and port wiring

mod migrations;
mod node;
mod property;

use anyhow::{Context, Result};
use serde_json::{Map, Value};

use crate::{
    audio::{AudioClip, AudioTimeline, AudioTrack},
    composition::{Composition, CompositionMetadata, RenderSettings, TimelineSettings},
    graph::{Connection, Graph},
    node::NodeId,
};

pub use property::parse_color;
pub(crate) use property::parse_property;

/// Parse a JSON string into a [`Composition`].
pub fn parse(json: &str) -> Result<Composition> {
    let root: Value = serde_json::from_str(json).context("invalid JSON")?;
    parse_value(&root)
}

/// Parse a [`serde_json::Value`] into a [`Composition`].
pub fn parse_value(root: &Value) -> Result<Composition> {
    let migrated = migrations::migrate_to_current(root)?;
    parse_current_value(&migrated)
}

fn parse_current_value(root: &Value) -> Result<Composition> {
    let obj = root.as_object().context("root must be an object")?;
    let timeline = parse_timeline(obj.get("timeline").context("missing `timeline`")?)?;
    let render_settings = parse_render_settings(
        obj.get("render_settings")
            .context("missing `render_settings`")?,
    )?;

    let nodes_arr = obj
        .get("nodes")
        .and_then(|v| v.as_array())
        .context("`nodes` must be an array")?;
    let connections_arr = obj
        .get("connections")
        .and_then(|v| v.as_array())
        .context("`connections` must be an array")?;

    let mut graph = Graph::new();

    // First pass: create all nodes
    for node_val in nodes_arr {
        let node_obj = node_val.as_object().context("node must be an object")?;
        let id = parse_node_id(node_obj.get("id").context("node missing `id`")?)?;
        let kind_str = node_obj
            .get("type")
            .and_then(|v| v.as_str())
            .context("node missing `type` string")?;

        let node_kind = node::build_node(kind_str, id, node_obj)?;
        graph.nodes.insert(id, node_kind);
    }

    // Second pass: create connections and wire up PortRefs
    for conn_val in connections_arr {
        let conn_obj = conn_val
            .as_object()
            .context("connection must be an object")?;
        let from_node = parse_node_id(conn_obj.get("from_node").context("missing `from_node`")?)?;
        let from_port = conn_obj
            .get("from_port")
            .and_then(|v| v.as_str())
            .unwrap_or("output")
            .to_string();
        let to_node = parse_node_id(conn_obj.get("to_node").context("missing `to_node`")?)?;
        let to_port = conn_obj
            .get("to_port")
            .and_then(|v| v.as_str())
            .context("missing `to_port`")?
            .to_string();

        graph
            .connect(Connection {
                from_node,
                from_port: from_port.clone(),
                to_node,
                to_port: to_port.clone(),
            })
            .with_context(|| {
                format!("connecting {from_node}:{from_port} -> {to_node}:{to_port}")
            })?;

        node::wire_port_ref(&mut graph, to_node, &to_port, from_node, &from_port)?;
    }

    let metadata = obj.get("metadata").map(|v| CompositionMetadata {
        name: v.get("name").and_then(|n| n.as_str()).map(String::from),
    });

    let mut comp = Composition::new(graph, timeline, render_settings);
    comp.metadata = metadata;
    comp.audio = root.get("audio").map(parse_audio_timeline).transpose()?;
    Ok(comp)
}

// ---------------------------------------------------------------------------
// Section parsers
// ---------------------------------------------------------------------------

fn parse_timeline(val: &Value) -> Result<TimelineSettings> {
    let obj = val.as_object().context("`timeline` must be an object")?;
    Ok(TimelineSettings {
        fps: obj.get("fps").and_then(|v| v.as_f64()).unwrap_or(30.0) as f32,
        duration_frames: obj
            .get("duration_frames")
            .and_then(|v| v.as_u64())
            .unwrap_or(1) as u32,
    })
}

fn parse_render_settings(val: &Value) -> Result<RenderSettings> {
    let obj = val
        .as_object()
        .context("`render_settings` must be an object")?;
    Ok(RenderSettings {
        width: obj
            .get("width")
            .and_then(|v| v.as_u64())
            .context("render_settings.width")? as u32,
        height: obj
            .get("height")
            .and_then(|v| v.as_u64())
            .context("render_settings.height")? as u32,
        background_color: parse_color(obj.get("background_color").unwrap_or(&Value::Null))
            .unwrap_or([0, 0, 0, 255]),
    })
}

fn parse_audio_timeline(val: &Value) -> Result<AudioTimeline> {
    let obj = val.as_object().context("`audio` must be an object")?;
    let tracks = obj
        .get("tracks")
        .and_then(Value::as_array)
        .context("audio.tracks must be an array")?
        .iter()
        .map(parse_audio_track)
        .collect::<Result<Vec<_>>>()?;
    let clips = obj
        .get("clips")
        .and_then(Value::as_array)
        .context("audio.clips must be an array")?
        .iter()
        .map(parse_audio_clip)
        .collect::<Result<Vec<_>>>()?;

    Ok(AudioTimeline { tracks, clips })
}

fn parse_audio_track(val: &Value) -> Result<AudioTrack> {
    let obj = val.as_object().context("audio track must be an object")?;
    Ok(AudioTrack {
        id: required_string(obj, "id")?,
        name: obj
            .get("name")
            .and_then(Value::as_str)
            .unwrap_or("Track")
            .to_string(),
        muted: obj.get("muted").and_then(Value::as_bool).unwrap_or(false),
        solo: obj.get("solo").and_then(Value::as_bool).unwrap_or(false),
        volume: obj.get("volume").and_then(Value::as_f64).unwrap_or(1.0) as f32,
    })
}

fn parse_audio_clip(val: &Value) -> Result<AudioClip> {
    let obj = val.as_object().context("audio clip must be an object")?;
    let start_ms = audio_time_ms(obj, "start_ms", "start_frame")?;
    let duration_ms = audio_time_ms(obj, "duration_ms", "duration_frames")?;
    if duration_ms == 0 {
        anyhow::bail!("audio clip duration_ms must be greater than zero");
    }

    Ok(AudioClip {
        id: required_string(obj, "id")?,
        source_id: required_string(obj, "source_id")?,
        track_id: required_string(obj, "track_id")?,
        name: obj
            .get("name")
            .and_then(Value::as_str)
            .unwrap_or("Audio clip")
            .to_string(),
        start_ms,
        duration_ms,
        source_start_ms: obj
            .get("source_start_ms")
            .and_then(Value::as_u64)
            .or_else(|| {
                obj.get("source_start_seconds")
                    .and_then(Value::as_f64)
                    .map(|seconds| (seconds.max(0.0) * 1_000.0).round() as u64)
            })
            .unwrap_or(0),
        volume: obj.get("volume").and_then(Value::as_f64).unwrap_or(1.0) as f32,
    })
}

fn audio_time_ms(obj: &Map<String, Value>, ms_key: &str, frame_key: &str) -> Result<u64> {
    if let Some(ms) = obj.get(ms_key).and_then(Value::as_u64) {
        return Ok(ms);
    }
    if let Some(frames) = obj.get(frame_key).and_then(Value::as_u64) {
        // Frame compatibility for current editor payloads. Canonical output should emit *_ms.
        return Ok(((frames as f64 / 30.0) * 1_000.0).round() as u64);
    }
    anyhow::bail!("audio clip missing `{ms_key}`")
}

fn required_string(obj: &Map<String, Value>, key: &str) -> Result<String> {
    obj.get(key)
        .and_then(Value::as_str)
        .map(ToString::to_string)
        .with_context(|| format!("missing `{key}` string"))
}

fn parse_node_id(val: &Value) -> Result<NodeId> {
    let n = val.as_u64().context("node id must be a u64")?;
    Ok(NodeId::new(n))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parse_minimal_composition() {
        let json = r#"{
            "lumenSchemaVersion": "0.1.0",
            "timeline": { "fps": 30, "duration_frames": 90 },
            "render_settings": { "width": 1920, "height": 1080 },
            "nodes": [
                { "id": 1, "type": "background", "params": { "paint": [255, 0, 0, 255], "width": 1920, "height": 1080 } },
                { "id": 2, "type": "media_output" }
            ],
            "connections": [
                { "from_node": 1, "from_port": "output", "to_node": 2, "to_port": "source" }
            ]
        }"#;

        let comp = parse(json).expect("should parse");
        assert_eq!(comp.timeline.fps, 30.0);
        assert_eq!(comp.timeline.duration_frames, 90);
        assert_eq!(comp.render_settings.width, 1920);
        assert_eq!(comp.render_settings.height, 1080);
        assert_eq!(comp.graph.nodes.len(), 2);
        assert_eq!(comp.graph.connections.len(), 1);
    }

    #[test]
    fn parse_composition_with_audio_timeline() {
        let json = r#"{
            "timeline": { "fps": 30, "duration_frames": 90 },
            "render_settings": { "width": 1920, "height": 1080 },
            "audio": {
                "tracks": [
                    { "id": "track-1", "name": "Voice", "muted": false, "solo": true, "volume": 0.5 }
                ],
                "clips": [
                    {
                        "id": "clip-1",
                        "source_id": "voice",
                        "track_id": "track-1",
                        "name": "voice.wav",
                        "start_ms": 100,
                        "duration_ms": 900,
                        "source_start_ms": 50,
                        "volume": 0.75
                    }
                ]
            },
            "nodes": [
                { "id": 1, "type": "background", "params": { "paint": [255, 0, 0, 255], "width": 1920, "height": 1080 } },
                { "id": 2, "type": "media_output" }
            ],
            "connections": [
                { "from_node": 1, "from_port": "output", "to_node": 2, "to_port": "source" }
            ]
        }"#;

        let comp = parse(json).expect("should parse");
        let audio = comp.audio.expect("audio timeline");
        assert_eq!(audio.tracks[0].id, "track-1");
        assert!(audio.tracks[0].solo);
        assert_eq!(audio.clips[0].source_id, "voice");
        assert_eq!(audio.clips[0].start_ms, 100);
        assert_eq!(audio.clips[0].source_start_ms, 50);
    }

    #[test]
    fn parse_with_expressions() {
        let json = r##"{
            "timeline": { "fps": 24, "duration_frames": 48 },
            "render_settings": { "width": 800, "height": 600 },
            "nodes": [
                { "id": 1, "type": "background", "params": { "paint": "#FF0000", "width": 800, "height": 600 } },
                { "id": 2, "type": "exposure", "params": {
                    "exposure": "=frame * 0.1",
                    "contrast": 1.0,
                    "offset": 0.0
                }},
                { "id": 3, "type": "media_output" }
            ],
            "connections": [
                { "from_node": 1, "from_port": "output", "to_node": 2, "to_port": "source" },
                { "from_node": 2, "from_port": "output", "to_node": 3, "to_port": "source" }
            ]
        }"##;

        let comp = parse(json).expect("should parse");
        assert_eq!(comp.graph.nodes.len(), 3);
    }

    #[test]
    fn parse_switch_node() {
        let json = r#"{
            "timeline": { "fps": 30, "duration_frames": 60 },
            "render_settings": { "width": 100, "height": 100 },
            "nodes": [
                { "id": 1, "type": "background", "params": { "paint": [255, 0, 0], "width": 100, "height": 100 } },
                { "id": 2, "type": "background", "params": { "paint": [0, 255, 0], "width": 100, "height": 100 } },
                { "id": 3, "type": "switch", "params": { "selected_layer": "=if(frame < 30, 0, 1)" } },
                { "id": 4, "type": "media_output" }
            ],
            "connections": [
                { "from_node": 1, "from_port": "output", "to_node": 3, "to_port": "layers" },
                { "from_node": 2, "from_port": "output", "to_node": 3, "to_port": "layers" },
                { "from_node": 3, "from_port": "output", "to_node": 4, "to_port": "source" }
            ]
        }"#;

        let comp = parse(json).expect("should parse");
        assert_eq!(comp.graph.nodes.len(), 4);
    }

    #[test]
    fn parse_enum_property_names() {
        let json = r#"{
            "timeline": { "fps": 30, "duration_frames": 60 },
            "render_settings": { "width": 100, "height": 100 },
            "nodes": [
                { "id": 1, "type": "background", "params": { "paint": [255, 0, 0], "width": 100, "height": 100 } },
                { "id": 2, "type": "background", "params": { "paint": [0, 255, 0], "width": 100, "height": 100 } },
                { "id": 3, "type": "merge", "params": { "blend_mode": "multiply", "opacity": 0.5 } },
                { "id": 4, "type": "media_output" }
            ],
            "connections": [
                { "from_node": 1, "from_port": "output", "to_node": 3, "to_port": "base" },
                { "from_node": 2, "from_port": "output", "to_node": 3, "to_port": "overlay" },
                { "from_node": 3, "from_port": "output", "to_node": 4, "to_port": "source" }
            ]
        }"#;

        let comp = parse(json).expect("should parse");
        let merge = comp.graph.nodes.get(&NodeId::new(3)).expect("merge");
        assert!(matches!(
            merge,
            crate::node::NodeKind::Merge(node)
                if matches!(node.params.blend_mode, crate::node::compositing::BlendModeDelegate::Multiply)
        ));
    }

    #[test]
    fn parse_rejects_invalid_enum_property_name() {
        let json = r#"{
            "timeline": { "fps": 30, "duration_frames": 60 },
            "render_settings": { "width": 100, "height": 100 },
            "nodes": [
                { "id": 1, "type": "merge", "params": { "blend_mode": "not_real" } }
            ],
            "connections": []
        }"#;

        let err = parse(json).unwrap_err().to_string();
        assert!(err.contains("unknown enum value `not_real`"));
    }

    #[test]
    fn unknown_node_type_errors() {
        let json = r#"{
            "timeline": { "fps": 30, "duration_frames": 1 },
            "render_settings": { "width": 100, "height": 100 },
            "nodes": [{ "id": 1, "type": "nonexistent" }],
            "connections": []
        }"#;

        assert!(parse(json).is_err());
    }

    #[test]
    fn parse_rejects_unknown_schema_version() {
        let json = r#"{
            "lumenSchemaVersion": "99.0.0",
            "timeline": { "fps": 30, "duration_frames": 1 },
            "render_settings": { "width": 100, "height": 100 },
            "nodes": [],
            "connections": []
        }"#;

        let err = parse(json).unwrap_err().to_string();
        assert!(err.contains("unsupported Lumen schema version `99.0.0`"));
    }
}