rill-lofi 0.5.0-beta.7

Lo-fi audio emulation: 8-bit, 12-bit, NES, AY-3-8910, Akai S900
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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
use crate::config::{ClassicSystem, LofiConfig};
use crate::dsp;
use rill_core::prelude::*;

/// Applies lo-fi audio effects (bitcrushing, sample-rate reduction, vintage noise,
/// DAC emulation, and delay) to emulate classic digital audio systems.
pub struct LofiProcessor<const BUF_SIZE: usize> {
    state: NodeState<f32, BUF_SIZE>,
    id: NodeId,
    metadata: NodeMetadata,
    inputs: Vec<Port<f32, BUF_SIZE>>,
    outputs: Vec<Port<f32, BUF_SIZE>>,

    config: LofiConfig,
    delay_buffer: Vec<f32>,
    delay_write_pos: usize,
    last_sample: f32,
    sample_hold_counter: usize,
    reduction_factor: usize,
}

impl<const BUF_SIZE: usize> LofiProcessor<BUF_SIZE> {
    /// Creates a new `LofiProcessor` with the given configuration.
    pub fn new(config: LofiConfig) -> Self {
        let buffer_size = match config.system {
            ClassicSystem::Nes => 256,
            ClassicSystem::Commodore64 => 512,
            ClassicSystem::AkaiS900 => 4096,
            ClassicSystem::FairlightCMI => 2048,
            _ => 1024,
        };

        let metadata = Self::build_metadata(&config);
        let id = NodeId(0);
        let state = NodeState::new(44100.0);

        let inputs = vec![Port::input(id, 0, "signal_in")];
        let outputs = vec![Port::output(id, 0, "signal_out")];

        Self {
            state,
            id,
            metadata,
            inputs,
            outputs,
            config,
            delay_buffer: vec![0.0; buffer_size],
            delay_write_pos: 0,
            last_sample: 0.0,
            sample_hold_counter: 0,
            reduction_factor: 1,
        }
    }

    /// Creates a new `LofiProcessor` configured for a specific classic system.
    pub fn for_system(system: ClassicSystem) -> Self {
        Self::new(LofiConfig::for_system(system))
    }

    /// Processes a single audio sample through the lo-fi effect chain.
    pub fn process_sample(&mut self, input: f32) -> f32 {
        let mut sample = input;

        if self.config.enable_sr_reduction {
            let target_sr = self.config.system.get_sample_rate();
            self.reduction_factor =
                dsp::quantization::calculate_reduction_factor(self.state.sample_rate, target_sr);
        }

        if self.config.enable_bitcrush {
            let bit_depth = self.config.system.get_bit_depth();
            sample = dsp::quantization::bitcrush(sample, bit_depth, true);
        }

        if self.config.enable_sr_reduction && self.reduction_factor > 1 {
            sample = dsp::quantization::sample_rate_reduce(
                sample,
                self.reduction_factor,
                &mut self.last_sample,
                &mut self.sample_hold_counter,
            );
        }

        if self.config.enable_noise {
            sample = dsp::noise::system_noise(self.config.system, sample);
        }

        sample = dsp::dac_emulation::for_system(self.config.system, sample);

        if !self.delay_buffer.is_empty() {
            self.delay_buffer[self.delay_write_pos] = sample;
            let read_pos = if self.delay_write_pos >= 256 {
                self.delay_write_pos - 256
            } else {
                self.delay_buffer.len() + self.delay_write_pos - 256
            };
            let delayed = self.delay_buffer[read_pos];
            sample = sample * 0.7 + delayed * 0.3;
            self.delay_write_pos = (self.delay_write_pos + 1) % self.delay_buffer.len();
        }

        let wet = sample * self.config.dry_wet;
        let dry = input * (1.0 - self.config.dry_wet);

        let mut out = wet + dry;
        out -= self.config.dc_offset;
        out *= self.config.output_gain;
        out = out.clamp(-self.config.output_ceiling, self.config.output_ceiling);
        out
    }

    /// Resets the internal delay buffer to silence.
    pub fn clear_delay_buffer(&mut self) {
        self.delay_buffer.fill(0.0);
        self.delay_write_pos = 0;
    }

