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
447
448
449
450
451
452
453
454
455
use crate::engine::audio::generator::FilterDef;
/// Audio events system - stores note/chord events to be rendered
use crate::language::syntax::ast::Value;
use std::collections::HashMap;

#[derive(Debug, Clone)]
pub enum AudioEvent {
    Note {
        node_id: Option<String>,
        midi: u8,
        start_time: f32,
        duration: f32,
        velocity: f32,
        synth_id: String,
        synth_def: SynthDefinition, // Snapshot of synth at event creation time
        // Audio options
        pan: f32,             // -1.0 to 1.0
        detune: f32,          // cents
        gain: f32,            // multiplier
        attack: Option<f32>,  // ms override
        release: Option<f32>, // ms override
        // Effects
        delay_time: Option<f32>,     // ms
        delay_feedback: Option<f32>, // 0.0-1.0
        delay_mix: Option<f32>,      // 0.0-1.0
        reverb_amount: Option<f32>,  // 0.0-1.0
        drive_amount: Option<f32>,   // 0.0-1.0
        drive_color: Option<f32>,    // 0.0-1.0
        // Full effects map (optional) - may contain chained effects for this event
        effects: Option<crate::language::syntax::ast::Value>,
        // Per-note automation flag
        use_per_note_automation: bool, // Whether to apply per-note automation at render time
    },
    Chord {
        node_id: Option<String>,
        midis: Vec<u8>,
        start_time: f32,
        duration: f32,
        velocity: f32,
        synth_id: String,
        synth_def: SynthDefinition, // Snapshot of synth at event creation time
        // Audio options
        pan: f32,             // -1.0 to 1.0
        detune: f32,          // cents
        spread: f32,          // 0.0 to 1.0
        gain: f32,            // multiplier
        attack: Option<f32>,  // ms override
        release: Option<f32>, // ms override
        // Effects
        delay_time: Option<f32>,     // ms
        delay_feedback: Option<f32>, // 0.0-1.0
        delay_mix: Option<f32>,      // 0.0-1.0
        reverb_amount: Option<f32>,  // 0.0-1.0
        drive_amount: Option<f32>,   // 0.0-1.0
        drive_color: Option<f32>,    // 0.0-1.0
        // Full effects map (optional)
        effects: Option<crate::language::syntax::ast::Value>,
        // Per-note automation flag
        use_per_note_automation: bool, // Whether to apply per-note automation at render time
    },
    Sample {
        node_id: Option<String>,
        uri: String,
        start_time: f32,
        velocity: f32,
        // Effects to apply to this sample (trigger effects)
        effects: Option<crate::language::syntax::ast::Value>,
        // Source identifier (pattern name) for routing purposes
        source: Option<String>,
    },
    Stop {
        target: Option<String>, // None = stop all, Some = stop specific entity
        time: f32,              // Time when to stop
    },
}

/// Audio events collector
#[derive(Debug, Default)]
pub struct AudioEventList {
    pub events: Vec<AudioEvent>,
    /// Print/log messages recorded during interpretation. These are not audio events
    /// and should not affect loop termination logic.
    pub logs: Vec<(f32, String)>,
    pub synths: HashMap<String, SynthDefinition>,
}

#[derive(Debug, Clone)]
pub struct SynthDefinition {
    pub waveform: String,
    pub attack: f32,
    pub decay: f32,
    pub sustain: f32,
    pub release: f32,
    pub synth_type: Option<String>,
    pub filters: Vec<FilterDef>,
    pub options: HashMap<String, f32>, // Configurable synth type options
    pub lfo: Option<crate::engine::audio::lfo::LfoParams>, // Low-Frequency Oscillator
    pub bpm: f32, // Tempo snapshot used by beat-synced modulation during rendering
    // Plugin support
    pub plugin_author: Option<String>,
    pub plugin_name: Option<String>,
    pub plugin_export: Option<String>,
}

impl Default for SynthDefinition {
    fn default() -> Self {
        Self {
            waveform: "sine".to_string(),
            attack: 0.01,
            decay: 0.1,
            sustain: 0.7,
            release: 0.2,
            synth_type: None,
            filters: Vec::new(),
            options: HashMap::new(),
            lfo: None,
            bpm: 120.0,
            plugin_author: None,
            plugin_name: None,
            plugin_export: None,
        }
    }
}

