Capture, DVR, and Stream Videos with RTSP - WinForms C#

This tutorial shows how to capture, DVR, and stream videos over RTSP in a WinForms C# application using the LEADTOOLS SDK.

Overview  
Summary This tutorial shows how to use LEADTOOLS Multimedia SDK technologies in a WinForms C# application.
Completion Time 30 minutes
Visual Studio Project Download tutorial project (5 KB)
Platform Windows WinForms C# Application
IDE Visual Studio 2022
Development License Download LEADTOOLS
Try it in another language

Required Knowledge

Get familiar with the basic steps of creating a project by reviewing the Add References and Set a License tutorial, before working on the Capture, DVR, and Stream Videos with RTSP - WinForms C# tutorial.

Create the Project and Add LEADTOOLS References

Start with a copy of the project created in the Add References and Set a License tutorial. If you do not have that project, follow the steps in that tutorial to create it.

The references needed depend upon the purpose of the project. References can be added by local DLLs.

The following DLLs are needed.

The DLLs are located at <INSTALL_DIR>\LEADTOOLS22\Bin\net:

For a complete list of which Multimedia DLL files are required for your application, refer to Multimedia Files to be Included With Your Application.

Set the License File

The License unlocks the features needed for the project. It must be set before any toolkit function is called. For details, including tutorials for different platforms, refer to Setting a Runtime License.

There are two types of runtime licenses:

Note

Adding LEADTOOLS local references and setting a license are covered in more detail in the Add References and Set a License tutorial.

Create the User Interface

With the project created, the references added, and the license set, coding can begin.

In the Solution Explorer, double-click Form1.cs to display the Designer. Open the Toolbox and add five Buttons to the top right of the form, as seen in the screenshot below. The Buttons' Text and Name properties are seen in the table below.

Button Text Button Name
&Device Properties... btnDeviceProperties
Start &Capture btnStartCapture
Stop &Capture btnStopCapture
Start &Streaming btnStartStreaming
Stop &Streaming btnStopStreaming

Add four new Labels to the top left of the form, as seen in the screenshot below. The Labels' Text and Name properties are seen in the table below.

Label Text Label Name
Capture Video Devices lblCaptureVideo
Capture Audio Devices lblCaptureAudio
IP Address lblIpAddress
Port Number lblPortNumber

Now, add two ComboBoxes at the top of the form next to the lblCaptureVideo and lblCaptureAudio Labels. Name the ComboBoxes, cbCaptureVideo and cbCaptureAudio respectively. Next, add two new TextBoxes at the top of the form next to the lblIpAddress and lblPortNumber Labels. Name the TextBoxes, txtIpAddress and txtPortNumber respectively. Leave the txtIpAddress' Text blank, and set the txtPortNumber's Text to 554.

Lastly, add a RichTextBox item to the bottom of the form, as shown in the screenshot below. Set its Name to rtbStatus and leave the Text blank.

Placement of UI controls screenshot.

Add the CaptureCtrl

In the Solution Explorer, double-click Form1.Designer.cs. Add the below code to the InitializeComponent() method to initialize a new CaptureCtrl object.

C#
this._CaptureCtrl = new Leadtools.Multimedia.CaptureCtrl(); 
        ((System.ComponentModel.ISupportInitialize)(this._CaptureCtrl)).BeginInit(); 
this.SuspendLayout(); 
//  
// _CaptureCtrl 
//  
this._CaptureCtrl.AudioCompressors.Selection = -1; 
this._CaptureCtrl.AudioDevices.Selection = -1; 
this._CaptureCtrl.Location = new System.Drawing.Point(14, 100); 
this._CaptureCtrl.Name = "_CaptureCtrl"; 
this._CaptureCtrl.OcxState = null; 
this._CaptureCtrl.Size = new System.Drawing.Size(768, 300); 
this._CaptureCtrl.TabIndex = 2; 
this._CaptureCtrl.TargetDevices.Selection = -1; 
this._CaptureCtrl.TargetFile = "C:\\Temp\\capture.avi"; 
this._CaptureCtrl.Text = "captureCtrl1"; 
this._CaptureCtrl.VideoCompressors.Selection = -1; 
this._CaptureCtrl.VideoDevices.Selection = -1; 
this._CaptureCtrl.WMProfile.Description = ""; 
this._CaptureCtrl.WMProfile.Name = ""; 