    /// Returns the total sample count and current time in seconds.
    pub fn stats(&self) -> (u64, f32) {
        (
            self.state.sample_pos,
            self.state.current_time_seconds() as f32,
        )
    }

    fn build_metadata(config: &LofiConfig) -> NodeMetadata {
        let system_name = match config.system {
            ClassicSystem::Nes => "NES Emulator",
            ClassicSystem::Commodore64 => "Commodore 64 SID",
            ClassicSystem::AkaiS900 => "Akai S900 Sampler",
            ClassicSystem::FairlightCMI => "Fairlight CMI",
            ClassicSystem::Custom { .. } => "Custom Lo-Fi",
            _ => "Lo-Fi Processor",
        };

        let description = match config.system {
            ClassicSystem::Nes => "Nintendo Entertainment System sound chip".to_string(),
            ClassicSystem::Commodore64 => "Commodore 64 SID chip".to_string(),
            ClassicSystem::AkaiS900 => "Akai S900 12-bit sampler".to_string(),
            ClassicSystem::FairlightCMI => "Fairlight CMI (first digital sampler)".to_string(),
            ClassicSystem::Custom {
                bit_depth,
                sample_rate,
                ..
            } => format!("Custom {}-bit at {} Hz", bit_depth, sample_rate),
            _ => "vintage digital audio system".to_string(),
        };

        NodeMetadata {
            name: system_name.to_string(),

            type_name: None,
            category: NodeCategory::Processor,
            description,
            author: "Rill Lo-Fi".to_string(),
            version: "0.2.0".to_string(),
            signal_inputs: 1,
            signal_outputs: 1,
            control_inputs: 0,
            control_outputs: 0,
            clock_inputs: 0,
            clock_outputs: 0,
            feedback_ports: 0,
            parameters: vec![
                ParamMetadata::new(
                    "system",
                    ParamType::Choice,
                    ParamValue::Choice("NES".to_string()),
                )
                .with_description("Classic system to emulate")
                .with_choices(vec![
                    ("NES".to_string(), 0.0),
                    ("Commodore64".to_string(), 1.0),
                    ("AkaiS900".to_string(), 2.0),
                    ("FairlightCMI".to_string(), 3.0),
                    ("Custom".to_string(), 4.0),
                ]),
                ParamMetadata::new("bit_depth", ParamType::Int, ParamValue::Int(8))
                    .with_description("Bit depth for quantization")
                    .with_range(1.0, 16.0, 1.0)
                    .with_unit("bits"),
                ParamMetadata::new("dry_wet", ParamType::Float, ParamValue::Float(1.0))
                    .with_description("Dry/wet mix")
                    .with_range(0.0, 1.0, 0.01),
                ParamMetadata::new("output_gain", ParamType::Float, ParamValue::Float(1.0))
                    .with_description("Output gain")
                    .with_range(0.0, 4.0, 0.1),
                ParamMetadata::new("dc_offset", ParamType::Float, ParamValue::Float(0.0))
                    .with_description("DC offset correction (subtracted after gain)")
                    .with_range(-1.0, 1.0, 0.01),
                ParamMetadata::new("output_ceiling", ParamType::Float, ParamValue::Float(1.0))
                    .with_description("Hard clamp ceiling (±value)")
                    .with_range(0.0, 1.0, 0.01),
                ParamMetadata::new("enable_bitcrush", ParamType::Bool, ParamValue::Bool(true))
                    .with_description("Enable bitcrushing"),
                ParamMetadata::new(
                    "enable_sr_reduction",
                    ParamType::Bool,
                    ParamValue::Bool(true),
                )
                .with_description("Enable sample rate reduction"),
                ParamMetadata::new("enable_noise", ParamType::Bool, ParamValue::Bool(true))
                    .with_description("Enable vintage noise"),
            ],
        }
    }
}

impl<const BUF_SIZE: usize> Node<f32, BUF_SIZE> for LofiProcessor<BUF_SIZE> {
    fn metadata(&self) -> NodeMetadata {
        self.metadata.clone()
    }

    fn node_type_id(&self) -> NodeTypeId {
        NodeTypeId::of::<Self>()
    }