impl AudioEventList {
    pub fn new() -> Self {
        Self {
            events: Vec::new(),
            logs: Vec::new(),
            synths: HashMap::new(),
        }
    }

    pub fn add_synth(&mut self, name: String, definition: SynthDefinition) {
        self.synths.insert(name, definition);
    }

    pub fn add_note_event(
        &mut self,
        synth_id: &str,
        midi: u8,
        start_time: f32,
        duration: f32,
        velocity: f32,
        pan: f32,
        detune: f32,
        gain: f32,
        attack: Option<f32>,
        release: Option<f32>,
        delay_time: Option<f32>,
        delay_feedback: Option<f32>,
        delay_mix: Option<f32>,
        reverb_amount: Option<f32>,
        drive_amount: Option<f32>,
        drive_color: Option<f32>,
    ) {
        // Capture synth definition snapshot at event creation time
        let synth_def = self.get_synth(synth_id).cloned().unwrap_or_else(|| {
            println!("⚠️  Warning: Synth '{}' not found when creating note event. Available synths: {:?}", 
                     synth_id, self.synths.keys().collect::<Vec<_>>());
            SynthDefinition::default()
        });

        self.events.push(AudioEvent::Note {
            node_id: Some("master".to_string()),
            midi,
            start_time,
            duration,
            velocity,
            synth_id: synth_id.to_string(),
            synth_def,
            pan,
            detune,
            gain,
            attack,
            release,
            delay_time,
            delay_feedback,
            delay_mix,
            reverb_amount,
            drive_amount,
            drive_color,
            effects: None,
            use_per_note_automation: false,
        });
    }

    pub fn add_chord_event(
        &mut self,
        synth_id: &str,
        midis: Vec<u8>,
        start_time: f32,
        duration: f32,
        velocity: f32,
        pan: f32,
        detune: f32,
        spread: f32,
        gain: f32,
        attack: Option<f32>,
        release: Option<f32>,
        delay_time: Option<f32>,
        delay_feedback: Option<f32>,
        delay_mix: Option<f32>,
        reverb_amount: Option<f32>,
        drive_amount: Option<f32>,
        drive_color: Option<f32>,
    ) {
        // Capture synth definition snapshot at event creation time
        let synth_def = self.get_synth(synth_id).cloned().unwrap_or_default();

        self.events.push(AudioEvent::Chord {
            node_id: Some("master".to_string()),
            midis,
            start_time,
            duration,
            velocity,
            synth_id: synth_id.to_string(),
            synth_def,
            pan,
            detune,
            spread,
            gain,
            attack,
            release,
            delay_time,
            delay_feedback,
            delay_mix,
            reverb_amount,
            drive_amount,
            drive_color,
            effects: None,
            use_per_note_automation: false,
        });
    }

    pub fn add_sample_event(&mut self, uri: &str, start_time: f32, velocity: f32) {
        self.events.push(AudioEvent::Sample {
            node_id: Some("master".to_string()),
            uri: uri.to_string(),
            start_time,
            velocity,
            effects: None,
            source: None,
        });
    }

    /// Add a sample event with an attached effects map (owned)
    pub fn add_sample_event_with_effects(
        &mut self,
        uri: &str,
        start_time: f32,
        velocity: f32,
        effects: Option<Value>,
    ) {
        self.events.push(AudioEvent::Sample {
            node_id: Some("master".to_string()),
            uri: uri.to_string(),
            start_time,
            velocity,
            effects,
            source: None,
        });
    }

    /// Add a log message (created by `print` statements). Time is in seconds from start.
    /// Logs are stored separately from audio events so they don't affect rendering/loop logic.
    pub fn add_log_event(&mut self, message: String, time: f32) {
        self.logs.push((time, message));
    }

    pub fn get_synth(&self, name: &str) -> Option<&SynthDefinition> {
        self.synths.get(name)
    }

