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
extern crate ladspa;
extern crate rustfft;

use ladspa::{ Plugin, PluginDescriptor, Port, PortConnection, Data };
use rustfft::{ FFT, FFTplanner };
use rustfft::num_complex::Complex;
use rustfft::num_traits::Zero;
use std::cmp;
use std::default::Default;
use std::f32::consts::PI;
use std::sync::Arc;

const AUTO_NOISE_MARGIN_DB: f32 = 10.0;

// macro_rules! dprint {
//    ($($arg:tt)*) => (if cfg!(debug_assertions) { print!($($arg)*); })
// }
macro_rules! dprintln {
   ($($arg:tt)*) => (if cfg!(debug_assertions) { println!($($arg)*); })
}

fn hanning (x: f32) -> f32 {
   debug_assert!(x >= 0.0, "x too small: {}", x);
   debug_assert!(x <= 1.0, "x too large: {}", x);
   (1.0 - f32::cos (x * 2.0 * PI)) / 2.0
}

/// Noise coring plugin data
#[derive (Default)]
struct NoiseCoring {
   input_buf: Vec<Data>,
   output_buf: Vec<Data>,
   input_fill: usize,

   filter_length: usize,
   strength: f32,
   noise_gain: f32,
   shape_db_per_dec: f32,
   window_size: usize,
   is_auto_mode: bool,
   auto_reactivity: f32,

   is_started: bool,

   filter_coefs: Vec<f32>,
   fft_input: Vec<Complex<f32>>,
   fft_output: Vec<Complex<f32>>,

   short_fft: Option<Arc<FFT<f32>>>,
   short_ifft: Option<Arc<FFT<f32>>>,
   full_fft: Option<Arc<FFT<f32>>>,
   full_ifft: Option<Arc<FFT<f32>>>,
}

