// 3x3 window generator for a raster-order pixel stream. // Two line buffers hold the previous two lines. Every input pixel at (x, y) // pushes one column {row y-2, row y-1, row y} into a 3x3 shift register, // so the window is centred on (x-1, y-1). win_ok is low when that centre // lies on the image border (x < 2 or y < 2), where the window would reach // outside the image. in_valid may have gaps; in_sof marks pixel (0, 0). // Latency: 3 clocks from an input pixel to its window. `timescale 1ns / 1ps module window3x3 #( parameter int W = 640, parameter int H = 480, localparam int XW = $clog2(W), localparam int YW = $clog2(H) ) ( input logic clk, input logic rst, input logic in_valid, input logic in_sof, input logic [7:0] pix, output logic win_valid, output logic win_sof, output logic win_ok, output logic [2:0][2:0][7:0] win // win[row][col], row 0 = top ); // Position of the incoming pixel. logic [XW-1:0] x_next, x_cur; logic [YW-1:0] y_next, y_cur; assign x_cur = in_sof ? '0 : x_next; assign y_cur = in_sof ? '0 : y_next; always_ff @(posedge clk) begin if (rst) begin x_next <= '0; y_next <= '0; end else if (in_valid) begin if (x_cur == XW'(W - 1)) begin x_next <= '0; y_next <= (y_cur == YW'(H - 1)) ? '0 : y_cur + 1'b1; end else begin x_next <= x_cur + 1'b1; y_next <= y_cur; end end end // Stage 1: read both line buffers. lb0 holds row y-1 and is refilled // with row y; one clock later lb1 (row y-2) is refilled with row y-1. logic [7:0] row1, row2, pix1, pix2, mid2; logic v1, v2; logic [XW-1:0] x1, x2; logic [YW-1:0] y1, y2; line_buffer #(.W(W)) u_lb0 (.clk(clk), .en(in_valid), .addr(x_cur), .din(pix), .dout(row1)); line_buffer #(.W(W)) u_lb1 (.clk(clk), .en(v1), .addr(x1), .din(row1), .dout(row2)); always_ff @(posedge clk) begin if (rst) begin v1 <= 1'b0; v2 <= 1'b0; end else begin v1 <= in_valid; v2 <= v1; end x1 <= x_cur; y1 <= y_cur; pix1 <= pix; x2 <= x1; y2 <= y1; pix2 <= pix1; mid2 <= row1; end // Stage 3: shift the new column {row2, mid2, pix2} into the window. always_ff @(posedge clk) begin if (rst) begin win_valid <= 1'b0; end else begin win_valid <= v2; end if (v2) begin win[0] <= {row2, win[0][2], win[0][1]}; // {col 2, col 1, col 0} win[1] <= {mid2, win[1][2], win[1][1]}; win[2] <= {pix2, win[2][2], win[2][1]}; win_ok <= (x2 >= XW'(2)) && (y2 >= YW'(2)); win_sof <= (x2 == '0) && (y2 == '0); end end endmodule