    pub fn total_duration(&self) -> f32 {
        // Find the earliest stop time (if any)
        let stop_time = self.events.iter().find_map(|event| match event {
            AudioEvent::Stop { target: None, time } => Some(*time), // Only consider "stop all"
            _ => None,
        });

        // Calculate total duration from all events
        let max_duration = self
            .events
            .iter()
            .map(|event| match event {
                AudioEvent::Note {
                    start_time,
                    duration,
                    ..
                } => start_time + duration,
                AudioEvent::Chord {
                    start_time,
                    duration,
                    ..
                } => start_time + duration,
                AudioEvent::Sample {
                    start_time, uri, ..
                } => {
                    // Get actual sample duration from registry
                    #[cfg(target_arch = "wasm32")]
                    {
                        use crate::web::registry::samples::get_sample;
                        if let Some(pcm) = get_sample(uri) {
                            // Assume 44.1kHz sample rate
                            let duration = pcm.len() as f32 / 44100.0;
                            start_time + duration
                        } else {
                            // Fallback: estimate 2 seconds
                            start_time + 2.0
                        }
                    }
                    #[cfg(not(target_arch = "wasm32"))]
                    {
                        // Fallback for native: estimate 2 seconds
                        let _ = uri; // Silence unused warning on non-WASM targets
                        start_time + 2.0
                    }
                }
                AudioEvent::Stop { target: None, time } => *time, // Include stop all times
                AudioEvent::Stop {
                    target: Some(_), ..
                } => 0.0, // Ignore stop specific
            })
            .fold(0.0, f32::max);

        // If there's a stop all event, limit duration to it
        if let Some(stop_t) = stop_time {
            max_duration.min(stop_t)
        } else {
            max_duration
        }
    }

    /// Merge another AudioEventList into this one
    /// This is used for parallel spawn execution
    pub fn merge(&mut self, other: AudioEventList) {
        // Merge synth definitions FIRST (prefer existing definitions on conflict)
        for (name, def) in other.synths {
            if !self.synths.contains_key(&name) {
                self.synths.insert(name, def);
            }
        }

        // Merge events and update their synth_def snapshots if needed
        for mut event in other.events {
            // Update synth_def snapshot for Note and Chord events
            match &mut event {
                AudioEvent::Note {
                    synth_id,
                    synth_def,
                    ..
                } => {
                    // If this event's synth now exists in merged synths, update the snapshot
                    if let Some(updated_def) = self.synths.get(synth_id) {
                        *synth_def = updated_def.clone();
                    }
                }
                AudioEvent::Chord {
                    synth_id,
                    synth_def,
                    ..
                } => {
                    // If this event's synth now exists in merged synths, update the snapshot
                    if let Some(updated_def) = self.synths.get(synth_id) {
                        *synth_def = updated_def.clone();
                    }
                }
                _ => {}
            }
            self.events.push(event);
        }

        // Merge logs (print messages) as well
        for log in other.logs {
            // Avoid inserting duplicate or near-duplicate log entries (same message
            // and timestamps within a small epsilon). Multiple workers or interpreter
            // snapshots may produce the same scheduled print with slightly different
            // float timestamps; deduplicate those here.
            let mut duplicated = false;
            for existing in &self.logs {
                let time_diff = (existing.0 - log.0).abs();
                if existing.1 == log.1 && time_diff <= 0.001 {
                    duplicated = true;
                    break;
                }
            }
            if !duplicated {
                self.logs.push(log);
            }
        }

        // Keep logs time-ordered for predictable playback
        self.logs
            .sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal));
    }
}

/// Helper to extract values from Value::Map
pub fn extract_number(map: &HashMap<String, Value>, key: &str, default: f32) -> f32 {
    map.get(key)
        .and_then(|v| {
            if let Value::Number(n) = v {
                Some(*n)
            } else {
                None
            }
        })
        .unwrap_or(default)
}

pub fn extract_string(map: &HashMap<String, Value>, key: &str, default: &str) -> String {
    map.get(key)
        .and_then(|v| {
            if let Value::String(s) = v {
                Some(s.clone())
            } else {
                None
            }
        })
        .unwrap_or_else(|| default.to_string())
}

pub fn extract_filters(filters_arr: &[Value]) -> Vec<FilterDef> {
    filters_arr
        .iter()
        .filter_map(|v| {
            if let Value::Map(filter_map) = v {
                let filter_type = extract_string(filter_map, "type", "lowpass");
                let cutoff = filter_map
                    .get("cutoff")
                    .and_then(|v| match v {
                        Value::Number(n) => Some(*n),
                        _ => None,
                    })
                    .unwrap_or(1000.0);
                let resonance = filter_map
                    .get("resonance")
                    .and_then(|v| match v {
                        Value::Number(n) => Some(*n),
                        _ => None,
                    })
                    .unwrap_or(1.0);

                Some(FilterDef {
                    filter_type,
                    cutoff,
                    resonance,
                })
            } else {
                None
            }
        })
        .collect()
}