devalang 0.2.0

Write music with code. Devalang is a domain-specific language (DSL) for sound designers and music hackers. Compose, automate, and control sound — in plain text.
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
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
use crate::language::syntax::ast::Value;
/// Automation system - parameter automation over time
/// Supports linear, exponential, and custom curves
use std::collections::HashMap;

/// Automation curve type (legacy simple curves)
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AutomationCurve {
    Linear,
    Exponential,
    Logarithmic,
    Smooth, // Smooth interpolation (ease-in-out)
}

impl AutomationCurve {
    pub fn from_str(s: &str) -> Self {
        match s.to_lowercase().as_str() {
            "linear" | "lin" => AutomationCurve::Linear,
            "exponential" | "exp" => AutomationCurve::Exponential,
            "logarithmic" | "log" => AutomationCurve::Logarithmic,
            "smooth" | "ease" => AutomationCurve::Smooth,
            _ => AutomationCurve::Linear,
        }
    }
}

/// Automation parameter
#[derive(Debug, Clone)]
pub struct AutomationParam {
    pub param_name: String,
    pub from_value: f32,
    pub to_value: f32,
    pub start_time: f32, // seconds
    pub duration: f32,   // seconds
    pub curve: AutomationCurve,
}

/// Lightweight template for per-note automation (percent-based points)
#[derive(Debug, Clone)]
pub struct AutomationParamTemplate {
    pub param_name: String,
    /// Points as (progress_fraction 0.0-1.0, value)
    pub points: Vec<(f32, f32)>,
    pub curve: AutomationCurve,
    /// Advanced curve (if specified)
    pub advanced_curve: Option<crate::engine::curves::CurveType>,
}

/// Automation envelope - collection of automation parameters
#[derive(Debug, Clone)]
pub struct AutomationEnvelope {
    pub target: String, // Target entity (synth name, "global", etc.)
    pub params: Vec<AutomationParam>,
}

impl AutomationEnvelope {
    pub fn new(target: String) -> Self {
        Self {
            target,
            params: Vec::new(),
        }
    }

    /// Add automation parameter
    pub fn add_param(&mut self, param: AutomationParam) {
        self.params.push(param);
    }

    /// Get automated value for a parameter at a specific time
    pub fn get_value(&self, param_name: &str, time_seconds: f32) -> Option<f32> {
        // Find all automation params for this parameter name
        let matching: Vec<&AutomationParam> = self
            .params
            .iter()
            .filter(|p| p.param_name == param_name)
            .collect();

        if matching.is_empty() {
            return None;
        }

        // Find the active automation (most recent one that affects current time)
        for param in matching.iter().rev() {
            let end_time = param.start_time + param.duration;

            if param.duration <= f32::EPSILON {
                return Some(if time_seconds >= param.start_time {
                    param.to_value
                } else {
                    param.from_value
                });
            }

            if time_seconds >= param.start_time && time_seconds <= end_time {
                // Currently in automation range
                let progress = (time_seconds - param.start_time) / param.duration;
                let value =
                    interpolate_value(param.from_value, param.to_value, progress, param.curve);
                return Some(value);
            } else if time_seconds > end_time {
                // Past automation - return end value
                return Some(param.to_value);
            }
        }

        // Before any automation - return first start value
        Some(matching[0].from_value)
    }
}

/// Interpolate between two values based on progress and curve type
fn interpolate_value(from: f32, to: f32, progress: f32, curve: AutomationCurve) -> f32 {
    let t = progress.clamp(0.0, 1.0);

    let interpolated = match curve {
        AutomationCurve::Linear => t,
        AutomationCurve::Exponential => {
            // Exponential curve (ease-out)
            if (to - from).abs() < 0.0001 { t } else { t * t }
        }
        AutomationCurve::Logarithmic => {
            // Logarithmic curve (ease-in)
            1.0 - (1.0 - t) * (1.0 - t)
        }
        AutomationCurve::Smooth => {
            // Smooth ease-in-out (cubic)
            if t < 0.5 {
                2.0 * t * t
            } else {
                1.0 - (-2.0 * t + 2.0).powi(2) / 2.0
            }
        }
    };

    from + (to - from) * interpolated
}

/// Parse automation from Value::Map
pub fn parse_automation_from_value(value: &Value) -> Option<AutomationEnvelope> {
    if let Value::Map(map) = value {
        let target = map.get("target").and_then(|v| match v {
            Value::String(s) | Value::Identifier(s) => Some(s.clone()),
            _ => None,
        })?;

        let mut envelope = AutomationEnvelope::new(target);

        // Parse params array
        if let Some(Value::Array(params_array)) = map.get("params") {
            for param_value in params_array {
                if let Some(param) = parse_automation_param(param_value) {
                    envelope.add_param(param);
                }
            }
        }

        Some(envelope)
    } else {
        None
    }
}