    fn init(&mut self, sample_rate: f32) {
        self.state = NodeState::new(sample_rate);
        self.last_sample = 0.0;
        self.sample_hold_counter = 0;
        self.clear_delay_buffer();

        if let ClassicSystem::Custom {
            sample_rate: ref mut field_sr,
            ..
        } = self.config.system
        {
            *field_sr = sample_rate;
        }

        if self.config.enable_sr_reduction {
            let target_sr = self.config.system.get_sample_rate();
            self.reduction_factor =
                dsp::quantization::calculate_reduction_factor(sample_rate, target_sr);
        }
    }

    fn reset(&mut self) {
        self.state.reset();
        self.last_sample = 0.0;
        self.sample_hold_counter = 0;
        self.clear_delay_buffer();
    }

    fn get_parameter(&self, id: &ParameterId) -> Option<ParamValue> {
        match id.as_str() {
            "bit_depth" => Some(ParamValue::Int(self.config.system.get_bit_depth() as i32)),
            "sample_rate" => Some(ParamValue::Float(self.config.system.get_sample_rate())),
            "dry_wet" => Some(ParamValue::Float(self.config.dry_wet)),
            "output_gain" => Some(ParamValue::Float(self.config.output_gain)),
            "dc_offset" => Some(ParamValue::Float(self.config.dc_offset)),
            "output_ceiling" => Some(ParamValue::Float(self.config.output_ceiling)),
            "enable_bitcrush" => Some(ParamValue::Bool(self.config.enable_bitcrush)),
            "enable_sr_reduction" => Some(ParamValue::Bool(self.config.enable_sr_reduction)),
            "enable_noise" => Some(ParamValue::Bool(self.config.enable_noise)),
            "system" => {
                let name = match self.config.system {
                    ClassicSystem::Nes => "NES",
                    ClassicSystem::Commodore64 => "Commodore64",
                    ClassicSystem::AkaiS900 => "AkaiS900",
                    ClassicSystem::FairlightCMI => "FairlightCMI",
                    ClassicSystem::Custom { .. } => "Custom",
                    _ => "Unknown",
                };
                Some(ParamValue::Choice(name.to_string()))
            }
            _ => None,
        }
    }

    fn set_parameter(&mut self, id: &ParameterId, value: ParamValue) -> ProcessResult<()> {
        match id.as_str() {
            "bit_depth" => {
                if let ParamValue::Int(v) = value {
                    if let ClassicSystem::Custom {
                        ref mut bit_depth, ..
                    } = self.config.system
                    {
                        *bit_depth = v as u8;
                        return Ok(());
                    }
                }
                Err(ProcessError::parameter(
                    "Cannot change bit_depth of fixed system",
                ))
            }
            "sample_rate" => {
                if let ParamValue::Float(v) = value {
                    if let ClassicSystem::Custom {
                        ref mut sample_rate,
                        ..
                    } = self.config.system
                    {
                        *sample_rate = v.clamp(8000.0, 192000.0);
                        return Ok(());
                    }
                }
                Err(ProcessError::parameter(
                    "Cannot change sample_rate of fixed system",
                ))
            }
            "dry_wet" => {
                if let ParamValue::Float(v) = value {
                    self.config.dry_wet = v.clamp(0.0, 1.0);
                    return Ok(());
                }
                Err(ProcessError::parameter("dry_wet must be a float"))
            }
            "output_gain" => {
                if let ParamValue::Float(v) = value {
                    self.config.output_gain = v.clamp(0.0, 4.0);
                    return Ok(());
                }
                Err(ProcessError::parameter("output_gain must be a float"))
            }
            "dc_offset" => {
                if let ParamValue::Float(v) = value {
                    self.config.dc_offset = v.clamp(-1.0, 1.0);
                    return Ok(());
                }
                Err(ProcessError::parameter("dc_offset must be a float"))
            }
            "output_ceiling" => {
                if let ParamValue::Float(v) = value {
                    self.config.output_ceiling = v.clamp(0.0, 1.0);
                    return Ok(());
                }
                Err(ProcessError::parameter("output_ceiling must be a float"))
            }
            "enable_bitcrush" => {
                if let ParamValue::Bool(v) = value {
                    self.config.enable_bitcrush = v;
                    return Ok(());
                }
                Err(ProcessError::parameter("enable_bitcrush must be a bool"))
            }
            "enable_sr_reduction" => {
                if let ParamValue::Bool(v) = value {
                    self.config.enable_sr_reduction = v;
                    return Ok(());
                }
                Err(ProcessError::parameter(
                    "enable_sr_reduction must be a bool",
                ))
            }
            "enable_noise" => {
                if let ParamValue::Bool(v) = value {
                    self.config.enable_noise = v;
                    return Ok(());
                }
                Err(ProcessError::parameter("enable_noise must be a bool"))
            }
            _ => Err(ProcessError::parameter(format!(
                "Unknown parameter: {}",
                id
            ))),
        }
    }

