// fir_transposed.sv // Transposed-form FIR filter, signed fixed point, one sample per clock at most. // // y[n] = sum_{k=0}^{NTAPS-1} h[k] * x[n-k] // // x: Q1.15 (DW = 16), h: Q1.15 (CW = 16), y: Q1.15. // Bit growth: each product has DW + CW = 32 bits (Q2.30). The sum of NTAPS // products needs at most $clog2(NTAPS) more bits, so the accumulator chain is // AW = DW + CW + $clog2(NTAPS) bits and can never overflow. // The output is rounded (add 2^14, arithmetic shift right by 15) and saturated // to 16 bits once, at the end. // // Pipeline (each maps onto the registers of a DSP slice): // 1. x_r input register, broadcast to every multiplier // 2. m[k] product registers // 3. s[k] partial-sum registers: s[k] <= m[k] + s[k+1] // 4. y rounded and saturated output // Latency: 4 clock cycles from in_valid to out_valid. // // COEFS packs the coefficients, h[0] in the least significant CW bits. // The default is a 31-tap low-pass (firwin, Hamming window, cutoff 6 kHz at // fs = 48 kHz) quantised to Q1.15; see fir_model.py. `timescale 1ns/1ps module fir_transposed #( parameter int NTAPS = 31, parameter int DW = 16, parameter int CW = 16, parameter logic [NTAPS*CW-1:0] COEFS = 496'hffd9ffbdffbc0000009c014401470000fd93fb5bfb8d000008c9139e1c9a20181c9a139e08c90000fb8dfb5bfd93000001470144009c0000ffbcffbdffd9 ) ( input logic clk, input logic rst, // synchronous, active high input logic in_valid, input logic signed [DW-1:0] x, output logic out_valid, output logic signed [15:0] y ); localparam int PW = DW + CW; // product width localparam int AW = PW + $clog2(NTAPS); // accumulator width localparam int FRAC = CW - 1; // coefficient fractional bits logic signed [DW-1:0] x_r; logic signed [PW-1:0] m [0:NTAPS-1]; logic signed [AW-1:0] s [0:NTAPS-1]; logic v1, v2, v3; function automatic logic signed [CW-1:0] coef(input int k); coef = COEFS[k*CW +: CW]; endfunction // Stages 1 and 2: input register and products (no reset: data only). always_ff @(posedge clk) begin x_r <= x; for (int k = 0; k < NTAPS; k++) begin m[k] <= coef(k) * x_r; end end // Stage 3: transposed adder chain. It holds the filter state, so it is // reset and only advances when a valid product arrives. always_ff @(posedge clk) begin if (rst) begin for (int k = 0; k < NTAPS; k++) s[k] <= '0; end else if (v2) begin for (int k = 0; k < NTAPS - 1; k++) begin s[k] <= AW'(m[k]) + s[k+1]; end s[NTAPS-1] <= AW'(m[NTAPS-1]); end end // Stage 4: round half up and saturate to Q1.15. logic signed [AW-1:0] r; assign r = (s[0] + AW'(1 << (FRAC - 1))) >>> FRAC; always_ff @(posedge clk) begin if (r > AW'(32767)) y <= 16'sh7FFF; else if (r < -AW'(32768)) y <= 16'sh8000; else y <= r[15:0]; end // Valid flags. always_ff @(posedge clk) begin if (rst) begin {v1, v2, v3, out_valid} <= '0; end else begin v1 <= in_valid; v2 <= v1; v3 <= v2; out_valid <= v3; end end endmodule