|
| 1 | +// Audio routing, sized to the output device. |
| 2 | +// |
| 3 | +// On an interface with 8 or more outputs (e.g. a modular synth's 8x8 card): |
| 4 | +// |
| 5 | +// in 1 -> SVF lowpass -> out 1 (mouse X sets the cutoff) |
| 6 | +// in 2 -> reverb -> outs 3+4 |
| 7 | +// in 5 -> out 5 untouched (CV passthrough: no gain, no filtering) |
| 8 | +// space -> sample -> outs 7+8 |
| 9 | +// |
| 10 | +// On a stereo device (e.g. laptop speakers), inputs are not used, to avoid |
| 11 | +// feedback through the speakers: |
| 12 | +// |
| 13 | +// space -> sample -> SVF lowpass -> outs 1+2 (mouse X sets the cutoff) |
| 14 | +// |
| 15 | +// Pick the interface with AUDIO_DEVICE (part of its name), e.g. |
| 16 | +// AUDIO_DEVICE="ES-9" cargo run --example audio_modular |
| 17 | +// It is used for both input and output. Without it, the default output is |
| 18 | +// used with no input. AUDIO_INPUT overrides the input ("none", "default", |
| 19 | +// or part of a name). |
| 20 | +// |
| 21 | +// Routing goes through the patch bay's jacks, so the window can show a level |
| 22 | +// meter for every input and output channel. |
| 23 | +// |
| 24 | +// Keys: space plays the sample. [ and ] move it to the previous/next output |
| 25 | +// pair (1+2 ... 15+16), to find which channels reach your speakers or |
| 26 | +// headphones. B toggles block size 256/128 (restarts the stream, keeps the |
| 27 | +// patch). |
| 28 | +// Unplug the interface while running: the stream stops (nothing plays on |
| 29 | +// other outputs), and resumes on the same patch when it is plugged back in. |
| 30 | + |
| 31 | +use bevy::color::Color; |
| 32 | +use bevy::prelude::Entity; |
| 33 | +use processing::prelude::*; |
| 34 | +use processing_glfw::GlfwContext; |
| 35 | +use processing_render::render::command::DrawCommand; |
| 36 | + |
| 37 | +const WIDTH: u32 = 640; |
| 38 | +const HEIGHT: u32 = 470; |
| 39 | + |
| 40 | +fn main() { |
| 41 | + if let Err(e) = sketch() { |
| 42 | + eprintln!("Sketch error: {e:?}"); |
| 43 | + exit(1).unwrap(); |
| 44 | + } |
| 45 | + exit(0).unwrap(); |
| 46 | +} |
| 47 | + |
| 48 | +/// Port numbers are zero-based; jacks are usually labelled from 1. |
| 49 | +fn jack(n: u32) -> u32 { |
| 50 | + n - 1 |
| 51 | +} |
| 52 | + |
| 53 | +fn sketch() -> error::Result<()> { |
| 54 | + let mut config = Config::default(); |
| 55 | + config.set(ConfigKey::AudioEnabled, "true".into()); |
| 56 | + // Without AUDIO_DEVICE: default output, and no input (no microphone). |
| 57 | + if let Ok(device) = std::env::var("AUDIO_DEVICE") { |
| 58 | + config.set(ConfigKey::AudioOutputDevice, device.clone()); |
| 59 | + config.set(ConfigKey::AudioInputDevice, device); |
| 60 | + } |
| 61 | + if let Ok(input) = std::env::var("AUDIO_INPUT") { |
| 62 | + config.set(ConfigKey::AudioInputDevice, input); |
| 63 | + } |
| 64 | + config.set(ConfigKey::AudioBlockFrames, "256".into()); |
| 65 | + // Room for every channel of a 16-channel interface like the ES-9, even if |
| 66 | + // it is plugged in after the sketch starts. |
| 67 | + config.set(ConfigKey::AudioGraphChannels, "16".into()); |
| 68 | + |
| 69 | + let mut glfw_ctx = GlfwContext::new(WIDTH, HEIGHT, false)?; |
| 70 | + init(config)?; |
| 71 | + let surface = glfw_ctx.create_surface(WIDTH, HEIGHT, false)?; |
| 72 | + let graphics = graphics_create(surface, WIDTH, HEIGHT, TextureFormat::Rgba16Float)?; |
| 73 | + |
| 74 | + println!("outputs: {:#?}", audio_list_output_devices()?); |
| 75 | + println!("inputs: {:#?}", audio_list_input_devices()?); |
| 76 | + println!("{:#?}", audio_info()?); |
| 77 | + |
| 78 | + let pluck = audio_sample_load("audio/pluck.wav")?; |
| 79 | + // Built once the output device is running, so the layout fits it. |
| 80 | + let mut patch: Option<Patch> = None; |
| 81 | + let mut block_frames = 256; |
| 82 | + let mut mouse_moved = false; |
| 83 | + let mut log: Vec<String> = Vec::new(); |
| 84 | + |
| 85 | + let draw = |command| graphics_record_command(graphics, command); |
| 86 | + let text = |content: String, x: f32, y: f32| { |
| 87 | + draw(DrawCommand::Text { |
| 88 | + content, |
| 89 | + x, |
| 90 | + y, |
| 91 | + z: 0.0, |
| 92 | + max_w: None, |
| 93 | + max_h: None, |
| 94 | + stroke_weight: None, |
| 95 | + }) |
| 96 | + }; |
| 97 | + |
| 98 | + while glfw_ctx.poll_events() { |
| 99 | + for event in audio_events()? { |
| 100 | + println!("audio: {event:?}"); |
| 101 | + log.push(format!("{event:?}")); |
| 102 | + } |
| 103 | + if log.len() > 6 { |
| 104 | + log.drain(..log.len() - 6); |
| 105 | + } |
| 106 | + |
| 107 | + let info = audio_info()?; |
| 108 | + if patch.is_none() && info.status == AudioStatus::Running { |
| 109 | + let p = build_patch(&info)?; |
| 110 | + println!("patched: {}", p.layout); |
| 111 | + patch = Some(p); |
| 112 | + } |
| 113 | + |
| 114 | + // The filter starts fully open; moving the mouse over the window takes |
| 115 | + // over: 100 Hz at the left edge to 18 kHz at the right. |
| 116 | + mouse_moved |= input_mouse_moved()?; |
| 117 | + let mx = if mouse_moved { |
| 118 | + input_mouse_x(surface)?.clamp(0.0, WIDTH as f32) |
| 119 | + } else { |
| 120 | + WIDTH as f32 |
| 121 | + }; |
| 122 | + let cutoff = 100.0 * (18_000.0f32 / 100.0).powf(mx / WIDTH as f32); |
| 123 | + if let Some(p) = &mut patch { |
| 124 | + audio_node_set(p.filter, "cutoff_hz", cutoff)?; |
| 125 | + if input_key_just_pressed(KeyCode::Space)? { |
| 126 | + audio_sample_play(p.sampler, pluck, 0.8)?; |
| 127 | + } |
| 128 | + if input_key_just_pressed(KeyCode::BracketRight)? { |
| 129 | + p.move_sample(2)?; |
| 130 | + } |
| 131 | + if input_key_just_pressed(KeyCode::BracketLeft)? { |
| 132 | + p.move_sample(-2)?; |
| 133 | + } |
| 134 | + } |
| 135 | + if input_key_just_pressed(KeyCode::KeyB)? { |
| 136 | + block_frames = if block_frames == 256 { 128 } else { 256 }; |
| 137 | + audio_set_block_frames(block_frames)?; |
| 138 | + } |
| 139 | + |
| 140 | + let mut lines = vec![ |
| 141 | + format!( |
| 142 | + "{:?} out: {} in: {}", |
| 143 | + info.status, |
| 144 | + info.output_device.as_deref().unwrap_or("-"), |
| 145 | + info.input_device.as_deref().unwrap_or("-"), |
| 146 | + ), |
| 147 | + format!( |
| 148 | + "{} Hz, {} frames, device {} in / {} out, graph {} / {}", |
| 149 | + info.sample_rate, |
| 150 | + info.block_frames, |
| 151 | + info.device_inputs, |
| 152 | + info.device_outputs, |
| 153 | + info.graph_inputs, |
| 154 | + info.graph_outputs, |
| 155 | + ), |
| 156 | + match &patch { |
| 157 | + Some(p) => p.layout.to_string(), |
| 158 | + None => "waiting for the output device...".to_string(), |
| 159 | + }, |
| 160 | + match &patch { |
| 161 | + Some(p) => format!( |
| 162 | + "space: sample > out {}+{} [ ]: move it B: block size cutoff {cutoff:.0} Hz", |
| 163 | + p.sample_out, |
| 164 | + p.sample_out + 1 |
| 165 | + ), |
| 166 | + None => String::new(), |
| 167 | + }, |
| 168 | + ]; |
| 169 | + lines.extend(log.iter().cloned()); |
| 170 | + |
| 171 | + graphics_begin_draw(graphics)?; |
| 172 | + draw(DrawCommand::BackgroundColor(Color::srgb(0.08, 0.08, 0.1)))?; |
| 173 | + draw(DrawCommand::NoStroke)?; |
| 174 | + draw(DrawCommand::Fill(Color::srgb(0.2, 0.5, 0.9)))?; |
| 175 | + draw(DrawCommand::Rect { |
| 176 | + x: 0.0, |
| 177 | + y: HEIGHT as f32 - 6.0, |
| 178 | + w: mx, |
| 179 | + h: 6.0, |
| 180 | + radii: [0.0; 4], |
| 181 | + })?; |
| 182 | + draw(DrawCommand::Fill(Color::WHITE))?; |
| 183 | + draw(DrawCommand::TextSize(14.0))?; |
| 184 | + for (i, line) in lines.iter().enumerate() { |
| 185 | + text(line.clone(), 12.0, 24.0 + i as f32 * 20.0)?; |
| 186 | + } |
| 187 | + |
| 188 | + // one bar per device channel; height is the peak level (sqrt so quiet |
| 189 | + // signals show) |
| 190 | + let levels = audio_jack_levels()?; |
| 191 | + let rows = [ |
| 192 | + ( |
| 193 | + "in", |
| 194 | + &levels.inputs[..(info.device_inputs as usize).min(levels.inputs.len())], |
| 195 | + ), |
| 196 | + ( |
| 197 | + "out", |
| 198 | + &levels.outputs[..(info.device_outputs as usize).min(levels.outputs.len())], |
| 199 | + ), |
| 200 | + ]; |
| 201 | + for (row, (label, levels)) in rows.into_iter().enumerate() { |
| 202 | + let base = 300.0 + row as f32 * 110.0; |
| 203 | + draw(DrawCommand::Fill(Color::WHITE))?; |
| 204 | + text(label.to_string(), 12.0, base - 30.0)?; |
| 205 | + for (i, level) in levels.iter().enumerate() { |
| 206 | + let level = level.min(1.0).sqrt(); |
| 207 | + let x = 60.0 + i as f32 * 36.0; |
| 208 | + draw(DrawCommand::Fill(Color::srgb(0.2, 0.2, 0.25)))?; |
| 209 | + draw(DrawCommand::Rect { |
| 210 | + x, |
| 211 | + y: base - 80.0, |
| 212 | + w: 28.0, |
| 213 | + h: 80.0, |
| 214 | + radii: [0.0; 4], |
| 215 | + })?; |
| 216 | + draw(DrawCommand::Fill(Color::srgb(0.3, 0.9, 0.4)))?; |
| 217 | + draw(DrawCommand::Rect { |
| 218 | + x, |
| 219 | + y: base - 80.0 * level, |
| 220 | + w: 28.0, |
| 221 | + h: 80.0 * level, |
| 222 | + radii: [0.0; 4], |
| 223 | + })?; |
| 224 | + draw(DrawCommand::Fill(Color::WHITE))?; |
| 225 | + text(format!("{}", i + 1), x + 6.0, base + 16.0)?; |
| 226 | + } |
| 227 | + } |
| 228 | + graphics_end_draw(graphics)?; |
| 229 | + } |
| 230 | + Ok(()) |
| 231 | +} |
| 232 | + |
| 233 | +/// This example's routing, built on the patch bay's jacks (`audio_jack_input` |
| 234 | +/// / `audio_jack_output`), so every channel shows on the meters. |
| 235 | +struct Patch { |
| 236 | + layout: &'static str, |
| 237 | + filter: Entity, |
| 238 | + sampler: Entity, |
| 239 | + /// What feeds the sample's output pair: the sampler, or the filter after it. |
| 240 | + sample_src: Entity, |
| 241 | + /// First jack of the sample's output pair (1-based). |
| 242 | + sample_out: u32, |
| 243 | + /// Output channels on the device when the patch was built. |
| 244 | + outputs: u32, |
| 245 | +} |
| 246 | + |
| 247 | +fn input(n: u32) -> error::Result<Entity> { |
| 248 | + audio_jack_input(jack(n)) |
| 249 | +} |
| 250 | + |
| 251 | +fn output(n: u32) -> error::Result<Entity> { |
| 252 | + audio_jack_output(jack(n)) |
| 253 | +} |
| 254 | + |
| 255 | +fn build_patch(info: &AudioInfo) -> error::Result<Patch> { |
| 256 | + let outputs = info.device_outputs.min(info.graph_outputs); |
| 257 | + let sampler = audio_sampler_create(2, 8)?; |
| 258 | + if outputs >= 8 { |
| 259 | + let filter = audio_node_create(AudioNodeKind::Svf, 1)?; |
| 260 | + setup_filter(filter)?; |
| 261 | + audio_connect_channel(input(1)?, 0, filter, 0)?; |
| 262 | + audio_connect_channel(filter, 0, output(1)?, 0)?; |
| 263 | + |
| 264 | + let reverb = audio_node_create(AudioNodeKind::Freeverb, 2)?; |
| 265 | + audio_node_set(reverb, "room_size", 0.85)?; |
| 266 | + audio_connect(input(2)?, reverb, &[(0, 0), (0, 1)])?; |
| 267 | + audio_connect_channel(reverb, 0, output(3)?, 0)?; |
| 268 | + audio_connect_channel(reverb, 1, output(4)?, 0)?; |
| 269 | + |
| 270 | + audio_connect_channel(input(5)?, 0, output(5)?, 0)?; |
| 271 | + |
| 272 | + audio_connect_channel(sampler, 0, output(7)?, 0)?; |
| 273 | + audio_connect_channel(sampler, 1, output(8)?, 0)?; |
| 274 | + Ok(Patch { |
| 275 | + layout: "multichannel: in1>filter>out1, in2>reverb>out3+4, in5>out5 (CV)", |
| 276 | + filter, |
| 277 | + sampler, |
| 278 | + sample_src: sampler, |
| 279 | + sample_out: 7, |
| 280 | + outputs, |
| 281 | + }) |
| 282 | + } else { |
| 283 | + let filter = audio_node_create(AudioNodeKind::Svf, 2)?; |
| 284 | + setup_filter(filter)?; |
| 285 | + audio_connect(sampler, filter, &[(0, 0), (1, 1)])?; |
| 286 | + audio_connect_channel(filter, 0, output(1)?, 0)?; |
| 287 | + // a mono device gets both sides on its one output |
| 288 | + audio_connect_channel(filter, 1, output(2.min(outputs.max(1)))?, 0)?; |
| 289 | + Ok(Patch { |
| 290 | + layout: "stereo: sample > filter > out1+2", |
| 291 | + filter, |
| 292 | + sampler, |
| 293 | + sample_src: filter, |
| 294 | + sample_out: 1, |
| 295 | + outputs, |
| 296 | + }) |
| 297 | + } |
| 298 | +} |
| 299 | + |
| 300 | +impl Patch { |
| 301 | + /// Move the sample to another output pair, `by` jacks along (wrapping), |
| 302 | + /// e.g. to find which channels reach your headphones. |
| 303 | + fn move_sample(&mut self, by: i32) -> error::Result<()> { |
| 304 | + let pairs = (self.outputs as i32 / 2).max(1); |
| 305 | + let pair = ((self.sample_out as i32 - 1) / 2 + by / 2).rem_euclid(pairs); |
| 306 | + let to = pair as u32 * 2 + 1; |
| 307 | + let [old_l, old_r] = self.pair(self.sample_out)?; |
| 308 | + audio_disconnect(self.sample_src, old_l, &[(0, 0)])?; |
| 309 | + audio_disconnect(self.sample_src, old_r, &[(1, 0)])?; |
| 310 | + let [l, r] = self.pair(to)?; |
| 311 | + audio_connect_channel(self.sample_src, 0, l, 0)?; |
| 312 | + audio_connect_channel(self.sample_src, 1, r, 0)?; |
| 313 | + self.sample_out = to; |
| 314 | + Ok(()) |
| 315 | + } |
| 316 | + |
| 317 | + /// Output jacks `first` and `first + 1` (the same one on a mono device). |
| 318 | + fn pair(&self, first: u32) -> error::Result<[Entity; 2]> { |
| 319 | + let last = self.outputs.max(1); |
| 320 | + Ok([output(first.min(last))?, output((first + 1).min(last))?]) |
| 321 | + } |
| 322 | +} |
| 323 | + |
| 324 | +fn setup_filter(filter: Entity) -> error::Result<()> { |
| 325 | + audio_node_set_variant(filter, "filter_type", "Lowpass")?; |
| 326 | + audio_node_set(filter, "q_factor", 2.0) |
| 327 | +} |
0 commit comments