Imports System.Threading
Public Class FramePerSec
	Private m_Mutex As New Mutex(False)
	Private m_aRcvTimeList As Integer()
	Private m_InsertIndex As Integer = 0
	Private m_IsOverWrite As Boolean = False

	Public Sub New(ByVal needCount As Integer)
		If needCount < 2 Then
			needCount = 2
		End If
		ReDim m_aRcvTimeList(needCount - 1)
		Native.timeBeginPeriod(1)
	End Sub
	Private Function GetTime() As Integer
		Return (Native.timeGetTime())
	End Function
	Public Sub OnReceiveImage()
		m_Mutex.WaitOne()
		m_aRcvTimeList(m_InsertIndex) = GetTime()
		m_InsertIndex = m_InsertIndex + 1
		If (m_aRcvTimeList.GetLength(0) <= m_InsertIndex) Then
			m_IsOverWrite = True
			m_InsertIndex = 0
		End If
		m_Mutex.ReleaseMutex()
	End Sub
	Private Function GetFirstTimeIndex() As Integer
		Dim firstTimeIndex As Integer = 0
		If (m_IsOverWrite) Then
			firstTimeIndex = m_InsertIndex
		End If
		Return (firstTimeIndex)
	End Function
	Private Function GetLatestTimeIndex() As Integer
		Dim latestTimeIndex As Integer = 0
		If 0 <> m_InsertIndex Then
			latestTimeIndex = m_InsertIndex - 1
		Else
			If m_IsOverWrite Then
				latestTimeIndex = m_aRcvTimeList.GetLength(0) - 1
			End If
		End If
		Return (latestTimeIndex)
	End Function
	Public Function GetFPS() As Double
		m_Mutex.WaitOne()
		Dim firstTimeIndex As Integer = GetFirstTimeIndex()
		Dim latestTimeIndex As Integer = GetLatestTimeIndex()
		Dim frameCount As Integer = 0

		If (firstTimeIndex < latestTimeIndex) Then
			frameCount = latestTimeIndex - firstTimeIndex
		Else
			frameCount = m_aRcvTimeList.GetLength(0) - 1
		End If

		Dim firstTime As Integer = m_aRcvTimeList(firstTimeIndex)
		Dim latestTime As Integer = m_aRcvTimeList(latestTimeIndex)
		m_Mutex.ReleaseMutex()

		Dim framePerSec As Double = 0.0
		If (0 <> frameCount) Then
			Dim period As Integer = 0
			If (firstTime <= latestTime) Then
				period = latestTime - firstTime
			Else
				period = Integer.MaxValue - firstTime
				period = period + latestTime + 1
			End If
			If (0 <> period) Then
				framePerSec = frameCount * 1000.0 / period
			End If
		End If
		Return (framePerSec)
	End Function
End Class
