@devaloop/devalang 0.0.1-beta.1 → 0.0.1-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (207) hide show
  1. package/.devalang +9 -10
  2. package/Cargo.toml +84 -80
  3. package/README.md +10 -7
  4. package/docs/CHANGELOG.md +83 -0
  5. package/docs/ROADMAP.md +6 -2
  6. package/docs/TODO.md +3 -14
  7. package/examples/bus.deva +10 -0
  8. package/examples/chain.deva +19 -0
  9. package/examples/effect.deva +2 -0
  10. package/examples/filter.deva +11 -0
  11. package/examples/lfo.deva +9 -0
  12. package/examples/plugin.deva +10 -10
  13. package/examples/routing.deva +23 -0
  14. package/examples/synth.deva +11 -1
  15. package/examples/synth_types.deva +17 -0
  16. package/out-tsc/bin/project-version.json +6 -0
  17. package/out-tsc/core/functions/index.d.ts +5 -0
  18. package/out-tsc/core/functions/index.js +11 -0
  19. package/out-tsc/pkg/devalang_core.d.ts +2 -0
  20. package/out-tsc/pkg/devalang_core.js +17 -2
  21. package/out-tsc/pkg/devalang_core_bg.wasm.d.ts +1 -0
  22. package/out-tsc/scripts/version/copy-to-binary.d.ts +1 -0
  23. package/out-tsc/scripts/version/copy-to-binary.js +79 -0
  24. package/package.json +23 -10
  25. package/project-version.json +3 -3
  26. package/rust/bindings/Cargo.toml +9 -0
  27. package/rust/bindings/src/lib.rs +86 -0
  28. package/rust/cli/addon/commands.rs +35 -0
  29. package/rust/cli/addon/download.rs +234 -0
  30. package/rust/cli/addon/install.rs +33 -0
  31. package/rust/cli/addon/list.rs +224 -0
  32. package/rust/cli/addon/metadata.rs +124 -0
  33. package/rust/cli/addon/mod.rs +8 -0
  34. package/rust/cli/addon/remove.rs +271 -0
  35. package/rust/cli/addon/update.rs +305 -0
  36. package/rust/cli/{install/addon.rs → addon/utils.rs} +34 -43
  37. package/rust/cli/build/commands.rs +153 -103
  38. package/rust/cli/build/mod.rs +2 -2
  39. package/rust/cli/build/process.rs +165 -146
  40. package/rust/cli/check/mod.rs +208 -208
  41. package/rust/cli/discover/commands.rs +53 -31
  42. package/rust/cli/discover/config.rs +2 -4
  43. package/rust/cli/discover/install.rs +139 -28
  44. package/rust/cli/discover/metadata.rs +3 -3
  45. package/rust/cli/login/commands.rs +124 -124
  46. package/rust/cli/me/commands.rs +52 -0
  47. package/rust/cli/me/mod.rs +1 -0
  48. package/rust/cli/mod.rs +2 -2
  49. package/rust/cli/parser.rs +76 -70
  50. package/rust/cli/play/commands.rs +375 -324
  51. package/rust/cli/play/mod.rs +5 -5
  52. package/rust/cli/play/process.rs +159 -150
  53. package/rust/cli/play/realtime.rs +91 -91
  54. package/rust/cli/telemetry/commands.rs +22 -22
  55. package/rust/cli/telemetry/event_creator.rs +80 -80
  56. package/rust/cli/telemetry/mod.rs +3 -3
  57. package/rust/cli/telemetry/send.rs +51 -51
  58. package/rust/cli/template/commands.rs +69 -69
  59. package/rust/config/driver.rs +112 -103
  60. package/rust/config/mod.rs +3 -3
  61. package/rust/config/ops.rs +26 -26
  62. package/rust/config/settings.rs +101 -101
  63. package/rust/core/audio/engine/driver.rs +237 -0
  64. package/rust/core/audio/engine/export.rs +169 -0
  65. package/rust/core/audio/engine/helpers.rs +178 -170
  66. package/rust/core/audio/engine/mod.rs +56 -7
  67. package/rust/core/audio/engine/notes/dsp.rs +88 -0
  68. package/rust/core/audio/engine/notes/mod.rs +53 -0
  69. package/rust/core/audio/engine/notes/params.rs +294 -0
  70. package/rust/core/audio/engine/sample/insert.rs +300 -0
  71. package/rust/core/audio/engine/sample/mod.rs +40 -0
  72. package/rust/core/audio/engine/sample/padding.rs +170 -0
  73. package/rust/core/audio/evaluator/condition.rs +61 -0
  74. package/rust/core/audio/evaluator/mod.rs +9 -0
  75. package/rust/core/audio/{evaluator.rs → evaluator/numeric.rs} +152 -310
  76. package/rust/core/audio/evaluator/rhs.rs +16 -0
  77. package/rust/core/audio/evaluator/string_expr.rs +94 -0
  78. package/rust/core/audio/interpreter/driver.rs +574 -542
  79. package/rust/core/audio/interpreter/mod.rs +2 -14
  80. package/rust/core/audio/interpreter/statements/arrow_call/interprete.rs +179 -0
  81. package/rust/core/audio/interpreter/statements/arrow_call/methods/chord.rs +398 -0
  82. package/rust/core/audio/interpreter/statements/arrow_call/methods/effects.rs +323 -0
  83. package/rust/core/audio/interpreter/statements/arrow_call/methods/mod.rs +3 -0
  84. package/rust/core/audio/interpreter/statements/arrow_call/methods/note.rs +371 -0
  85. package/rust/core/audio/interpreter/statements/arrow_call/mod.rs +3 -0
  86. package/rust/core/audio/interpreter/statements/arrow_call/types/arp.rs +192 -0
  87. package/rust/core/audio/interpreter/statements/arrow_call/types/mod.rs +24 -0
  88. package/rust/core/audio/interpreter/statements/arrow_call/types/pad.rs +116 -0
  89. package/rust/core/audio/interpreter/statements/arrow_call/types/pluck.rs +97 -0
  90. package/rust/core/audio/interpreter/statements/arrow_call/types/sub.rs +100 -0
  91. package/rust/core/audio/interpreter/{automate.rs → statements/automate.rs} +2 -4
  92. package/rust/core/audio/interpreter/{call.rs → statements/call.rs} +36 -5
  93. package/rust/core/audio/interpreter/{condition.rs → statements/condition.rs} +72 -71
  94. package/rust/core/audio/interpreter/{function.rs → statements/function.rs} +24 -26
  95. package/rust/core/audio/interpreter/{let_.rs → statements/let_.rs} +36 -38
  96. package/rust/core/audio/interpreter/{load.rs → statements/load.rs} +17 -19
  97. package/rust/core/audio/interpreter/{loop_.rs → statements/loop_.rs} +115 -114
  98. package/rust/core/audio/interpreter/statements/mod.rs +12 -0
  99. package/rust/core/audio/interpreter/{sleep.rs → statements/sleep.rs} +28 -28
  100. package/rust/core/audio/interpreter/{spawn.rs → statements/spawn.rs} +54 -4
  101. package/rust/core/audio/interpreter/{tempo.rs → statements/tempo.rs} +40 -40
  102. package/rust/core/audio/interpreter/{trigger.rs → statements/trigger.rs} +242 -239
  103. package/rust/core/audio/loader/trigger.rs +98 -97
  104. package/rust/core/audio/mod.rs +6 -7
  105. package/rust/core/audio/special/easing.rs +189 -189
  106. package/rust/core/audio/special/env.rs +45 -45
  107. package/rust/core/audio/special/math.rs +134 -134
  108. package/rust/core/audio/special/modulator.rs +143 -143
  109. package/rust/core/builder/mod.rs +129 -86
  110. package/rust/core/debugger/{module.rs → logs.rs} +52 -55
  111. package/rust/core/debugger/mod.rs +30 -30
  112. package/rust/core/debugger/store.rs +38 -40
  113. package/rust/core/error/mod.rs +269 -269
  114. package/rust/core/lexer/driver.rs +2 -4
  115. package/rust/core/mod.rs +9 -10
  116. package/rust/core/parser/driver/block.rs +111 -0
  117. package/rust/core/parser/driver/cursor.rs +82 -0
  118. package/rust/core/parser/driver/driver_impl.rs +159 -0
  119. package/rust/core/parser/driver/mod.rs +6 -0
  120. package/rust/core/parser/driver/parse_array.rs +120 -0
  121. package/rust/core/parser/driver/parse_map.rs +247 -0
  122. package/rust/core/parser/driver/parser.rs +160 -0
  123. package/rust/core/parser/handler/arrow_call.rs +90 -15
  124. package/rust/core/parser/handler/at.rs +279 -279
  125. package/rust/core/parser/handler/bank.rs +104 -104
  126. package/rust/core/parser/handler/condition.rs +83 -83
  127. package/rust/core/parser/handler/dot.rs +148 -148
  128. package/rust/core/parser/handler/identifier/automate.rs +254 -254
  129. package/rust/core/parser/handler/identifier/call.rs +91 -91
  130. package/rust/core/parser/handler/identifier/emit.rs +70 -70
  131. package/rust/core/parser/handler/identifier/function.rs +113 -113
  132. package/rust/core/parser/handler/identifier/group.rs +89 -89
  133. package/rust/core/parser/handler/identifier/let_.rs +173 -173
  134. package/rust/core/parser/handler/identifier/mod.rs +55 -55
  135. package/rust/core/parser/handler/identifier/on.rs +107 -107
  136. package/rust/core/parser/handler/identifier/print.rs +49 -49
  137. package/rust/core/parser/handler/identifier/sleep.rs +96 -43
  138. package/rust/core/parser/handler/identifier/spawn.rs +91 -91
  139. package/rust/core/parser/handler/identifier/synth.rs +39 -3
  140. package/rust/core/parser/handler/loop_.rs +194 -194
  141. package/rust/core/parser/handler/pattern.rs +25 -2
  142. package/rust/core/parser/handler/tempo.rs +105 -57
  143. package/rust/core/parser/statement.rs +10 -11
  144. package/rust/core/plugin/loader.rs +137 -137
  145. package/rust/core/plugin/runner/mod.rs +11 -0
  146. package/rust/core/plugin/{runner.rs → runner/non_wasm.rs} +206 -72
  147. package/rust/core/plugin/runner/wasm32.rs +44 -0
  148. package/rust/core/preprocessor/loader/inject.rs +313 -0
  149. package/rust/core/preprocessor/loader/loader_helpers.rs +110 -0
  150. package/rust/core/preprocessor/loader/mod.rs +235 -0
  151. package/rust/core/preprocessor/module.rs +55 -60
  152. package/rust/core/preprocessor/{processor.rs → processor/handlers.rs} +107 -114
  153. package/rust/core/preprocessor/processor/mod.rs +1 -0
  154. package/rust/core/preprocessor/resolver/function.rs +69 -69
  155. package/rust/core/preprocessor/resolver/group.rs +122 -94
  156. package/rust/core/preprocessor/resolver/pattern.rs +14 -2
  157. package/rust/core/store/global.rs +57 -61
  158. package/rust/core/store/mod.rs +1 -5
  159. package/rust/lib.rs +323 -308
  160. package/rust/macros/Cargo.toml +14 -0
  161. package/rust/macros/src/lib.rs +52 -0
  162. package/rust/main.rs +336 -143
  163. package/rust/types/Cargo.toml +1 -1
  164. package/rust/types/src/addons.rs +57 -55
  165. package/rust/types/src/config.rs +82 -74
  166. package/rust/types/src/lib.rs +15 -12
  167. package/rust/types/src/plugin.rs +20 -0
  168. package/rust/types/src/store.rs +139 -0
  169. package/rust/types/src/telemetry.rs +85 -85
  170. package/rust/utils/Cargo.toml +5 -2
  171. package/rust/utils/src/file.rs +477 -94
  172. package/rust/utils/src/first_usage.rs +97 -97
  173. package/rust/utils/src/lib.rs +9 -9
  174. package/rust/utils/src/logger.rs +200 -200
  175. package/rust/utils/src/path.rs +158 -88
  176. package/rust/utils/src/signature.rs +41 -41
  177. package/rust/utils/src/spinner.rs +20 -20
  178. package/rust/utils/src/version.rs +58 -27
  179. package/rust/utils/src/watcher.rs +46 -46
  180. package/rust/web/api.rs +5 -5
  181. package/rust/web/auth.rs +5 -0
  182. package/rust/web/cdn.rs +34 -34
  183. package/rust/web/forge.rs +5 -0
  184. package/rust/web/mod.rs +2 -0
  185. package/tests/integration.rs +21 -21
  186. package/typescript/core/functions/index.ts +11 -0
  187. package/typescript/pkg/devalang_core.ts +20 -4
  188. package/typescript/scripts/version/copy-to-binary.ts +82 -0
  189. package/rust/cli/bank/api.rs +0 -122
  190. package/rust/cli/bank/commands.rs +0 -275
  191. package/rust/cli/bank/mod.rs +0 -29
  192. package/rust/cli/install/bank.rs +0 -53
  193. package/rust/cli/install/commands.rs +0 -35
  194. package/rust/cli/install/mod.rs +0 -4
  195. package/rust/cli/install/plugin.rs +0 -61
  196. package/rust/core/audio/engine/sample.rs +0 -366
  197. package/rust/core/audio/engine/synth.rs +0 -325
  198. package/rust/core/audio/interpreter/arrow_call.rs +0 -311
  199. package/rust/core/audio/renderer.rs +0 -54
  200. package/rust/core/parser/driver.rs +0 -584
  201. package/rust/core/preprocessor/loader.rs +0 -637
  202. package/rust/core/store/export.rs +0 -28
  203. package/rust/core/store/function.rs +0 -40
  204. package/rust/core/store/import.rs +0 -28
  205. package/rust/core/store/variable.rs +0 -51
  206. package/rust/core/utils/mod.rs +0 -1
  207. package/rust/core/utils/path.rs +0 -37