    fn id(&self) -> NodeId {
        self.id
    }

    fn set_id(&mut self, id: NodeId) {
        self.id = id;
    }

    fn input_port(&self, index: usize) -> Option<&Port<f32, BUF_SIZE>> {
        self.inputs.get(index)
    }

    fn input_port_mut(&mut self, index: usize) -> Option<&mut Port<f32, BUF_SIZE>> {
        self.inputs.get_mut(index)
    }

    fn output_port(&self, index: usize) -> Option<&Port<f32, BUF_SIZE>> {
        self.outputs.get(index)
    }

    fn output_port_mut(&mut self, index: usize) -> Option<&mut Port<f32, BUF_SIZE>> {
        self.outputs.get_mut(index)
    }

    fn control_port(&self, _index: usize) -> Option<&Port<f32, BUF_SIZE>> {
        None
    }

    fn control_port_mut(&mut self, _index: usize) -> Option<&mut Port<f32, BUF_SIZE>> {
        None
    }

    fn state(&self) -> &NodeState<f32, BUF_SIZE> {
        &self.state
    }

    fn state_mut(&mut self) -> &mut NodeState<f32, BUF_SIZE> {
        &mut self.state
    }

    fn num_signal_inputs(&self) -> usize {
        1
    }

    fn num_signal_outputs(&self) -> usize {
        1
    }
}

impl<const BUF_SIZE: usize> Processor<f32, BUF_SIZE> for LofiProcessor<BUF_SIZE> {
    fn process(
        &mut self,
        _ctx: &RenderContext,
        signal_inputs: &[&[f32; BUF_SIZE]],
        _control_inputs: &[f32],
        _clock_inputs: &[RenderContext],
        _feedback_inputs: &[&[f32; BUF_SIZE]],
    ) -> ProcessResult<()> {
        if signal_inputs.is_empty() {
            return Ok(());
        }

        let input = signal_inputs[0];
        for (i, sample) in input.iter().enumerate() {
            self.outputs[0].buffer.as_mut_array()[i] = self.process_sample(*sample);
        }

        Ok(())
    }

