rfft static method

Complex32List rfft(
  1. Float32List input, {
  2. int? n,
})

Computes the real-to-complex FFT of a real-valued input signal.

If n is omitted, the transform length defaults to input.length. When n is larger than the input length, the input is zero-padded. When n is smaller, the input is truncated to the first n samples.

Returns the non-redundant positive-frequency spectrum with n ~/ 2 + 1 complex bins.

Implementation

static Complex32List rfft(Float32List input, {int? n}) {
  n = n ?? input.length;
  final bins = yl_rfft_bins(n);

  final plan = yl_fft_plan_r2c_create(n);
  if (plan == ffi.nullptr) {
    throw StateError('yl_fft_plan_r2c_create($n) returned nullptr');
  }

  ffi.Pointer<ffi.Float> inPtr = ffi.nullptr;
  ffi.Pointer<ffi.Float> realOutPtr = ffi.nullptr;
  ffi.Pointer<ffi.Float> imagOutPtr = ffi.nullptr;
  try {
    inPtr = calloc<ffi.Float>(n);
    realOutPtr = calloc<ffi.Float>(bins);
    imagOutPtr = calloc<ffi.Float>(bins);

    final copyLen = math.min(input.length, n);
    inPtr.asTypedList(n).setRange(0, copyLen, input);

    yl_fft_plan_execute_r2c(plan, inPtr, realOutPtr, imagOutPtr);

    return Complex32List.fromRealImagPtr(realOutPtr, imagOutPtr, bins);
  } finally {
    if (inPtr != ffi.nullptr) calloc.free(inPtr);
    if (realOutPtr != ffi.nullptr) calloc.free(realOutPtr);
    if (imagOutPtr != ffi.nullptr) calloc.free(imagOutPtr);
    yl_fft_plan_destroy(plan);
  }
}