/// Noise coring methods
impl NoiseCoring {
   /// Analyze `self.fft_output` and update the filter parameters.
   ///
   /// This function estimates the noise level and shape from the FFT
   /// coefficients and updates `self.strength` and
   /// `self.shape_db_per_dec` accordingly.
   fn estimate_noise_parameters (&mut self)
   {
      // This macro takes a slice of the spectrum and converts it to
      // an iterator of pairs `(log (frequency), power_dB)`
      macro_rules! to_spectrum_iter (
         ($e:expr) => {
            $e.iter()
               .enumerate()
               .skip (1)
               .map (|(i, x)|
                     ((i as f32).log10(),
                      10.0*f32::log10 (x.norm_sqr()
                                       / (self.window_size/4) as f32)))
         };
      );

      // Search for a local minimum at the beginning of the spectrum.
      // In order to avoid outliers, we take the median of the first
      // three minima (ignoring frequency 0).
      let (xb, yb) = {
         let mut iter
            = to_spectrum_iter!(self.fft_output[1..])
            .zip (to_spectrum_iter!(self.fft_output[2..])
                  .zip (to_spectrum_iter!(self.fft_output[3..])))
            .filter_map (|((_, x1), ((i2, x2), (_, x3)))|
                         if (x2 <= x1) && (x2 <= x3) { Some ((i2, x2)) }
                         else { None });
         let (x1, y1) = iter.next().unwrap_or ((0.0, 0.0));
         let (x2, y2) = iter.next().unwrap_or ((0.0, 0.0));
         let (x3, y3) = iter.next().unwrap_or ((0.0, 0.0));
         if ((y1 <= y2) && (y2 <= y3))
            || ((y3 <= y2) && (y2 <= y1))       { (x2, y2) }
         else if ((y2 <= y1) && (y1 <= y3))
            || ((y3 <= y1) && (y1 <= y2))       { (x1, y1) }
         else                                   { (x3, y3) }
      };
      // dprintln!("First local min: {} {}", xb, yb);

      // Search for a local minimum at the end of the spectrum. In
      // order to avoid outliers, we take the median of the last three
      // minima (ignoring the Nyquistfrequency Fs/2).
      let (xe, ye) = {
         let mut iter
            = to_spectrum_iter!(self.fft_output[..self.window_size/2]).rev()
            .zip (to_spectrum_iter!(self.fft_output[..self.window_size/2-1]).rev()
                  .zip (to_spectrum_iter!(self.fft_output[..self.window_size/2-2]).rev()))
            .filter_map (|((_, x1), ((i2, x2), (_, x3)))|
                         if (x2 <= x1) && (x2 <= x3) { Some ((i2, x2)) }
                         else { None });
         let (x1, y1) = iter.next().unwrap_or ((0.0, 0.0));
         let (x2, y2) = iter.next().unwrap_or ((0.0, 0.0));
         let (x3, y3) = iter.next().unwrap_or ((0.0, 0.0));
         if ((y1 <= y2) && (y2 <= y3))
            || ((y3 <= y2) && (y2 <= y1))       { (x2, y2) }
         else if ((y2 <= y1) && (y1 <= y3))
            || ((y3 <= y1) && (y1 <= y2))       { (x1, y1) }
         else                                   { (x3, y3) }
      };
      // dprintln!("Last local min: {} {}", xe, ye);

      // Compute a first approximation of the noise parameters from
      // the local minima.
      let (a, b)
         = if xe > xb {
            let a = (ye - yb) / (xe - xb);
            let b = yb - a * xe;
            (a, b)
         } else {
            (0.0, 0.0)
         };
      // dprintln!("Noise parameters in first approximation: level {} dB, shape {} dB/decade",
      //           b + ((self.window_size as f32).log10() - 2.0) * a, a);

      // Compute a refined approximation of the noise parameters
      // through linear regression in all bands that are lower than
      // the first approximation plus a constant arbitrary threshold
      // (10dB).
      let (sxy, sx2, sx, sy, n)
         = to_spectrum_iter!(self.fft_output[..self.window_size/2])
         .filter (|&(x, y)| y <= a*x + b + AUTO_NOISE_MARGIN_DB)
         .fold (
            (0.0, 0.0, 0.0, 0.0, 0),
            |(sxy, sx2, sx, sy, n), (i, x)|
            (sxy+i*x, sx2+i*i, sx+i, sy+x, n+1));
      if n == 0 {
         dprintln!("WARNING: Could not estimate noise shape!");
         if !self.is_started {
            // This should only happen when the input contains only
            // zeroes so it doesn't really matter what the strength is
            // provided that it is >0 (to avoid NaNs in the filter
            // output).
            self.strength = 1.0;
         }
         return;
      }
      let (a, b)
         = if sxy.is_infinite() || sy.is_infinite() {
            // Assume very low level of white noise
            (0.0, -150.0)
         } else {
            let n = n as f32;
            let det = sx2*n - sx*sx;
            let a = (n*sxy - sx*sy) / det;
            let b = (-sx*sxy + sx2*sy) / det;
            (a, b)
         };
      // dprint!("Linearized spectrum:");
      // for i in 1..self.window_size/2 {
      //    dprint!(" {},", a*(i as f32).log10()+b);
      // }
      // dprintln!();

      let level_db    = b + ((self.window_size as f32).log10() - 2.0) * a;
      let noise_level = 10.0f32.powf (level_db/20.0);
      let strength    = -noise_level / f32::ln (1.0 - self.noise_gain);

      if self.is_started {
         let r = self.auto_reactivity;
         self.strength         = strength * r + self.strength * (1.0 - r);
         self.shape_db_per_dec = -a * r + self.shape_db_per_dec * (1.0 - r);
      } else {
         self.strength = strength;
         self.shape_db_per_dec = -a;
         self.is_started = true;
      }
      dprintln!("Noise: level {}, shape {} -> Filter: strength {}, shape {}",
                level_db, a, 20.0*f32::log10 (self.strength), self.shape_db_per_dec);
   }

