// Persistent filter and overlap state, bounded slots and explicit EOF flush.
import aner.audio
import aner.signal

let source = audio.synthetic(frames: 4096, rate: 16000, frequency: 1000.0,
    block_frames: 317, queue_blocks: 4)
let block = audio.block_slot(memory_mb: 1)
let filtered = audio.block_slot(memory_mb: 1)
let lowpass = signal.filter(rate: 16000, channels: 1, kind: "lowpass", frequency: 3000.0)
let plan = signal.stft_plan(rate: 16000, n_fft: 512, hop: 128, scaling: "power", pad_end: true)
let stream = signal.processor(plan, max_frames: 8)
let output = signal.spectrogram_slot()
var frame_count = 0
var status = audio.read_into(source, block)
while status == "ready" || status == "timeout" {
    if status == "ready" {
        signal.process_into(lowpass, block, filtered)
        signal.push_into(stream, filtered, output)
        frame_count = frame_count + signal.frames(output)
        // Consume these native values here. The next push replaces output.
        // Avoid retaining a new Tensor, Chart or frozen clip on every block.
    }
    status = audio.read_into(source, block)
}
audio.close(source)
if status == "end" {
    signal.flush_into(stream, output)
    frame_count = frame_count + signal.frames(output)
    // ceil(4096 / 128) = 32 supported starts, including zero-padded EOF windows.
    print(frame_count)
    print(signal.valid_samples(output, signal.frames(output) - 1))
} else {
    print(status)
    print(audio.error(source))
}