    fn latency(&self) -> usize {
        0
    }
}

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

    fn build_param_id(name: &str) -> ParameterId {
        ParameterId::new(name).unwrap()
    }

    fn approx_eq(a: f32, b: f32, eps: f32) -> bool {
        (a - b).abs() < eps
    }

    #[test]
    fn test_lofi_processor_process_basic() {
        let mut processor = LofiProcessor::<64>::new(LofiConfig::default());

        processor
            .set_parameter(&build_param_id("enable_bitcrush"), ParamValue::Bool(false))
            .unwrap();
        processor
            .set_parameter(
                &build_param_id("enable_sr_reduction"),
                ParamValue::Bool(false),
            )
            .unwrap();
        processor
            .set_parameter(&build_param_id("enable_noise"), ParamValue::Bool(false))
            .unwrap();
        processor
            .set_parameter(&build_param_id("dry_wet"), ParamValue::Float(0.0))
            .unwrap();
        processor
            .set_parameter(&build_param_id("output_gain"), ParamValue::Float(0.8))
            .unwrap();
        processor.init(44100.0);

        let mut input = [0.0f32; 64];
        for (i, slot) in input.iter_mut().enumerate() {
            *slot = (i as f32 / 64.0 * std::f32::consts::TAU).sin() * 0.5;
        }

        let ctx = RenderContext::new(0, 64, 44100.0);
        processor.process(&ctx, &[&input], &[], &[], &[]).unwrap();

        let output = *processor.outputs[0].buffer.as_array();
        for i in 0..64 {
            let expected = input[i] * 0.8;
            assert!(
                approx_eq(output[i], expected, 0.001),
                "Mismatch at {}: got {}, expected {}",
                i,
                output[i],
                expected
            );
        }

        let (_samples, _time) = processor.stats();
    }

    #[test]
    fn test_lofi_processor_with_bitcrush() {
        let mut processor = LofiProcessor::<64>::new(LofiConfig::default());

        processor
            .set_parameter(
                &build_param_id("enable_sr_reduction"),
                ParamValue::Bool(false),
            )
            .unwrap();
        processor
            .set_parameter(&build_param_id("enable_noise"), ParamValue::Bool(false))
            .unwrap();
        processor
            .set_parameter(&build_param_id("enable_bitcrush"), ParamValue::Bool(true))
            .unwrap();
        processor
            .set_parameter(&build_param_id("dry_wet"), ParamValue::Float(0.0))
            .unwrap();
        processor.init(44100.0);

        let input = [0.5f32; 64];
        let ctx = RenderContext::new(0, 64, 44100.0);
        processor.process(&ctx, &[&input], &[], &[], &[]).unwrap();

        let output = *processor.outputs[0].buffer.as_array();
        for &sample in output.iter() {
            assert!(
                (0.49..=0.51).contains(&sample),
                "Bitcrush should not radically change value 0.5"
            );
        }
    }

    #[test]
    fn test_lofi_processor_dry_wet() {
        let mut processor = LofiProcessor::<64>::new(LofiConfig::default());

        processor
            .set_parameter(&build_param_id("enable_bitcrush"), ParamValue::Bool(true))
            .unwrap();
        processor
            .set_parameter(
                &build_param_id("enable_sr_reduction"),
                ParamValue::Bool(false),
            )
            .unwrap();
        processor
            .set_parameter(&build_param_id("enable_noise"), ParamValue::Bool(false))
            .unwrap();
        processor
            .set_parameter(&build_param_id("dry_wet"), ParamValue::Float(0.0))
            .unwrap();
        processor.init(44100.0);

        let input_val = 0.75f32;
        let input = [input_val; 64];
        let ctx = RenderContext::new(0, 64, 44100.0);
        processor.process(&ctx, &[&input], &[], &[], &[]).unwrap();

        let output = *processor.outputs[0].buffer.as_array();
        assert!(
            approx_eq(output[0], input_val, 0.001),
            "With dry_wet=0, output should equal input"
        );
    }

    #[test]
    fn test_lofi_processor_clear_delay() {
        let mut processor = LofiProcessor::<64>::new(LofiConfig::default());
        processor
            .set_parameter(&build_param_id("enable_bitcrush"), ParamValue::Bool(false))
            .unwrap();
        processor
            .set_parameter(
                &build_param_id("enable_sr_reduction"),
                ParamValue::Bool(false),
            )
            .unwrap();
        processor
            .set_parameter(&build_param_id("enable_noise"), ParamValue::Bool(false))
            .unwrap();
        processor.clear_delay_buffer();
        let input = [0.0f32; 64];
        let ctx = RenderContext::new(0, 64, 44100.0);
        processor.process(&ctx, &[&input], &[], &[], &[]).unwrap();
        let output = *processor.outputs[0].buffer.as_array();
        for &sample in output.iter() {
            assert!(approx_eq(sample, 0.0, 0.001));
        }
    }

    #[test]
    fn test_lofi_processor_empty_input() {
        let mut processor = LofiProcessor::<64>::new(LofiConfig::default());
        let ctx = RenderContext::new(0, 64, 44100.0);
        let result = processor.process(&ctx, &[], &[], &[], &[]);
        assert!(result.is_ok());
    }

    #[test]
    fn test_lofi_processor_parameter_validation() {
        let mut processor = LofiProcessor::<64>::new(LofiConfig::default());

        let result =
            processor.set_parameter(&build_param_id("output_gain"), ParamValue::Float(-1.0));
        assert!(result.is_ok());
        let val = processor
            .get_parameter(&build_param_id("output_gain"))
            .unwrap();
        assert_eq!(val.as_f32(), Some(0.0));

        let result =
            processor.set_parameter(&build_param_id("output_gain"), ParamValue::Float(10.0));
        assert!(result.is_ok());
        let val = processor
            .get_parameter(&build_param_id("output_gain"))
            .unwrap();
        assert_eq!(val.as_f32(), Some(4.0));

        let result =
            processor.set_parameter(&build_param_id("unknown_param"), ParamValue::Float(0.5));
        assert!(result.is_err());
    }

    #[test]
    fn test_lofi_processor_metadata() {
        let processor = LofiProcessor::<64>::new(LofiConfig::default());
        let meta = processor.metadata();
        assert_eq!(meta.signal_inputs, 1);
        assert_eq!(meta.signal_outputs, 1);
        assert_eq!(meta.category, NodeCategory::Processor);
        assert!(!meta.name.is_empty());
    }

    #[test]
    fn test_lofi_processor_for_system() {
        let processor = LofiProcessor::<64>::for_system(ClassicSystem::Nes);
        let meta = processor.metadata();
        assert!(!meta.name.is_empty());
        assert_eq!(meta.signal_inputs, 1);
        assert_eq!(meta.signal_outputs, 1);
        let default_gain = processor
            .get_parameter(&build_param_id("output_gain"))
            .unwrap();
        assert_eq!(default_gain.as_f32(), Some(1.0));
    }

    #[test]
    fn test_lofi_processor_init_reset() {
        let mut processor = LofiProcessor::<64>::new(LofiConfig::default());
        processor.init(48000.0);
        assert!(approx_eq(processor.state.sample_rate, 48000.0, 0.001));

        let input = [0.5f32; 64];
        let ctx = RenderContext::new(0, 64, 44100.0);
        processor.process(&ctx, &[&input], &[], &[], &[]).unwrap();

        processor.reset();
        assert_eq!(processor.state.sample_pos, 0);
        assert_eq!(processor.state.blocks_processed, 0);
    }

    #[test]
    fn test_dc_offset_removal() {
        let config = LofiConfig {
            enable_bitcrush: false,
            enable_sr_reduction: false,
            enable_noise: false,
            dc_offset: 0.5,
            dry_wet: 1.0,
            output_gain: 1.0,
            ..Default::default()
        };
        let mut processor = LofiProcessor::<1>::new(config);

        // Feed constant 1.0 — with offset 0.5 applied, output should be reduced by ~0.5
        // (exact value depends on DAC emulation, which always runs)
        let s = processor.process_sample(1.0);
        // Without offset: ~0.77 (dac * delay * gain). With offset 0.5: ~0.27
        assert!(
            s < 0.5,
            "offset should reduce output below 0.5, got {:.3}",
            s
        );
        assert!(
            s > 0.0,
            "positive input should stay positive after offset, got {:.3}",
            s
        );
    }

    #[test]
    fn test_output_ceiling_clamp() {
        let config = LofiConfig {
            enable_bitcrush: false,
            enable_sr_reduction: false,
            enable_noise: false,
            output_ceiling: 0.8,
            dry_wet: 1.0,
            output_gain: 2.0, // 1.0 * 2.0 = 2.0 → clamp to 0.8
            ..Default::default()
        };
        let mut processor = LofiProcessor::<1>::new(config);

        let sample = processor.process_sample(1.0);
        assert!(sample <= 0.8, "should be ≤ 0.8, got {:.3}", sample);
        assert!(sample >= -0.8, "should be ≥ -0.8, got {:.3}", sample);
    }

    #[test]
    fn test_dc_offset_and_ceiling_combined() {
        let config = LofiConfig {
            enable_bitcrush: false,
            enable_sr_reduction: false,
            enable_noise: false,
            dc_offset: 0.5,
            output_gain: 2.0,
            output_ceiling: 0.5,
            dry_wet: 1.0,
            ..Default::default()
        };
        let mut processor = LofiProcessor::<1>::new(config);

        // Input 1.0 → max gain 2.0 + offset 0.5 should exceed ceiling 0.5 → clamped
        let sample = processor.process_sample(1.0);
        assert!(
            sample.abs() <= 0.5,
            "ceiling should clamp to ±0.5, got {:.3}",
            sample
        );
    }
}