   /// Analyze `self.input_buf` and compute the filter coefficients.
   ///
   /// This function uses `self.fft_input` and `self.fft_output` as
   /// scratch space and puts the computed coefficients in
   /// `self.filter_coefs`.
   fn make_filter (&mut self) {
      debug_assert!(self.input_buf.len() == self.window_size);
      debug_assert!(self.fft_input.len() == 2*self.window_size);
      debug_assert!(self.fft_output.len() == 2*self.window_size);

      // Compute a windowed FFT of the input
      for (i, (cplx, &real)) in
         self.fft_input.iter_mut()
         .zip (self.input_buf.iter())
         .enumerate()
         .take (self.window_size)
      {
         *cplx = (real * hanning (i as f32 / self.window_size as f32)).into();
      }
      self.short_fft.as_ref().expect ("FFT planner not initialized!").process (
         &mut self.fft_input[..self.window_size],
         &mut self.fft_output[..self.window_size]);

      // dprint!("Spectrum:");
      // for &x in self.fft_output[..self.window_size/2+1].iter() {
      //    dprint!(" {},",
      //            10.0*f32::log10 (x.norm_sqr()
      //                             / (self.window_size/4) as f32));
      // }
      // dprintln!();

      if self.is_auto_mode { self.estimate_noise_parameters(); }

      // Compute an ideal frequency response that keeps frequencies
      // where the signal is stronger than the noise and cuts
      // frequencies where the noise is stronger.
      for (i, x)
         in self.fft_output.iter_mut()
         .take (self.window_size/2+1)
         .enumerate()
      {
         // Note that there is no need to process the second half
         // of the data since it is symmetrical
         *x = (
            // Noise modelling. If `shape_db_per_dec` is 0 (white
            // noise), then the noise is constant. Otherwise noise is
            // infinite at frequency zero, which means that the
            // response must be zero, and noise is
            // $l(f_0)+shape*log(f/f_0)$ for other frequencies.
            if (i == 0) && (self.shape_db_per_dec > 0.0) { 0.0 }
            else {
               let strength = if i == 0 {
                  self.strength
               } else {
                  self.strength
                     * (self.window_size as f32 / (100*i) as f32)
                     .powf (self.shape_db_per_dec / 20.0)
                  // The strength is computed from the reference
                  // `strength` ($s(f_0)$) by:
                  //
                  // $s(f)=s(f_0)\times\frac{l(f)}{l(f_0)}$
                  //
                  // which gives:
                  //
                  // $s(f)=s(f_0)\times\left(\frac{f}{f_0}\right)^\frac{shape_db_per_dec}{20}$
                  //
                  // Additionally, $f_0$ is arbitrarily defined as
                  // `sampling_frequency/100` and $f$ is
                  // `i/window_size*sampling_frequency`
               };
               (1.0 - f32::exp (
                  -x.norm()
                     / strength
                     / (self.window_size/4) as f32))
               // The division by `window_size/4` normalizes analyzed
               // frequencies to the same level as the plot spectrum
               // in Audacity v2.2.1
            })
            .into();
      }
      // dprint!("Ideal response:");
      // for &x in self.fft_output[..self.window_size/2+1].iter() {
      //    dprint!(" {},",
      //            10.0*f32::log10 (x.norm_sqr()));
      // }
      // dprintln!();

      // Increase the width of the ideal frequency response so that
      // all frequencies close to signal frequencies are kept. This
      // allows signal frequencies to be preserved during the
      // windowing of the impulse response. It will leave some
      // noise at frequencies close to the signal but that's not a
      // problem because the signal will mask the remaining noise
      // to the human ear.
      {
         let dilation_radius = self.window_size / self.filter_length;
         let (left, right) = self.fft_input[..self.window_size].split_at_mut (self.window_size/2);
         left[0]
            = self.fft_output[1 .. dilation_radius+1]
            .iter()
            .map (|c| c.re)
            .fold (self.fft_output[0].re,
                   |max, x| if x > max { x } else { max })
            .into();
         for (i, (left, right)) in
            left.iter_mut().skip (1)
            .zip (right.iter_mut().rev())
            .enumerate()
         {
            let start = (i+1).saturating_sub (dilation_radius);
            let end   = cmp::min (i+dilation_radius+1, self.window_size/2);
            *left
               = self.fft_output[start+1 .. end+1]
               .iter()
               .map (|c| c.re)
               .fold (self.fft_output[start].re,
                      |max, x| if x > max { x } else { max })
               .into();
            *right = *left;
         }
         right[0]
            = self.fft_output[
               (self.window_size/2).saturating_sub (dilation_radius)
                  .. self.window_size/2]
            .iter()
            .map (|c| c.re)
            .fold (
               self.fft_output[(self.window_size/2-1).saturating_sub (dilation_radius)].re,
               |max, x| if x > max { x } else { max })
            .into();
      }

      // Window the impulse response to avoid issues with the Gibbs
      // phenomenon (the ideal frequency response has infinite
      // impulse response which causes ringing artefacts in the
      // filter output)
      self.short_ifft.as_ref().expect ("FFT planner not initialized!").process (
         &mut self.fft_input[..self.window_size],
         &mut self.fft_output[..self.window_size]);
      {
         let (left, right) = self.fft_output.split_at_mut (self.window_size);
         left[0] = (left[0].re / self.window_size as f32).into();
         for (i, (left, right)) in
            left[1..self.filter_length/2].iter_mut()
            .zip (right.iter_mut().rev())
            .enumerate()
         {
            // debug_assert!((left.im.abs() < 2e-2*left.re.abs())
            //               || (left.norm_sqr() < 1e-4),
            //               "{} is not almost real", *left);
            *left  = (left.re
                      / self.window_size as f32 // Compensate for RustFFT lack of normalization
                      * hanning (0.5 + (i+1) as f32 / self.filter_length as f32))
               .into();
            *right = *left;
         }
      }
      let full_size = self.fft_output.len();
      for c in
         self.fft_output[self.filter_length/2
                         .. full_size-self.filter_length/2+1]
         .iter_mut()
      { *c = 0.0.into(); }

      self.full_fft.as_ref().expect ("FFT planner not initialized!").process (
         &mut self.fft_output, &mut self.fft_input);
      for (x, c) in self.filter_coefs.iter_mut().zip (self.fft_input.iter()) {
         // debug_assert!((c.im.abs() < 2e-2*c.re.abs())
         //               || (c.norm_sqr() < 1e-4),
         //               "{} is not almost real", c);
         *x = c.re;
      }
      // dprint!("Windowed frequency response:");
      // for &x in self.filter_coefs[..self.window_size+1].iter() {
      //    dprint!(" {},", 20.0*f32::log10 (x));
      // }
      // dprintln!();
   }

