STANAG 4609 Player .NET SDK  Version 3.9.1
Form1.cs
using System;
using System.Linq;
using System.Windows.Forms;
using KlvPlayer;
using StCoreWr;
using KlvPlayerDemoWinForms.Properties;
using System.Diagnostics;
using System.Net;
using System.Text.RegularExpressions;
using System.IO;
using System.Xml.Linq;
using System.Net.Sockets;
using System.Drawing;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using KlvBaseTypes;
using StMonitorAgent;
using Newtonsoft.Json.Linq;
namespace KlvPlayerDemoWinForms
{
public partial class Form1 : Form
{
public enum OperationMode { FilePlayback, StreamPlayback };
private OperationMode m_OperationalMode = OperationMode.FilePlayback;
private bool m_fDvrMode = false;
private bool m_IsLive = false;
private CKlvPlayer m_KlvPlayer = null;
private bool m_fRunning = false;
private bool m_fDragging = false;
private int m_KlvPid = -1;
private long m_KlvPacketCounter = 0;
private int m_nextOverlayControlIndex;
private CStMonitorAgent m_MonitorAgent = null; // Demo Klv Monitor
private DateTime m_LastMonitorKlvUpdate = DateTime.Now; // Demo Klv Monitor last update
private int MaxMonitorKlvUpdateRate = 200; // Demo Klv Monitor Update Rate
private Image m_startImage;
private Image m_stopImage;
private Image m_pauseImage;
private double m_MediaDuration;
string m_Url = "";
// Constructor
public Form1()
{
InitializeComponent();
}
// Called on form load. Initialize the controls
private void Form1_Load(object sender, EventArgs e)
{
try
{
InitImages();
textBoxUrl.Text = Settings.Default.FilePath;
textBoxIP.Text = Settings.Default.IP;
maskedTextBoxPort.Text = Settings.Default.Port;
textBoxRecordingUrl.Text = Settings.Default.RecordingFilePath;
IPAddress[] ipv4Addresses = Array.FindAll(Dns.GetHostEntry(string.Empty).AddressList, a => a.AddressFamily == AddressFamily.InterNetwork);
comboBoxNic.DataSource = ipv4Addresses;
comboBoxNic.SelectedIndex = 0;
radioButtonFilePlayback.Checked = Settings.Default.FilePlaybackMode;
buttonSnapShot.Enabled = false;
checkBoxDVR.Checked = Settings.Default.DvrMode;
textBoxRecordingUrl.Enabled = Settings.Default.DvrMode;
m_nextOverlayControlIndex = 1;
InitKlvPlayer();
}
catch (Exception ex)
{
Trace.WriteLine(ex.Message);
MessageBox.Show(ex.Message);
}
}
private void InitImages()
{
System.IO.Stream stream;
System.Reflection.Assembly assembly;
assembly = System.Reflection.Assembly.LoadFrom(Application.ExecutablePath);
stream = assembly.GetManifestResourceStream("KlvPlayerDemoWinForms.Resources.BttnPlay.png");
m_startImage = Image.FromStream(stream);
stream = assembly.GetManifestResourceStream("KlvPlayerDemoWinForms.Resources.BttnStop.png");
m_stopImage = Image.FromStream(stream);
stream = assembly.GetManifestResourceStream("KlvPlayerDemoWinForms.Resources.BttnPause.png");
m_pauseImage = Image.FromStream(stream);
}
// Called on
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
try
{
// Stop the player in case it is running
if (m_KlvPlayer != null)
{
if (m_fRunning)
StopPlayback();
m_KlvPlayer.Close();
m_KlvPlayer = null;
}
if (m_MonitorAgent != null)
m_MonitorAgent.CloseAllSubscribers();
// Save current settings
Settings.Default.FilePath = textBoxUrl.Text;
Settings.Default.IP = textBoxIP.Text;
Settings.Default.Port = maskedTextBoxPort.Text;
Settings.Default.Save();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
throw;
}
}
// Initialize Klv Player instance and setup events
private void InitKlvPlayer()
{
Trace.WriteLine("InitKlvPlayer");
try
{
if (m_KlvPlayer == null)
{
m_KlvPlayer = new CKlvPlayer(m_fDvrMode); // Create Player instance. If DVR mode (Shifted TV) is not needed, pass false to save the overhead related to DVR mode.
m_KlvPlayer.Hwnd = (int)this.VideoPanel.Handle; // Set Window handle for video rendering
m_KlvPlayer.RenderVideo = true;
m_KlvPlayer.VideoCaptureMode.uncompressedVideo = UncompressedVideoModeWr.UncompressedVideoMode_None; // We don't need uncompressed video frames.
m_KlvPlayer.AudioMayBeMissing = true;
InitParams();
// Set eventsFrameAccuracyRequiresSequenceHeaders
m_KlvPlayer.PidDetectionEvent += new NotifyPidDetection(OnPidDetectionEvent); // PID detection events (video / KLV / audio / data)
m_KlvPlayer.PlayerEvent += new NotifyPlayerEvent(OnPlayerEvent); // Player general events notification
m_KlvPlayer.SyncFrameEvent += new NotifySyncFrame(OnSyncFrameEvent); // Synchronized Video frames / Klv / Private data
m_KlvPlayer.ErrorEvent += new NotifyError(OnErrorEvent); // Player error events
}
Trace.WriteLine("Activating the player");
if (m_KlvPlayer.Activate("KlvPlayer", Settings.Default.LicensePath, Settings.Default.LicenseKey) == false)
{
this.Text = "KlvPlayer (Demo mode)";
ShowStatusMessage("License not valid. Demo mode.");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void InitParams()
{
m_KlvPlayer.FrameAccuracyMode = Settings.Default.FrameAccuracyMode; // Set this to true if you want to achieve an accurate StepForward / StepBackward functionality. Note, TimeToRender will be always zero (sync will be done internally).
m_KlvPlayer.FrameAccuracyRequiresSequenceHeaders = Settings.Default.FrameAccuracyRequiresSequenceHeaders;
m_KlvPlayer.DvrRefTimeMatchMode = (DVR_RefTimeMatchMode)Settings.Default.DvrTimeMatchMode;
m_KlvPlayer.DvrLocalBufferSize = (uint)Settings.Default.DvrLocaRecordingBufferSize;
}
#region KlvPlayer Events
void OnPidDetectionEvent(List<PidInfoWr> pidList)
{
pidList.ForEach(pid =>
{
if (pid.streamType == StreamType.KLV && m_KlvPid == -1)
m_KlvPid = pid.streamId;
});
}
void OnPlayerEvent(Player_State ev, string info, long param)
{
ShowStatusMessage(string.Format("{0} {1}", ev, info));
BeginInvoke(new MethodInvoker(delegate
{
PlayerStateChanged();
}));
}
void OnSyncFrameEvent(List<StreamFrameInfoWr> streamList)
{
streamList.ForEach(delegate (StreamFrameInfoWr streamFrame)
{
switch (streamFrame.streamType)
{
case StreamType.VIDEO:
{
// Here we got an uncompressed frame
VideoFrameInfoWr vf = streamFrame as VideoFrameInfoWr;
}
break;
case StreamType.KLV:
{
// Here we got a klv packet
KlvFrameInfoWr kf = streamFrame as KlvFrameInfoWr;
if (kf.duplicateCounter == 0 && kf.decodedData != null)
{
if (m_MonitorAgent != null && DateTime.Now.Subtract(m_LastMonitorKlvUpdate).TotalMilliseconds > MaxMonitorKlvUpdateRate)
{
PubToMonitor(kf);
m_LastMonitorKlvUpdate = DateTime.Now;
}
m_KlvPacketCounter++;
BeginInvoke(new MethodInvoker(delegate
{
toolStripStatusLabelKlvPacketsReceived.Text = m_KlvPacketCounter.ToString();
}));
}
}
break;
case StreamType.PRIVATE_DATA:
{
// Here we got a private data packet
DataFrameInfoWr df = streamFrame as DataFrameInfoWr;
}
break;
}
});
}
void OnErrorEvent(Error_Type e, string err)
{
string errMessage = string.Format("{0} {1}", e, err);
ShowStatusMessage(errMessage);
BeginInvoke(new MethodInvoker(delegate
{
MessageBox.Show(err);
}));
}
#endregion
#region KlvPlayer Control
// Start / Stop playback
private void buttonStartStop_Click(object sender, EventArgs e)
{
StartStopPlayback();
}
// pause playback
private void buttonPause_Click(object sender, EventArgs e)
{
if (m_KlvPlayer.PlayerState == Player_State.Paused)
m_KlvPlayer.Start();
else
{
m_KlvPlayer.Pause();
if (m_OperationalMode == OperationMode.StreamPlayback)
m_IsLive = false;
}
}
private void buttonStepForward_Click(object sender, EventArgs e)
{
if (m_KlvPlayer != null)
m_KlvPlayer.StepForward();
}
private void buttonStepBackward_Click(object sender, EventArgs e)
{
if (m_KlvPlayer != null)
m_KlvPlayer.StepBackward();
}
private void buttonLive_Click(object sender, EventArgs e)
{
if (m_KlvPlayer != null)
m_KlvPlayer.GoToLive();
buttonLive.Enabled = false;
m_IsLive = true;
}
private void buttonSnapShot_Click(object sender, EventArgs e)
{
if (m_KlvPlayer == null)
return;
try
{
System.Drawing.Bitmap frame = m_KlvPlayer.GetSnapshot();
frame.RotateFlip(RotateFlipType.Rotate180FlipX);
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Jpeg file|*.jpg | Bmp file|*.bmp";
saveFileDialog.Title = "Save Current Frame";
saveFileDialog.OverwritePrompt = true;
DialogResult res = saveFileDialog.ShowDialog();
if (res == System.Windows.Forms.DialogResult.OK)
{
// If the file name is not an empty string open it for saving.
if (saveFileDialog.FileName != "")
{
var extension = Path.GetExtension(saveFileDialog.FileName);
switch (extension.ToLower())
{
case ".bmp":
frame.Save(saveFileDialog.FileName);
break;
default:
System.Drawing.Imaging.ImageCodecInfo jgpEncoder = GetEncoder(System.Drawing.Imaging.ImageFormat.Jpeg);
System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;
System.Drawing.Imaging.EncoderParameters myEncoderParameters = new System.Drawing.Imaging.EncoderParameters(1);
System.Drawing.Imaging.EncoderParameter myEncoderParameter = new System.Drawing.Imaging.EncoderParameter(myEncoder, 80L);
myEncoderParameters.Param[0] = myEncoderParameter;
frame.Save(saveFileDialog.FileName, jgpEncoder, myEncoderParameters);
break;
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
#endregion
// Start / Stop playback
private void StartStopPlayback()
{
Trace.WriteLine("StartStopPlayback command");
if (m_KlvPlayer == null)
InitKlvPlayer();
else
InitParams();
if (m_fRunning == false)
{
m_MediaDuration = 0.0;
m_KlvPacketCounter = 0;
if (!FillUrl())
{
MessageBox.Show(this, "Empty Url", "Error", MessageBoxButtons.OK);
return;
}
m_KlvPlayer.Caching = Settings.Default.Caching;
m_KlvPlayer.VideoPresenter().UseDirectX = this.enableOverlay.Checked;
Trace.WriteLine("Init Player - Url " + m_Url);
if (m_KlvPlayer.Init(m_Url) == false)
{
string errorMsg = "Cannot initialize player.";
Trace.WriteLine(errorMsg);
MessageBox.Show(errorMsg);
return;
}
this.enableOverlay.Enabled = false;
Trace.WriteLine("Start Player command");
m_KlvPlayer.Start();
if (m_OperationalMode == OperationMode.StreamPlayback)
{
m_IsLive = true;
Trace.WriteLine("Operational Mode - StreamPlayback");
buttonPause.Enabled = false;
labelFileDuration.Text = "-";
}
m_fRunning = true;
panelParams.Enabled = false;
PositionTrackBar.Value = 0;
if (m_KlvPlayer.IsDvrMode && !string.IsNullOrEmpty(Settings.Default.RecordingFilePath))
m_KlvPlayer.AddRecordedUrl(Settings.Default.RecordingFilePath);
}
else
{
StopPlayback();
this.enableOverlay.Enabled = true;
}
}
// Stop playback
private void StopPlayback()
{
timer1.Enabled = false;
Trace.WriteLine("Stop Player command");
if (m_KlvPlayer != null)
m_KlvPlayer.Stop();
m_fRunning = false;
}
private void radioButtonFilePlayback_CheckedChanged(object sender, EventArgs e)
{
if ((sender as ButtonBase).Enabled == true)
{
m_OperationalMode = OperationMode.FilePlayback;
groupBoxFile.Enabled = true;
groupBoxStream.Enabled = false;
buttonLive.Visible = false;
}
}
private void radioButtonStreamPlayback_CheckedChanged(object sender, EventArgs e)
{
if ((sender as ButtonBase).Enabled == true)
{
m_OperationalMode = OperationMode.StreamPlayback;
groupBoxFile.Enabled = false;
groupBoxStream.Enabled = true;
buttonLive.Visible = m_KlvPlayer.IsDvrMode;
}
}
private void checkBoxDVR_CheckedChanged(object sender, EventArgs e)
{
if ((sender as CheckBox).Checked == true)
{
m_fDvrMode = true;
textBoxRecordingUrl.Enabled = true;
buttonLive.Visible = true;
}
else
{
m_fDvrMode = false;
textBoxRecordingUrl.Enabled = false;
buttonLive.Visible = false;
}
if(m_KlvPlayer != null)
{
m_KlvPlayer.Close();
m_KlvPlayer = null;
}
}
private void PositionTrackBar_MouseDown(object sender, MouseEventArgs e)
{
m_fDragging = true;
}
private void PositionTrackBar_MouseUp(object sender, MouseEventArgs e)
{
m_fDragging = false;
timer1.Enabled = false;
m_KlvPlayer.SetPosition(((TrackBar)sender).Value);
timer1.Enabled = true;
m_IsLive = false;
}
private void buttonBrowse_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Video (*.MPG;*.MPEG;*.TS;*.M3U8)|*.MPG;*.MPEG;*.TS;*.M3U8|" + "All files (*.*)|*.*";
ofd.Multiselect = true;
ofd.Title = "Please Select Video File(s)";
DialogResult res = ofd.ShowDialog();
if (res == System.Windows.Forms.DialogResult.OK)
{
Settings.Default.FilePath = ofd.FileName;
textBoxUrl.Text = ofd.FileName;
}
}
private void buttonBrowseRecordingUrl_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Video (*.MPG;*.MPEG;*.TS;*.M3U8)|*.MPG;*.MPEG;*.TS;*.M3U8|" + "All files (*.*)|*.*";
ofd.Multiselect = true;
ofd.Title = "Please Select Video File(s)";
DialogResult res = ofd.ShowDialog();
if (res == System.Windows.Forms.DialogResult.OK)
{
textBoxRecordingUrl.Text = ofd.FileName;
Settings.Default.RecordingFilePath = ofd.FileName;
}
}
private void exitToolStripMenuItemExit_Click(object sender, EventArgs e)
{
if (m_KlvPlayer != null)
m_KlvPlayer.Stop();
Close();
}
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
AboutForm aForm = new AboutForm();
aForm.ShowDialog();
}
private void optionsToolStripMenuItem_Click(object sender, EventArgs e)
{
OptionsForm oForm = new OptionsForm();
oForm.ShowDialog();
}
private void buttonKlvMonitor_Click(object sender, EventArgs e)
{
if (m_MonitorAgent == null)
{
// Open / Close Klv Monitor
Task.Factory.StartNew(() =>
{
m_MonitorAgent = new CStMonitorAgent();
if (!m_MonitorAgent.OpenMonitorWindow())
{
System.Windows.Forms.MessageBox.Show("Cannot open StMonitor");
m_MonitorAgent = null;
}
});
}
else
{
m_MonitorAgent.CloseAllSubscribers();
m_MonitorAgent = null;
}
}
// Called on player state change
private void PlayerStateChanged()
{
Trace.WriteLine(string.Format("Player State changed: {0}", m_KlvPlayer.PlayerState));
BeginInvoke(new MethodInvoker(delegate
{
switch (m_KlvPlayer.PlayerState)
{
case Player_State.Starting:
case Player_State.Running:
if (m_OperationalMode == OperationMode.FilePlayback)
m_MediaDuration = m_KlvPlayer.GetDuration();
UpdateControlsAfterPlayerStart();
timer1.Enabled = true;
break;
case Player_State.WaitingFordata:
break;
case Player_State.Paused:
if(!m_KlvPlayer.IsDvrMode)
timer1.Enabled = false;
UpdateControlsAfterPlayerPause();
break;
case Player_State.Stopped:
case Player_State.Completed:
if (m_fRunning)
{
if (m_KlvPlayer != null)
m_KlvPlayer.Stop();
m_fRunning = false;
}
UpdateControlsAfterPlayerStop();
break;
case Player_State.Error:
break;
default:
break;
}
}));
}
private void UpdateControlsAfterPlayerStart()
{
BeginInvoke(new MethodInvoker(delegate
{
buttonStartStop.Image = m_stopImage;
buttonPause.Image = m_pauseImage;
buttonSnapShot.Enabled = true;
buttonPause.Enabled = true;
if (m_OperationalMode == OperationMode.FilePlayback)
{
if (m_MediaDuration > 0.0)
PositionTrackBar.Enabled = true;
labelFileDuration.Text = m_MediaDuration == 0.0 ? "..." : TimeSpan.FromSeconds(m_MediaDuration).ToString(@"hh\:mm\:ss");
PositionTrackBar.Maximum = (int)m_MediaDuration;
}
else
{
if (m_KlvPlayer.IsDvrMode)
{
labelFileDuration.Text = "Live";
PositionTrackBar.Enabled = true;
}
}
buttonStepForward.Enabled = false;
buttonStepBackward.Enabled = false;
}));
}
private void UpdateControlsAfterPlayerStop()
{
BeginInvoke(new MethodInvoker(delegate
{
buttonStartStop.Image = m_startImage;
buttonPause.Image = m_pauseImage;
PositionTrackBar.Enabled = false;
buttonPause.Enabled = false;
buttonStepForward.Enabled = false;
buttonStepBackward.Enabled = false;
buttonLive.Enabled = false;
buttonSnapShot.Enabled = false;
panelParams.Enabled = true;
}));
}
private void UpdateControlsAfterPlayerPause()
{
BeginInvoke(new MethodInvoker(delegate
{
buttonPause.Image = m_startImage;
buttonStepForward.Enabled = true;
buttonStepBackward.Enabled = true;
buttonLive.Enabled = true;
}));
}
private void ShowStatusMessage(string message)
{
Trace.WriteLine(message);
BeginInvoke(new MethodInvoker(delegate
{
StatusLabel.Text = message;
}));
}
private void timer1_Tick(object sender, EventArgs e)
{
// Update slider position if we're in the file playblack state
UpdateSliderAndPos();
}
private void UpdateSliderAndPos()
{
try
{
if (m_KlvPlayer != null && (m_KlvPlayer.PlayerState == Player_State.Running || m_KlvPlayer.PlayerState == Player_State.WaitingFordata ||
(m_KlvPlayer.IsDvrMode && m_KlvPlayer.PlayerState == Player_State.Paused)))
{
if (!m_fDragging)
{
double? val = null;
if (m_KlvPlayer.IsDvrMode)
{
double posStart, posEnd;
if (m_KlvPlayer.GetAvailableRange(out posStart, out posEnd))
{
PositionTrackBar.Minimum = (int)posStart;
PositionTrackBar.Maximum = (int)posEnd;
int endPosReport;
if (m_IsLive)
endPosReport = (int)posEnd;
else
endPosReport = (int)m_KlvPlayer.GetCurrentPosition();
if ((int)posStart < endPosReport && (int)posEnd >= endPosReport)
PositionTrackBar.Value = endPosReport;
}
}
else
if (m_OperationalMode == OperationMode.FilePlayback)
{
val = m_KlvPlayer.GetCurrentPosition();
if (val.Value > 0.0)
{
int pos = (int)val;
PositionTrackBar.Value = pos < PositionTrackBar.Maximum ? pos : PositionTrackBar.Maximum;
}
}
if(!val.HasValue)
val = m_KlvPlayer.GetCurrentPosition();
labelCurPosition.Text = TimeSpan.FromSeconds(val.Value).ToString(@"hh\:mm\:ss");
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private System.Drawing.Imaging.ImageCodecInfo GetEncoder(System.Drawing.Imaging.ImageFormat format)
{
System.Drawing.Imaging.ImageCodecInfo[] codecs = System.Drawing.Imaging.ImageCodecInfo.GetImageDecoders();
foreach (System.Drawing.Imaging.ImageCodecInfo codec in codecs)
{
if (codec.FormatID == format.Guid)
{
return codec;
}
}
return null;
}
private void fullScreenToolStripMenuItem_Click(object sender, EventArgs e)
{
if (m_KlvPlayer != null)
m_KlvPlayer.SetFullScreen(true);
}
private void PubToMonitor(KlvFrameInfoWr kf)
{
var jsonPckt = new JObject();
jsonPckt.Add("pcktNumber", m_KlvPacketCounter);
jsonPckt["klvs"] = (JObject)kf.decodedData;
m_MonitorAgent.PubNewPacket(jsonPckt.ToString());
}
private bool FillUrl()
{
Trace.WriteLine("FillUrl");
try
{
switch (m_OperationalMode)
{
case OperationMode.FilePlayback:
m_Url = textBoxUrl.Text;
break;
case OperationMode.StreamPlayback:
if (checkBoxTSoverRTP.Checked) // For RTP
m_Url = String.Format(@"rtp://{0}:{1}/nic={2}/timeout={3}/format=m2t", textBoxIP.Text, maskedTextBoxPort.Text, comboBoxNic.Text, Settings.Default.TimeOut);
else
m_Url = String.Format(@"udp://{0}:{1}/nic={2}/timeout={3}", textBoxIP.Text, maskedTextBoxPort.Text, comboBoxNic.Text, Settings.Default.TimeOut);
break;
default:
break;
}
}
catch (Exception ex)
{
Trace.WriteLine(ex.Message);
}
Trace.WriteLine("Url " + m_Url);
return !string.IsNullOrEmpty(m_Url);
}
private void addOverlay_Click(object sender, EventArgs e)
{
var graphicOverlayControl = m_KlvPlayer.VideoPresenter().CreateGraphicOverlayControl();
if (graphicOverlayControl == null)
return;
var overlayWindow = new GraphicOverlayForm(m_nextOverlayControlIndex, graphicOverlayControl);
overlayWindow.Text = "Graphic overlay config #" + m_nextOverlayControlIndex.ToString();
overlayWindow.Show();
m_nextOverlayControlIndex++;
}
private void enableOverlay_CheckedChanged(object sender, EventArgs e)
{
this.addOverlay.Visible = this.enableOverlay.Checked;
}
}
}
Untitled 1




 Copyright 2019,    IMPLEOTV SYSTEMS LTD