Add the line of code below to the bottom of the Form1 class, after #endregion:

C#
private Leadtools.Multimedia.CaptureCtrl _CaptureCtrl; 

Add the CaptureCtrl Initialize Code

Navigate back to Form1.cs, using the Solution Explorer. Click the Events icon in the Properties Window. Then, double-click the Load event to create an event handler if one does not already exist. This will bring up the code behind the form.

Add the using statements below to the top of the Form1 class.

C#
using System; 
using System.IO; 
using System.Net; 
using System.Windows.Forms; 
using Leadtools; 
using Leadtools.Multimedia; 

Add the global variable below to the Form1 class.

C#
//Create RTSPServer 
public RTSPServer _server; 

Add the following code to the Form1() method, below the call to SetLicense().

C#
if (_CaptureCtrl != null) 
{ 
    EnumerateCaptureDevices(); // Get the available Audio and Video devices 
    _CaptureCtrl.Preview = true; // Enable the preview 
    _CaptureCtrl.TargetFile = "Test.LBL"; // Set the name of the resulting DVR file. 
    _CaptureCtrl.TargetFormat = Leadtools.Multimedia.TargetFormatType.DVRTransport; // Set the target format to  DVR 
    _CaptureCtrl.VideoCompressors.Mpeg4.Selected = true; // Set the video compression to Mpeg4 
    _CaptureCtrl.AudioCompressors.AAC.Selected = true; // Set the Audio compression to AAC 
} 
GetIPNumber(); // Getting the v4 IP Address. 

Add the following code inside the Form1_Load event handler to select the first available video device and audio device.

C#
private void Form1_Load(object sender, EventArgs e) 
{ 
    try 
    { 
        if (_CaptureCtrl.VideoDevices.Count > 0) 
            _CaptureCtrl.VideoDevices[0].Selected = true; //Select the first available Video device 
        if (_CaptureCtrl.AudioDevices.Count > 0) 
            _CaptureCtrl.AudioDevices[0].Selected = true; //Select the first available Audio device 
    } 
    catch (Exception ex) 
    { 
        MessageBox.Show("No external video devices found."); 
    } 
} 

Add two new methods named EnumerateCaptureDevices() and GetIPNumber() to the Form1 class. These methods will be called inside the Form1() method, as shown above.

Add the below code to the EnumerateCaptureDevices() method to add all the available video and audio devices on the machine to the ComboBoxes.

C#
private void EnumerateCaptureDevices() 
{ 
    if (_CaptureCtrl.VideoDevices.Count != 0) 
    { 
        for (int i = 0; i < _CaptureCtrl.VideoDevices.Count; i++) 
        { 
            cbCaptureVideo.Items.Add(_CaptureCtrl.VideoDevices[i]); 
        } 
        cbCaptureVideo.SelectedIndex = 0; 
        cbCaptureVideo.SelectedIndexChanged += new EventHandler(cbCaptureVideo_SelectedIndexChanged); 
    } 
 
    if (_CaptureCtrl.AudioDevices.Count != 0) 
    { 
        for (int i = 0; i < _CaptureCtrl.AudioDevices.Count; i++) 
        { 
            cbCaptureAudio.Items.Add(_CaptureCtrl.AudioDevices[i]); 
        } 
        cbCaptureAudio.SelectedIndex = 0; 
        cbCaptureAudio.SelectedIndexChanged += new EventHandler(cbCaptureAudio_SelectedIndexChanged); 
    } 
} 

Add the below code to the GetIPNumber() method to get your IP Address that will be used to access the RTSP stream.