   /// Process `self.input_buf` and applies the filter.
   ///
   /// The filter coefficients in frequency space are taken from
   /// `self.filter_coefs`. This function uses `self.fft_input` and
   /// `self.fft_output` as scratch space and **adds** the processed
   /// audio to `self.output_buf`.
   fn apply_filter (&mut self) {
      // Pad the input with zeroes and compute the forward FFT
      for (cplx, &real) in
         self.fft_input.iter_mut()
         .zip (self.input_buf.iter())
         .take (self.window_size)
      { *cplx = real.into(); }
      for cplx in self.fft_input[self.window_size..].iter_mut() {
         *cplx = 0.0.into();
      }

      self.full_fft.as_ref().expect ("FFT planner not initialized!").process (
         &mut self.fft_input, &mut self.fft_output);
      // Apply the filter in frequency space
      for (x, &h)
         in self.fft_output.iter_mut()
            .zip (self.filter_coefs.iter())
      { *x *= h; }
      // Add the filtered data to the output buffer
      self.full_ifft.as_ref().expect ("FFT planner not initialized!").process (
         &mut self.fft_output, &mut self.fft_input);
      for (i, (out, &flt)) in
         self.output_buf.iter_mut()
         .zip (self.fft_input.iter())
         .take (self.window_size)
         .enumerate()
      {
         // debug_assert!((flt.im.abs() < 2e-2*flt.re.abs())
         //               || (flt.norm_sqr() < 1e-4),
         //               "{} is not almost real", flt);
         *out += flt.re / (2*self.window_size) as f32
            * hanning (i as f32 / self.window_size as f32);
         // Note: the division by `2*window_size` is here to
         // compensate for the lack of normalization in RustFFT.
      }
   }
}

/// Instanciate a new noise coring filter
fn new_noisecoring (_: &PluginDescriptor, _: u64) -> Box<Plugin + Send>
{
   Box::new (NoiseCoring::default())
}