/// Parse per-param templates from a raw automate body string.
/// Expects blocks like: param <name> { 0% = 0.0 100% = 1.0 }
pub fn parse_param_templates_from_raw(raw: &str) -> Vec<AutomationParamTemplate> {
    use regex::Regex;
    let mut templates = Vec::new();

    // Find param blocks: param <name> [curve <curveName>] { ... }
    let Ok(re_block) =
        Regex::new(r"param\s+([A-Za-z_][A-Za-z0-9_]*)\s*(?:curve\s+([^\s{]+)\s*)?\{([^}]*)\}")
    else {
        return templates;
    };
    let Ok(re_point) = Regex::new(r"([0-9]+(?:\.[0-9]+)?)%?\s*=\s*([\-0-9\.eE]+)") else {
        return templates;
    };

    for cap in re_block.captures_iter(raw) {
        let Some(name_match) = cap.get(1) else {
            continue;
        };
        let name = name_match.as_str().to_string();
        let curve_str = cap.get(2).map(|m| m.as_str());
        let Some(body_match) = cap.get(3) else {
            continue;
        };
        let body = body_match.as_str();

        let mut points: Vec<(f32, f32)> = Vec::new();
        for pcap in re_point.captures_iter(body) {
            if let (Some(p_str), Some(v_str)) = (pcap.get(1), pcap.get(2)) {
                if let (Ok(pv), Ok(vv)) =
                    (p_str.as_str().parse::<f32>(), v_str.as_str().parse::<f32>())
                {
                    let frac = (pv / 100.0).clamp(0.0, 1.0);
                    points.push((frac, vv));
                }
            }
        }

        // Sort by progress fraction
        points.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal));

        if !points.is_empty() {
            // Parse advanced curve if specified
            let advanced_curve = curve_str.and_then(|s| crate::engine::curves::parse_curve(s));

            templates.push(AutomationParamTemplate {
                param_name: name,
                points,
                curve: AutomationCurve::Linear,
                advanced_curve,
            });
        }
    }

    templates
}

/// Evaluate a template at a given progress fraction (0.0..1.0)
pub fn evaluate_template_at(tpl: &AutomationParamTemplate, progress: f32) -> f32 {
    let p = progress.clamp(0.0, 1.0);
    if tpl.points.is_empty() {
        return 0.0;
    }
    // Before first point
    if p <= tpl.points[0].0 {
        return tpl.points[0].1;
    }
    // After last point
    if let Some(&(last_progress, last_value)) = tpl.points.last() {
        if p >= last_progress {
            return last_value;
        }
    }

    // Find segment
    for w in tpl.points.windows(2) {
        let (p0, v0) = w[0];
        let (p1, v1) = w[1];
        if p >= p0 && p <= p1 {
            let local = if (p1 - p0).abs() < f32::EPSILON {
                0.0
            } else {
                (p - p0) / (p1 - p0)
            };

            // Apply advanced curve if specified
            let eased_local = if let Some(curve) = &tpl.advanced_curve {
                crate::engine::curves::evaluate_curve(*curve, local)
            } else {
                local // Standard linear interpolation
            };

            return v0 + (v1 - v0) * eased_local;
        }
    }

    // Fallback
    tpl.points.last().map(|(_, value)| *value).unwrap_or(0.0)
}

/// Parse single automation parameter from Value
fn parse_automation_param(value: &Value) -> Option<AutomationParam> {
    if let Value::Map(map) = value {
        let param_name = map.get("name").and_then(|v| match v {
            Value::String(s) | Value::Identifier(s) => Some(s.clone()),
            _ => None,
        })?;

        let from_value = map.get("from").and_then(|v| match v {
            Value::Number(n) => Some(*n),
            _ => None,
        })?;

        let to_value = map.get("to").and_then(|v| match v {
            Value::Number(n) => Some(*n),
            _ => None,
        })?;

        let start_time = map
            .get("start")
            .and_then(|v| match v {
                Value::Number(n) => Some(*n),
                _ => None,
            })
            .unwrap_or(0.0);

        let duration = map.get("duration").and_then(|v| match v {
            Value::Number(n) => Some(*n),
            _ => None,
        })?;

        let curve = map
            .get("curve")
            .and_then(|v| match v {
                Value::String(s) | Value::Identifier(s) => Some(AutomationCurve::from_str(s)),
                _ => None,
            })
            .unwrap_or(AutomationCurve::Linear);

        Some(AutomationParam {
            param_name,
            from_value,
            to_value,
            start_time,
            duration,
            curve,
        })
    } else {
        None
    }
}