C#
private void GetIPNumber() 
{ 
    IPHostEntry host; 
    host = Dns.GetHostEntry(Dns.GetHostName()); 
    foreach (IPAddress ip in host.AddressList) 
    { 
        if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) 
        { 
            txtIpAddress.Text = ip.ToString(); 
        } 
    } 
} 

Next, add the code below to the new cbCaptureVideo_SelectedIndexChanged EventHandler created in the EnumerateCaptureDevices() method above. This EventHandler fires anytime the video device in the ComboBox changes.

C#
private void cbCaptureVideo_SelectedIndexChanged(object sender, EventArgs e) 
{ 
    if (_CaptureCtrl.State != Leadtools.Multimedia.CaptureState.Running) 
        _CaptureCtrl.VideoDevices[cbCaptureVideo.SelectedIndex].Selected = true; 
    else 
    { 
        _CaptureCtrl.StopCapture(); 
        _CaptureCtrl.VideoDevices[cbCaptureVideo.SelectedIndex].Selected = true; 
    } 
} 

Next, add the code below to the new cbCaptureAudio_SelectedIndexChanged EventHandler created in the EnumerateCaptureDevices() method above. This EventHandler fires anytime the audio device in the ComboBox changes.

C#
private void cbCaptureAudio_SelectedIndexChanged(object sender, EventArgs e) 
{ 
    try 
    { 
        if (_CaptureCtrl.State != Leadtools.Multimedia.CaptureState.Running) 
            _CaptureCtrl.AudioDevices[cbCaptureAudio.SelectedIndex].Selected = true; 
        else 
        { 
            _CaptureCtrl.StopCapture(); 
            _CaptureCtrl.AudioDevices[cbCaptureAudio.SelectedIndex].Selected = true; 
        } 
    } 
    catch (Exception ex) 
    { 
        cbCaptureAudio.SelectedIndex = 0; 
        _CaptureCtrl.AudioDevices[0].Selected = true; 
        MessageBox.Show(ex.Message); 
    } 
} 

Add the Capture, DVR, and Stream Code

In the Solution Explorer, double-click Form1.cs to display the Designer. Double-click on all five of the Buttons to create their own event handlers. This will bring up the code behind the form.

Add the code below to the btnDeviceProperties_Click event handler to display the CaptureCtrl capture properties dialog, and allow you to adjust the settings.

C#
private void btnDeviceProperties_Click(object sender, EventArgs e) 
{ 
    _CaptureCtrl.ShowDialog(Leadtools.Multimedia.CaptureDlg.Capture, this); 
} 

Add the code below to the btnStartCapture_Click event handler to start the CaptureCtrl.

C#
private void btnStartCapture_Click(object sender, EventArgs e) 
{ 
    // Uncomment the following two lines to show the built gragh. 
    // _CaptureCtrl.ReadyCapture(Leadtools.Multimedia.CaptureMode.VideoAndAudio); 
    // _CaptureCtrl.EditGraph(); 
    try 
    { 
        if (_CaptureCtrl.AudioDevices.Count == 0) 
        { 
            MessageBox.Show("The Capture and the streaming will be without Audio"); 
            _CaptureCtrl.StartCapture(Leadtools.Multimedia.CaptureMode.Video); 
        } 
        else 
        { 
            _CaptureCtrl.StartCapture(Leadtools.Multimedia.CaptureMode.VideoAndAudio); 
        } 
        btnStartCapture.Enabled = !btnStartCapture.Enabled; 
        btnStartCapture.Enabled = !btnStartCapture.Enabled; 
        if (System.IO.File.Exists(_CaptureCtrl.TargetFile) && btnStopStreaming.Enabled == false) 
            btnStartStreaming.Enabled = true; 
 
        if (_CaptureCtrl.State == CaptureState.Running) 
            rtbStatus.Text = "Capturing..."; 
        if (btnStopStreaming.Enabled == true) 
            rtbStatus.Text += "\t" + "Streaming..."; 
    } 
    catch (Exception ex) 
    { 
        MessageBox.Show(ex.Message, this.Text); 
    } 
} 