/// LADSPA plugin interface
impl Plugin for NoiseCoring
{
   /// Run the noise coring filter on an audio buffer.
   ///
   /// * `sample_count` - Buffer size.
   /// * `ports`        - LADSPA port connections.
   fn run<'a> (&mut self,
               sample_count: usize,
               ports: &[&'a PortConnection<'a>])
   {
      let input              = ports[0].unwrap_audio();
      let mut output         = ports[1].unwrap_audio_mut();
      let amount_db          = *ports[2].unwrap_control();
      let level_db           = *ports[3].unwrap_control();
      let shape_db_per_dec   = *ports[4].unwrap_control();
      let filter_length      = (*ports[5].unwrap_control() as usize).max (128);
      let is_residual_output = *ports[6].unwrap_control() > 0.5;
      self.is_auto_mode      = *ports[7].unwrap_control() > 0.5;
      self.auto_reactivity   = *ports[8].unwrap_control();
      let is_fast_mode       = *ports[9].unwrap_control() > 0.5;
      let mut latency        = ports[10].unwrap_control_mut();

      dprintln!("NOISECORING: sample_count = {}", sample_count);

      let window_size   = filter_length.next_power_of_two()*2;

      self.noise_gain = 10.0f32.powf (-amount_db / 20.0);
      if !self.is_auto_mode {
         self.strength = {
            let noise_level = 10.0f32.powf (level_db/20.0);
            -noise_level / f32::ln (1.0 - self.noise_gain)
         };
         self.shape_db_per_dec = shape_db_per_dec;
      }

      /* First time we are called (or if the buffer size changes) */
      if self.window_size != window_size {
         // Update parameters
         self.filter_length = filter_length;
         self.window_size   = window_size;

         // Allocate work buffers
         self.input_buf    = vec![0.0; self.window_size];
         self.output_buf   = vec![0.0; self.window_size];
         self.filter_coefs = vec![0.0; 2*self.window_size];
         self.fft_input    = vec![Complex::zero(); 2*self.window_size];
         self.fft_output   = vec![Complex::zero(); 2*self.window_size];

         // Plan the FFT
         self.short_fft = Some (FFTplanner::new (false).plan_fft (self.window_size));
         self.short_ifft = Some (FFTplanner::new (true).plan_fft (self.window_size));
         self.full_fft = Some (FFTplanner::new (false).plan_fft (2*self.window_size));
         self.full_ifft = Some (FFTplanner::new (true).plan_fft (2*self.window_size));

         // Reset
         self.activate();

         /* TODO: benchmark, is it faster to recompute the window each
          * time we use it or to pre-compute it once and for all? */

      }
      /* TODO: handle the case where sample_count < window_size */

      **latency = self.window_size as f32;

      let mut start = 0;

      let overlap = if is_fast_mode { window_size/2 } else { 3*window_size/4 };
      let offset  = window_size - overlap;

      if self.input_fill < overlap {
         // We only get here at the beginning because once we have
         // really started, we always keep `overlap` samples worth of
         // data in the input buffer.
         let to_read = cmp::min (overlap - self.input_fill,
                                 input.len());
         // dprintln!("I/O {} samples @{}", to_read, start);
         self.input_buf[self.input_fill .. self.input_fill + to_read]
            .copy_from_slice (&input[..to_read]);

         // It doesn't matter exactly which samples we send: at this
         // point they are all zeroes
         output[..to_read].copy_from_slice (&self.output_buf[..to_read]);

         self.input_fill += to_read;
         start += to_read;

         if self.input_fill == overlap {
            // The first `offset` samples will be smoothly mixed with
            // the unprocessed signal (for subsequent windows, the
            // overlap of each window will be smoothly mixed with the
            // overlap of the previous windows).
            for (i, (out, &inp)) in
               self.output_buf.iter_mut()
               .skip (offset)
               .zip (self.input_buf.iter())
               .enumerate()
            {
               *out
                  = inp
                  * ((window_size / (2*offset)) as f32
                     - (0 .. 1 + i/offset)
                     .map (|k| hanning ((k*offset + i%offset) as f32
                                        / window_size as f32))
                     .sum::<f32>());
               if is_residual_output {
                  *out -= inp;
               }
            }
         }
      }

      while start + self.window_size <= input.len() + self.input_fill {
         // Store the next input samples. Note that LADSPA allows
         // the input and output buffers to point to the same
         // location, so we risk overwriting `input` when we write
         // to `output`.
         let to_read = self.window_size - self.input_fill;
         // dprintln!("I/O {} samples @{}", to_read, start);
         self.input_buf[self.input_fill..].copy_from_slice (
            &input[start .. start + to_read]);

         // Send the corresponding output samples and shift the output
         // data to make room for processing.
         output[start .. start + to_read].copy_from_slice (
            &self.output_buf[self.input_fill - overlap .. offset]);
         for i in 0 .. overlap {
            self.output_buf[i] = self.output_buf[i + offset];
         }
         if is_residual_output {
            for (x, &y)
               in self.output_buf[overlap..].iter_mut()
               .zip (self.input_buf[overlap..].iter())
            { *x = -y; }
         } else {
            for x in self.output_buf[overlap..].iter_mut() { *x = 0.0; }
         }

         self.input_fill = overlap;
         start += to_read;

         // Process samples
         self.make_filter();
         self.apply_filter();

         // Shift the input data to make room for the next samples.
         for i in 0 .. overlap {
            self.input_buf[i] = self.input_buf[i + offset];
         }
      }

      // Store the remaining input samples and send the corresponding
      // output samples. We will process them the next time we are
      // called.
      let to_read = input.len() - start;
      // dprintln!("I/O {} samples @{}", to_read, start);
      if to_read > 0 {
         debug_assert!(self.input_fill == overlap);
         self.input_buf[self.input_fill .. self.input_fill + to_read]
            .copy_from_slice (&input[start..]);
         output[start..].copy_from_slice (&self.output_buf[.. to_read]);
         self.input_fill += to_read;
      }

      // Compensate for the number of overlapped samples
      if !is_fast_mode {
         for o in output.iter_mut() {
            *o /= (window_size / (2*offset)) as f32;
         }
      }
   }

   /// Reset a noise coring filter instance
   fn activate (&mut self)
   {
      self.input_fill = 0;
      self.is_started = false;
   }
}

