///////////////////////////////////////////////////////////////////////////////////////////////////
// Company: <Name>
//
// File: slvs_frame_end_gen.v
// File history:
//      <Revision number>: <Date>: <Comments>
//      <Revision number>: <Date>: <Comments>
//      <Revision number>: <Date>: <Comments>
//
// Description: 
//
// <Description here>
//
// Targeted device: <Family::PolarFireSoC> <Die::MPFS250TS_ES> <Package::FCG1152>
// Author: <Name>
//
/////////////////////////////////////////////////////////////////////////////////////////////////// 

//`timescale <time_units> / <precision>

module slvs_frame_end_gen( 

 input clk_i,
 input resetn_i,
 input frame_valid_i,
 input line_valid_i,
 output reg frame_end_o,
 output line_valid_o
 );
 
 parameter vcnt_threshold = 66;
 
reg [15:0] h_cnt;
reg [15:0] v_cnt;
reg [ 3:0] cnt;
reg        line_valid_r;
wire       line_valid_fe;
reg        frame_end_r;
wire       frame_end_fe;//re

assign frame_end_fe = ~frame_valid_i & (frame_end_r);

always@(posedge clk_i, negedge resetn_i)
  if (!resetn_i)
  begin
    frame_end_r <= 0;
    frame_end_o <= 0;
  end
  else
  begin
    frame_end_r <= frame_valid_i;
    if(frame_end_fe  == 1 || cnt != 0 )
      cnt       <= cnt + 1;
      
    if (cnt == 15)
      frame_end_o <= 1;
    else
      frame_end_o <= 0;
  end      

assign line_valid_fe = ~line_valid_i & line_valid_r;
assign line_valid_o  = (h_cnt < 240 && ( ( v_cnt >= vcnt_threshold) &&  ( v_cnt < 2160 + vcnt_threshold))) ? line_valid_i : 0 ;

always@(posedge clk_i, negedge resetn_i)
  if (!resetn_i)
  begin
    line_valid_r <= 0;
    h_cnt        <= 0;
    v_cnt        <= 0;
  end
  else
  begin
    line_valid_r <= line_valid_i;
    if (line_valid_i)
      h_cnt      <= h_cnt + 1;
    else
      h_cnt      <= 0;
    
    if (line_valid_fe)
      v_cnt      <= v_cnt + 1;
    else if (frame_end_fe == 1)
      v_cnt      <= 0;
  end    
       
endmodule