Add the code below to the btnStopCapture_Click event handler to stop the CaptureCtrl.

C#
private void btnStopCapture_Click(object sender, EventArgs e) 
{ 
    if (_CaptureCtrl.State == Leadtools.Multimedia.CaptureState.Running) // Check if the Capture control is running  
        _CaptureCtrl.StopCapture(); // Stop the capture 
    btnStartCapture.Enabled = !btnStartCapture.Enabled; 
    btnStopCapture.Enabled = !btnStopCapture.Enabled; 
 
 
    rtbStatus.Text = _CaptureCtrl.State.ToString() + "..."; 
    if (btnStartStreaming.Enabled == false) 
        rtbStatus.Text += "\t streaming the saved capture file"; 
} 

Add the code below to the btnStartStreaming_Click event handler to create a new RTSPServer instance and start streaming the captured video to the specified port number.

C#
private void btnStartStreaming_Click(object sender, EventArgs e) 
{ 
    if (txtPortNumber.Text == "0") 
    { 
        MessageBox.Show("Port Number Cannot be 0"); 
        return; 
    } 
    if ((txtIpAddress.Text != string.Empty) && (txtPortNumber.Text != string.Empty)) 
    { 
        _server = new RTSPServer(); // Create new RTSPServer Instance 
        _server.SetSourceFolder(0, ""); // Leaving the folder Name as an empty string causes saving in the current directory 
        _server.TargetAddress = txtIpAddress.Text; // Set the IP Address 
        _server.StartServer(int.Parse(txtPortNumber.Text)); // Start Streaming using the the port number. 
        btnStopStreaming.Enabled = !btnStopStreaming.Enabled; 
        btnStartStreaming.Enabled = !btnStartStreaming.Enabled; 
        rtbStatus.Text = "Streaming..." + "\t Use this for playing the RTSP:  " + "rtsp://" + txtIpAddress.Text + ":" + txtPortNumber.Text + "/Test.LBL"; 
    } 
    else 
    { 
        MessageBox.Show("Please Make sure to insert correct IP address and Port number"); 
    } 
} 

Add the code below to the btnStopStreaming_Click event handler to stop streaming the video.

C#
private void btnStopStreaming_Click(object sender, EventArgs e) 
{ 
    if (_server != null) 
    { 
        _server.StopServer(int.Parse(txtPortNumber.Text)); // Stop streaming using the port number 
    } 
    btnStartStreaming.Enabled = !btnStartStreaming.Enabled; 
    btnStopStreaming.Enabled = !btnStopStreaming.Enabled; 
    if (_CaptureCtrl.State == CaptureState.Running) 
        rtbStatus.Text = "Capturing..."; 
    else 
        rtbStatus.Text = _CaptureCtrl.State.ToString() + "..."; 
} 

Run the Project

Run the project by pressing F5, or by selecting Debug -> Start Debugging.

If the steps were followed correctly, the application runs, initializes the CaptureCtrl, and the form should appear. To test, follow the steps below:

  1. Using the ComboBoxes, select the video device and audio device to use when capturing video. Audio device is not necessary.

  2. If you wish to change any of the device properties, do so by clicking Device Properties...

  3. Set the Port Number to the port you would like to stream to.

  4. Press Start Capture to start your video.

  5. Press Start Streaming to start your video stream.

  6. You can use the LEADTOOLS MM Playback Demo to play the captured stream.

  7. Once you are finished you can select Stop Capture and Stop Streaming to end the video capture and stream.

Wrap-up

This tutorial showed how to capture, DVR, and stream a video in a WinForms C# application. We also covered how to use the CaptureCtrl and RTSPServer classes.

See Also

Help Version 22.0.2024.2.20
Products | Support | Contact Us | Intellectual Property Notices
© 1991-2023 LEAD Technologies, Inc. All Rights Reserved.


Products | Support | Contact Us | Intellectual Property Notices
© 1991-2023 LEAD Technologies, Inc. All Rights Reserved.