/// LADSPA plugin interface
#[no_mangle]
pub extern fn get_ladspa_descriptor (index: u64) -> Option<PluginDescriptor>
{
   match index {
      0 => {
         Some (PluginDescriptor {
            unique_id: 5461,
            label: "noise_coring",
            properties: ladspa::PROP_NONE,
            name: "Noise Coring",
            maker: "Jérôme M. Berger",
            copyright: "(c) 2011-2018 Jérôme M. Berger - released under the terms of the LGPLv2.1",
            ports: vec![Port {
               name: "Audio In",
               desc: ladspa::PortDescriptor::AudioInput,
               .. Default::default()
            }, Port {
               name: "Audio Out",
               desc: ladspa::PortDescriptor::AudioOutput,
               .. Default::default()
            }, Port {
               name: "Reduction amount (dB)",
               desc: ladspa::PortDescriptor::ControlInput,
               default: Some (ladspa::DefaultValue::Low),
               lower_bound: Some (0.0),
               upper_bound: Some (48.0),
               .. Default::default()
            }, Port {
               name: "Noise level (dB)",
               desc: ladspa::PortDescriptor::ControlInput,
               default: Some (ladspa::DefaultValue::Low),
               lower_bound: Some (-48.0),
               upper_bound: Some (0.0),
               .. Default::default()
            }, Port {
               name: "Noise shape (dB/decade)",
               desc: ladspa::PortDescriptor::ControlInput,
               default: Some (ladspa::DefaultValue::Low),
               lower_bound: Some (-10.0),
               upper_bound: Some (70.0),
               .. Default::default()
            }, Port {
               name: "Filter length",
               desc: ladspa::PortDescriptor::ControlInput,
               hint: Some (ladspa::HINT_INTEGER),
               default: Some (ladspa::DefaultValue::Low),
               lower_bound: Some (0.0),
               upper_bound: Some (16384.0),
            }, Port {
               name: "Residual output",
               desc: ladspa::PortDescriptor::ControlInput,
               hint: Some (ladspa::HINT_TOGGLED),
               default: Some (ladspa::DefaultValue::Value0),
               .. Default::default()
            }, Port {
               name: "Automatic noise model",
               desc: ladspa::PortDescriptor::ControlInput,
               hint: Some (ladspa::HINT_TOGGLED),
               default: Some (ladspa::DefaultValue::Value1),
               .. Default::default()
            }, Port {
               name: "Automatic reactivity",
               desc: ladspa::PortDescriptor::ControlInput,
               default: Some (ladspa::DefaultValue::Low),
               lower_bound: Some (0.0),
               upper_bound: Some (1.0),
               .. Default::default()
            }, Port {
               name: "Fast mode",
               desc: ladspa::PortDescriptor::ControlInput,
               hint: Some (ladspa::HINT_TOGGLED),
               default: Some (ladspa::DefaultValue::Value0),
               .. Default::default()
            }, Port {
               name: "latency",
               desc: ladspa::PortDescriptor::ControlOutput,
               hint: Some (ladspa::HINT_INTEGER),
               .. Default::default()
            },
            ],
            new: new_noisecoring,
         })
      },
      _ => None
   }
}