/// Automation registry - stores all active automations
#[derive(Debug, Clone, Default)]
pub struct AutomationRegistry {
    envelopes: HashMap<String, AutomationEnvelope>,
}

impl AutomationRegistry {
    pub fn new() -> Self {
        Self {
            envelopes: HashMap::new(),
        }
    }

    /// Register an automation envelope
    pub fn register(&mut self, envelope: AutomationEnvelope) {
        self.envelopes.insert(envelope.target.clone(), envelope);
    }

    /// Get automated value for a target and parameter at a specific time
    pub fn get_value(&self, target: &str, param_name: &str, time_seconds: f32) -> Option<f32> {
        self.envelopes
            .get(target)
            .and_then(|env| env.get_value(param_name, time_seconds))
    }

    /// Check if a target has any active automations
    pub fn has_automation(&self, target: &str) -> bool {
        self.envelopes.contains_key(target)
    }

    /// Get all automation targets
    pub fn targets(&self) -> Vec<String> {
        self.envelopes.keys().cloned().collect()
    }
}

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

    #[test]
    fn test_linear_interpolation() {
        let param = AutomationParam {
            param_name: "volume".to_string(),
            from_value: 0.0,
            to_value: 1.0,
            start_time: 0.0,
            duration: 2.0,
            curve: AutomationCurve::Linear,
        };

        let mut envelope = AutomationEnvelope::new("synth1".to_string());
        envelope.add_param(param);

        // At t=0, should be 0.0
        assert_eq!(envelope.get_value("volume", 0.0), Some(0.0));

        // At t=1 (50%), should be 0.5
        assert!((envelope.get_value("volume", 1.0).unwrap() - 0.5).abs() < 0.001);

        // At t=2, should be 1.0
        assert_eq!(envelope.get_value("volume", 2.0), Some(1.0));

        // At t=3 (past), should stay at 1.0
        assert_eq!(envelope.get_value("volume", 3.0), Some(1.0));
    }

    #[test]
    fn test_smooth_curve() {
        let value_start = interpolate_value(0.0, 1.0, 0.0, AutomationCurve::Smooth);
        let value_mid = interpolate_value(0.0, 1.0, 0.5, AutomationCurve::Smooth);
        let value_end = interpolate_value(0.0, 1.0, 1.0, AutomationCurve::Smooth);

        assert_eq!(value_start, 0.0);
        assert_eq!(value_end, 1.0);
        assert!(value_mid > 0.4 && value_mid < 0.6); // Should be around 0.5
    }

    #[test]
    fn test_automation_registry() {
        let mut registry = AutomationRegistry::new();

        let mut envelope = AutomationEnvelope::new("synth1".to_string());
        envelope.add_param(AutomationParam {
            param_name: "volume".to_string(),
            from_value: 0.0,
            to_value: 1.0,
            start_time: 0.0,
            duration: 2.0,
            curve: AutomationCurve::Linear,
        });

        registry.register(envelope);

        assert!(registry.has_automation("synth1"));
        assert!(!registry.has_automation("synth2"));

        let value = registry.get_value("synth1", "volume", 1.0);
        assert!(value.is_some());
        assert!((value.unwrap() - 0.5).abs() < 0.001);
    }

    #[test]
    fn test_zero_duration_param_switches_at_start_time() {
        let mut envelope = AutomationEnvelope::new("synth1".to_string());
        envelope.add_param(AutomationParam {
            param_name: "volume".to_string(),
            from_value: 0.25,
            to_value: 0.75,
            start_time: 2.0,
            duration: 0.0,
            curve: AutomationCurve::Linear,
        });

        assert_eq!(envelope.get_value("volume", 1.0), Some(0.25));
        assert_eq!(envelope.get_value("volume", 2.0), Some(0.75));
        assert_eq!(envelope.get_value("volume", 3.0), Some(0.75));
    }

    #[test]
    fn test_empty_template_evaluates_to_zero() {
        let template = AutomationParamTemplate {
            param_name: "cutoff".to_string(),
            points: Vec::new(),
            curve: AutomationCurve::Linear,
            advanced_curve: None,
        };

        assert_eq!(evaluate_template_at(&template, 0.5), 0.0);
    }
}