@@ -0,0 +1,294 @@
1
+ use devalang_types::Value;
2
+ use std::collections::HashMap;
3
+
4
+ pub struct FilterSpec {
5
+ pub kind: String,
6
+ pub cutoff: f32,
7
+ }
8
+
9
+ pub struct FilterState {
10
+ pub prev_l: f32,
11
+ pub prev_r: f32,
12
+ pub prev_in_l: f32,
13
+ pub prev_in_r: f32,
14
+ pub prev_out_l: f32,
15
+ pub prev_out_r: f32,
16
+ }
17
+
18
+ pub struct NoteSetup {
19
+ pub sample_rate: f32,
20
+ pub channels: usize,
21
+ pub total_samples: usize,
22
+ pub start_sample: usize,
23
+ pub attack_samples: usize,
24
+ pub decay_samples: usize,
25
+ pub release_samples: usize,
26
+ pub sustain_level: f32,
27
+ pub pluck_click: f32,
28
+ pub pluck_click_samples: usize,
29
+ pub drive: f32,
30
+ pub filters: Vec<FilterSpec>,
31
+ pub filter_states: Vec<FilterState>,
32
+ pub lfo_rate: f32,
33
+ pub lfo_depth: f32,
34
+ pub lfo_target: Option<String>,
35
+ pub voices: usize,
36
+ pub unison_detune: f32,
37
+ pub volume_env: HashMap<String, Value>,
38
+ pub pan_env: HashMap<String, Value>,
39
+ pub pitch_env: HashMap<String, Value>,
40
+ }
41
+
42
+ pub fn build_note_setup(
43
+ engine: &mut crate::core::audio::engine::AudioEngine,
44
+ _waveform: &str,
45
+ freq: f32,
46
+ amp: f32,
47
+ start_time_ms: f32,
48
+ mut duration_ms: f32,
49
+ synth_params: &HashMap<String, Value>,
50
+ note_params: &HashMap<String, Value>,
51
+ automation: &Option<HashMap<String, Value>>,
52
+ ) -> NoteSetup {
53
+ use crate::core::audio::engine::helpers;
54
+
55
+ // Extract ADSR and normalize units
56
+ let attack = engine.extract_f32(synth_params, "attack").unwrap_or(0.0);
57
+ let decay = engine.extract_f32(synth_params, "decay").unwrap_or(0.0);
58
+ let sustain = engine.extract_f32(synth_params, "sustain").unwrap_or(1.0);
59
+ let release = engine.extract_f32(synth_params, "release").unwrap_or(0.0);
60
+ let _sustain_level = if sustain > 1.0 {
61
+ (sustain / 100.0).clamp(0.0, 1.0)
62
+ } else {
63
+ sustain.clamp(0.0, 1.0)
64
+ };
65
+
66
+ if let Some(g) = engine.extract_f32(note_params, "gate") {
67
+ if g > 0.0 && g <= 1.0 {
68
+ duration_ms = duration_ms * g;
69
+ } else if g > 1.0 {
70
+ duration_ms = duration_ms * (g / 100.0);
71
+ }
72
+ } else if let Some(g) = engine.extract_f32(synth_params, "gate") {
73
+ if g > 0.0 && g <= 1.0 {
74
+ duration_ms = duration_ms * g;
75
+ } else if g > 1.0 {
76
+ duration_ms = duration_ms * (g / 100.0);
77
+ }
78
+ }
79
+
80
+ let velocity = engine.extract_f32(note_params, "velocity").unwrap_or(1.0);
81
+
82
+ let detune_cents = engine
83
+ .extract_f32(note_params, "detune")
84
+ .or(engine.extract_f32(synth_params, "detune"))
85
+ .unwrap_or(0.0);
86
+
87
+ let _lowpass_cut = engine
88
+ .extract_f32(note_params, "lowpass")
89
+ .or(engine.extract_f32(synth_params, "lowpass"))
90
+ .unwrap_or(0.0);
91
+
92
+ let _amplitude = (i16::MAX as f32) * amp.clamp(0.0, 1.0) * velocity.clamp(0.0, 1.0);
93
+
94
+ let _freq_start = freq;
95
+ let mut _freq_end = freq;
96
+ let _amp_start = amp * velocity.clamp(0.0, 1.0);
97
+ let mut _amp_end = _amp_start;
98
+
99
+ let glide = engine
100
+ .extract_boolean(note_params, "glide")
101
+ .unwrap_or(false);
102
+ let slide = engine
103
+ .extract_boolean(note_params, "slide")
104
+ .unwrap_or(false);
105
+ if glide {
106
+ if let Some(Value::Number(target_freq)) = note_params.get("target_freq") {
107
+ _freq_end = *target_freq;
108
+ } else {
109
+ _freq_end = freq * 1.5;
110
+ }
111
+ }
112
+ if slide {
113
+ if let Some(Value::Number(target_amp)) = note_params.get("target_amp") {
114
+ _amp_end = *target_amp * velocity.clamp(0.0, 1.0);
115
+ } else {
116
+ _amp_end = _amp_start * 0.5;
117
+ }
118
+ }
119
+
120
+ let sample_rate = engine.sample_rate as f32;
121
+ let channels = engine.channels as usize;
122
+
123
+ let total_samples = ((duration_ms / 1000.0) * sample_rate) as usize;
124
+ let start_sample = ((start_time_ms / 1000.0) * sample_rate) as usize;
125
+
126
+ // MIDI event
127
+ let midi_note_f = 69.0 + 12.0 * (_freq_start / 440.0).log2();
128
+ let midi_note = midi_note_f.round().clamp(0.0, 127.0) as u8;
129
+ let midi_vel = (velocity.clamp(0.0, 1.0) * 127.0).round().clamp(0.0, 127.0) as u8;
130
+ engine
131
+ .midi_events
132
+ .push(crate::core::audio::engine::driver::MidiNoteEvent {
133
+ key: midi_note,
134
+ vel: midi_vel,
135
+ start_ms: start_time_ms as u32,
136
+ duration_ms: duration_ms as u32,
137
+ channel: 0,
138
+ });
139
+
140
+ let _detune_factor = (2.0_f32).powf(detune_cents / 1200.0);
141
+
142
+ let (_volume_env, _pan_env, _pitch_env) = helpers::env_maps_from_automation(automation);
143
+
144
+ let attack_s = if attack > 10.0 {
145
+ attack / 1000.0
146
+ } else {
147
+ attack
148
+ };
149
+ let decay_s = if decay > 10.0 { decay / 1000.0 } else { decay };
150
+ let release_s = if release > 10.0 {
151
+ release / 1000.0
152
+ } else {
153
+ release
154
+ };
155
+ let sustain_level = _sustain_level;
156
+
157
+ let attack_samples = (attack_s * sample_rate) as usize;
158
+ let decay_samples = (decay_s * sample_rate) as usize;
159
+ let release_samples = (release_s * sample_rate) as usize;
160
+
161
+ // optional pluck click
162
+ let pluck_click = engine
163
+ .extract_f32(note_params, "pluck_click")
164
+ .or(engine.extract_f32(synth_params, "pluck_click"))
165
+ .unwrap_or(0.0);
166
+ let pluck_click_ms = engine
167
+ .extract_f32(note_params, "pluck_click_ms")
168
+ .or(engine.extract_f32(synth_params, "pluck_click_ms"))
169
+ .unwrap_or(10.0);
170
+ let pluck_click_samples = ((pluck_click_ms / 1000.0) * sample_rate) as usize;
171
+
172
+ let drive = engine
173
+ .extract_f32(note_params, "drive")
174
+ .or(engine.extract_f32(synth_params, "drive"))
175
+ .unwrap_or(0.0);
176
+
177
+ // parse filter specs
178
+ let mut raw_filters: Vec<HashMap<String, Value>> = Vec::new();
179
+ if let Some(Value::Array(arr)) = synth_params.get("filters") {
180
+ for v in arr {
181
+ if let Value::Map(m) = v {
182
+ raw_filters.push(m.clone());
183
+ }
184
+ }
185
+ }
186
+ if let Some(Value::Array(arr)) = note_params.get("filters") {
187
+ for v in arr {
188
+ if let Value::Map(m) = v {
189
+ raw_filters.push(m.clone());
190
+ }
191
+ }
192
+ }
193
+
194
+ let mut filters: Vec<FilterSpec> = Vec::new();
195
+ let mut filter_states: Vec<FilterState> = Vec::new();
196
+ for rf in raw_filters.into_iter() {
197
+ let kind = rf
198
+ .get("type")
199
+ .and_then(|v| match v {
200
+ Value::String(s) => Some(s.clone()),
201
+ Value::Identifier(s) => Some(s.clone()),
202
+ _ => None,
203
+ })
204
+ .unwrap_or_else(|| "lowpass".to_string());
205
+ let cutoff = rf
206
+ .get("cutoff")
207
+ .and_then(|v| match v {
208
+ Value::Number(n) => Some(*n),
209
+ Value::String(s) => s.parse::<f32>().ok(),
210
+ _ => None,
211
+ })
212
+ .unwrap_or(1000.0);
213
+ filters.push(FilterSpec {
214
+ kind: kind.to_lowercase(),
215
+ cutoff,
216
+ });
217
+ filter_states.push(FilterState {
218
+ prev_l: 0.0,
219
+ prev_r: 0.0,
220
+ prev_in_l: 0.0,
221
+ prev_in_r: 0.0,
222
+ prev_out_l: 0.0,
223
+ prev_out_r: 0.0,
224
+ });
225
+ }
226
+
227
+ // LFO parsing (from synth or note) - simplified: prefer note params over synth params
228
+ let mut lfo_rate = 0.0f32;
229
+ let mut lfo_depth = 0.0f32;
230
+ let mut lfo_target: Option<String> = None;
231
+ if let Some(Value::Map(m)) = synth_params.get("lfo") {
232
+ if let Some(Value::Number(r)) = m.get("rate") {
233
+ lfo_rate = *r;
234
+ }
235
+ if let Some(Value::Number(d)) = m.get("depth") {
236
+ lfo_depth = *d;
237
+ }
238
+ if let Some(Value::String(t)) = m.get("target") {
239
+ lfo_target = Some(t.clone());
240
+ }
241
+ }
242
+ if let Some(Value::Map(m)) = note_params.get("lfo") {
243
+ if let Some(Value::Number(r)) = m.get("rate") {
244
+ lfo_rate = *r;
245
+ }
246
+ if let Some(Value::Number(d)) = m.get("depth") {
247
+ lfo_depth = *d;
248
+ }
249
+ if let Some(Value::String(t)) = m.get("target") {
250
+ lfo_target = Some(t.clone());
251
+ }
252
+ }
253
+
254
+ let voices = engine
255
+ .extract_f32(note_params, "voices")
256
+ .or(engine.extract_f32(synth_params, "voices"))
257
+ .unwrap_or(1.0)
258
+ .max(1.0)
259
+ .round() as usize;
260
+ let unison_detune = engine
261
+ .extract_f32(note_params, "unison_detune")
262
+ .or(engine.extract_f32(synth_params, "unison_detune"))
263
+ .unwrap_or(0.0);
264
+
265
+ let (volume_env, pan_env, pitch_env) = (
266
+ helpers::env_map_to_hash(&_volume_env),
267
+ helpers::env_map_to_hash(&_pan_env),
268
+ helpers::env_map_to_hash(&_pitch_env),
269
+ );
270
+
271
+ NoteSetup {
272
+ sample_rate,
273
+ channels,
274
+ total_samples,
275
+ start_sample,
276
+ attack_samples,
277
+ decay_samples,
278
+ release_samples,
279
+ sustain_level,
280
+ pluck_click,
281
+ pluck_click_samples,
282
+ drive,
283
+ filters,
284
+ filter_states,
285
+ lfo_rate,
286
+ lfo_depth,
287
+ lfo_target,
288
+ voices,
289
+ unison_detune,
290
+ volume_env,
291
+ pan_env,
292
+ pitch_env,
293
+ }
294
+ }
@@ -0,0 +1,300 @@
1
+ use crate::config::ops::load_config;
2
+ use devalang_types::Value;
3
+ use devalang_types::VariableTable;
4
+ use devalang_utils::path::normalize_path;
5
+ use rodio::{Decoder, Source};
6
+ use std::path::PathBuf;
7
+ use std::{collections::HashMap, fs::File, io::BufReader, path::Path};
8
+
9
+ pub fn insert_sample_impl(
10
+ engine: &mut crate::core::audio::engine::driver::AudioEngine,
11
+ filepath: &str,
12
+ time_secs: f32,
13
+ dur_sec: f32,
14
+ effects: Option<HashMap<String, Value>>,
15
+ variable_table: &VariableTable,
16
+ ) {
17
+ if filepath.is_empty() {
18
+ eprintln!("❌ Empty file path provided for audio sample.");
19
+ return;
20
+ }
21
+
22
+ let module_root = Path::new(&engine.module_name);
23
+ let root = match devalang_utils::path::get_project_root() {
24
+ Ok(p) => p,
25
+ Err(_) => std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from(".")),
26
+ };
27
+ let resolved_path: String;
28
+
29
+ let mut var_path = filepath.to_string();
30
+ if let Some(Value::String(variable_path)) = variable_table.variables.get(filepath) {
31
+ var_path = variable_path.clone();
32
+ } else if let Some(Value::Sample(sample_path)) = variable_table.variables.get(filepath) {
33
+ var_path = sample_path.clone();
34
+ }
35
+
36
+ if var_path.starts_with("devalang://") {
37
+ let path_after_protocol = var_path.replace("devalang://", "");
38
+ let parts: Vec<&str> = path_after_protocol.split('/').collect();
39
+
40
+ if parts.len() < 3 {
41
+ eprintln!(
42
+ "❌ Invalid devalang:// path format. Expected devalang://<type>/<author>.<bank>/<entity>"
43
+ );
44
+ return;
45
+ }
46
+
47
+ let obj_type = parts[0];
48
+ let bank_name = parts[1];
49
+ // Rejoin the remainder as the entity path so bank entries can contain
50
+ // nested paths like "subdir/sample.wav" or plain names.
51
+ let entity_name = parts[2..].join("/");
52
+
53
+ let deva_dir = match devalang_utils::path::get_deva_dir() {
54
+ Ok(dir) => dir,
55
+ Err(e) => {
56
+ eprintln!("❌ {}", e);
57
+ return;
58
+ }
59
+ };
60
+ let subdir = match obj_type {
61
+ "bank" => "banks",
62
+ "plugin" => "plugins",
63
+ "preset" => "presets",
64
+ "template" => "templates",
65
+ other => other,
66
+ };
67
+
68
+ // Try both plural and singular folder names (some installs use 'bank' instead of 'banks')
69
+ let singular = if subdir.ends_with('s') {
70
+ &subdir[..subdir.len() - 1]
71
+ } else {
72
+ subdir
73
+ };
74
+
75
+ // Build a list of candidate addon roots to support different layouts:
76
+ // - legacy flat: .deva/<subdir>/<publisher>.<name>
77
+ // - nested: .deva/<subdir>/<publisher>/<name>
78
+ // Test both plural and singular folder names.
79
+ let mut candidate_roots: Vec<PathBuf> = Vec::new();
80
+ for sd in &[subdir, singular] {
81
+ let base = deva_dir.join(sd).join(bank_name);
82
+ candidate_roots.push(base.clone());
83
+
84
+ if bank_name.contains('.') {
85
+ let mut it = bank_name.splitn(2, '.');
86
+ let pubr = it.next().unwrap_or("");
87
+ let nm = it.next().unwrap_or("");
88
+ candidate_roots.push(deva_dir.join(sd).join(pubr).join(nm));
89
+ }
90
+ }
91
+
92
+ // If none of the candidate roots yields the asset, we will also
93
+ // try to lookup referenced addons from the project config.
94
+
95
+ // Helper to resolve audio path for a given addon root
96
+ let resolve_from_root = |root: &PathBuf| -> Option<String> {
97
+ // Determine audio dir: prefer audioPath in bank.toml, else audio/
98
+ let mut audio_dir = root.join("audio");
99
+ let bank_toml = root.join("bank.toml");
100
+ if bank_toml.exists() {
101
+ if let Ok(content) = std::fs::read_to_string(&bank_toml) {
102
+ if let Ok(parsed) = toml::from_str::<toml::Value>(&content) {
103
+ if let Some(ap) = parsed
104
+ .get("audioPath")
105
+ .or_else(|| parsed.get("audio_path"))
106
+ .and_then(|v| v.as_str())
107
+ {
108
+ let ap_norm = ap.replace("\\", "/");
109
+ audio_dir = root.join(ap_norm);
110
+ }
111
+ }
112
+ }
113
+ }
114
+
115
+ let candidate = audio_dir.join(&entity_name);
116
+ if candidate.exists() {
117
+ return Some(candidate.to_string_lossy().to_string());
118
+ }
119
+
120
+ let has_extension = std::path::Path::new(&entity_name).extension().is_some();
121
+ if !has_extension {
122
+ let wav_candidate = audio_dir.join(format!("{}.wav", entity_name));
123
+ if wav_candidate.exists() {
124
+ return Some(wav_candidate.to_string_lossy().to_string());
125
+ }
126
+
127
+ let legacy_candidate = root.join(format!("{}.wav", entity_name));
128
+ if legacy_candidate.exists() {
129
+ return Some(legacy_candidate.to_string_lossy().to_string());
130
+ }
131
+ } else {
132
+ let legacy_candidate = root.join(&entity_name);
133
+ if legacy_candidate.exists() {
134
+ return Some(legacy_candidate.to_string_lossy().to_string());
135
+ }
136
+ }
137
+
138
+ None
139
+ };
140
+
141
+ let mut found: Option<String> = None;
142
+ for root in &candidate_roots {
143
+ if let Some(p) = resolve_from_root(root) {
144
+ found = Some(p);
145
+ break;
146
+ }
147
+ }
148
+
149
+ // If not found in typical layouts, try to find the addon referenced in the project config
150
+ if found.is_none() {
151
+ if let Ok(config_path) = devalang_utils::path::get_devalang_config_path() {
152
+ if let Some(cfg) = load_config(Some(&config_path)) {
153
+ // Scan banks or plugins depending on obj_type
154
+ if obj_type == "bank" {
155
+ if let Some(banks) = cfg.banks {
156
+ for b in banks {
157
+ if let Some(name_in_path) = b.path.strip_prefix("devalang://bank/")
158
+ {
159
+ // match by exact, suffix, or dot notation
160
+ if name_in_path == bank_name
161
+ || name_in_path.ends_with(bank_name)
162
+ {
163
+ let root = deva_dir.join(subdir).join(name_in_path);
164
+ if let Some(p) = resolve_from_root(&root) {
165
+ found = Some(p);
166
+ break;
167
+ }
168
+ // try nested layout
169
+ if name_in_path.contains('.') {
170
+ let mut it = name_in_path.splitn(2, '.');
171
+ let pubr = it.next().unwrap_or("");
172
+ let nm = it.next().unwrap_or("");
173
+ let root2 = deva_dir.join(subdir).join(pubr).join(nm);
174
+ if let Some(p) = resolve_from_root(&root2) {
175
+ found = Some(p);
176
+ break;
177
+ }
178
+ }
179
+ }
180
+ }
181
+ }
182
+ }
183
+ } else if obj_type == "plugin" {
184
+ if let Some(plugins) = cfg.plugins {
185
+ for p in plugins {
186
+ if let Some(name_in_path) =
187
+ p.path.strip_prefix("devalang://plugin/")
188
+ {
189
+ if name_in_path == bank_name
190
+ || name_in_path.ends_with(bank_name)
191
+ {
192
+ let root = deva_dir.join(subdir).join(name_in_path);
193
+ if let Some(path_found) = resolve_from_root(&root) {
194
+ found = Some(path_found);
195
+ break;
196
+ }
197
+ if name_in_path.contains('.') {
198
+ let mut it = name_in_path.splitn(2, '.');
199
+ let pubr = it.next().unwrap_or("");
200
+ let nm = it.next().unwrap_or("");
201
+ let root2 = deva_dir.join(subdir).join(pubr).join(nm);
202
+ if let Some(path_found) = resolve_from_root(&root2) {
203
+ found = Some(path_found);
204
+ break;
205
+ }
206
+ }
207
+ }
208
+ }
209
+ }
210
+ }
211
+ }
212
+ }
213
+ }
214
+ }
215
+
216
+ if let Some(p) = found {
217
+ resolved_path = p;
218
+ } else {
219
+ // Not found; fallback to legacy candidate for error message
220
+ let legacy = deva_dir
221
+ .join(subdir)
222
+ .join(bank_name)
223
+ .join(format!("{}.wav", entity_name));
224
+ resolved_path = legacy.to_string_lossy().to_string();
225
+ }
226
+ } else {
227
+ let entry_dir = module_root.parent().unwrap_or(&root);
228
+ let absolute_path = root.join(entry_dir).join(&var_path);
229
+
230
+ resolved_path = normalize_path(absolute_path.to_string_lossy().to_string());
231
+ }
232
+
233
+ if !Path::new(&resolved_path).exists() {
234
+ eprintln!("❌ Unknown trigger or missing audio file: {}", filepath);
235
+ return;
236
+ }
237
+
238
+ let file = match File::open(&resolved_path) {
239
+ Ok(f) => BufReader::new(f),
240
+ Err(e) => {
241
+ eprintln!("❌ Failed to open audio file {}: {}", resolved_path, e);
242
+ return;
243
+ }
244
+ };
245
+
246
+ let decoder = match Decoder::new(file) {
247
+ Ok(d) => d,
248
+ Err(e) => {
249
+ eprintln!("❌ Failed to decode audio file {}: {}", resolved_path, e);
250
+ return;
251
+ }
252
+ };
253
+
254
+ // Read frames from decoder and convert to mono if needed.
255
+ let sample_rate = engine.sample_rate as f32;
256
+ let channels = engine.channels as usize;
257
+
258
+ let max_frames = (dur_sec * sample_rate) as usize;
259
+ let dec_channels = decoder.channels() as usize;
260
+ let max_raw_samples = max_frames.saturating_mul(dec_channels.max(1));
261
+ let raw_samples: Vec<i16> = decoder.convert_samples().take(max_raw_samples).collect();
262
+
263
+ // Convert interleaved channels to mono by averaging channels per frame.
264
+ // Apply a small RMS-preserving scale so mono level is similar to mixed stereo.
265
+ let actual_frames = if dec_channels > 0 {
266
+ raw_samples.len() / dec_channels
267
+ } else {
268
+ 0
269
+ };
270
+ let mut samples: Vec<i16> = Vec::with_capacity(actual_frames);
271
+ let rms_scale = (dec_channels as f32).sqrt();
272
+ for frame in 0..actual_frames {
273
+ let mut sum: i32 = 0;
274
+ for ch in 0..dec_channels {
275
+ sum += raw_samples[frame * dec_channels + ch] as i32;
276
+ }
277
+ if dec_channels > 0 {
278
+ let avg = (sum / (dec_channels as i32)) as f32;
279
+ let scaled = (avg * rms_scale).clamp(i16::MIN as f32, i16::MAX as f32) as i16;
280
+ samples.push(scaled);
281
+ } else {
282
+ samples.push(0);
283
+ }
284
+ }
285
+
286
+ if samples.is_empty() {
287
+ eprintln!("❌ No samples read from {}", resolved_path);
288
+ return;
289
+ }
290
+
291
+ let offset = (time_secs * sample_rate * (channels as f32)) as usize;
292
+ let required_len = offset + samples.len() * (channels as usize);
293
+ if engine.buffer.len() < required_len {
294
+ engine.buffer.resize(required_len, 0);
295
+ }
296
+
297
+ crate::core::audio::engine::sample::padding::pad_samples_impl(
298
+ engine, &samples, time_secs, effects,
299
+ );
300
+ }
@@ -0,0 +1,40 @@
1
+ pub mod insert;
2
+ pub mod padding;
3
+
4
+ use devalang_types::Value;
5
+ use devalang_types::VariableTable;
6
+ use std::collections::HashMap;
7
+
8
+ impl super::driver::AudioEngine {
9
+ pub fn insert_sample(
10
+ &mut self,
11
+ filepath: &str,
12
+ time_secs: f32,
13
+ dur_sec: f32,
14
+ effects: Option<HashMap<String, Value>>,
15
+ variable_table: &VariableTable,
16
+ ) {
17
+ crate::core::audio::engine::sample::insert::insert_sample_impl(
18
+ self,
19
+ filepath,
20
+ time_secs,
21
+ dur_sec,
22
+ effects,
23
+ variable_table,
24
+ );
25
+ }
26
+
27
+ pub fn pad_samples(
28
+ &mut self,
29
+ samples: &[i16],
30
+ time_secs: f32,
31
+ effects_map: Option<HashMap<String, Value>>,
32
+ ) {
33
+ crate::core::audio::engine::sample::padding::pad_samples_impl(
34
+ self,
35
+ samples,
36
+ time_secs,
37
+ effects_map,
38
+ );
39
+ }
40
+ }