### Install RtspClientSharp using NuGet Source: https://github.com/bogdanovkirill/rtspclientsharp/blob/master/README.md Install the RtspClientSharp NuGet package using the command line. Ensure your project targets .NET 4.6.1/.NET Core 2.0 or later. ```cmd nuget install RtspClientSharp ``` -------------------------------- ### Install RtspClientSharp via .NET CLI Source: https://context7.com/bogdanovkirill/rtspclientsharp/llms.txt Use this command to add the RtspClientSharp package to your project using the .NET CLI. ```bash dotnet add package RtspClientSharp ``` -------------------------------- ### Connect and Receive RTSP Stream Source: https://context7.com/bogdanovkirill/rtspclientsharp/llms.txt Establishes an RTSP connection, subscribes to frame received events, and starts receiving media frames. Requires specifying the server URI and optionally credentials. Handles connection and RTSP-specific exceptions. ```csharp using System; using System.Net; using System.Threading; using System.Threading.Tasks; using RtspClientSharp; using RtspClientSharp.RawFrames; using RtspClientSharp.RawFrames.Video; using RtspClientSharp.RawFrames.Audio; using RtspClientSharp.Rtsp; class Program { static async Task Main() { var serverUri = new Uri("rtsp://192.168.1.77:554/stream1"); var credentials = new NetworkCredential("admin", "password123"); var connectionParameters = new ConnectionParameters(serverUri, credentials); using var cancellationTokenSource = new CancellationTokenSource(); using var rtspClient = new RtspClient(connectionParameters); // Subscribe to frame received event rtspClient.FrameReceived += (sender, frame) => { Console.WriteLine($"[{frame.Timestamp:HH:mm:ss.fff}] Received: {frame.GetType().Name}"); }; try { Console.WriteLine("Connecting to RTSP server..."); await rtspClient.ConnectAsync(cancellationTokenSource.Token); Console.WriteLine("Connected. Receiving frames..."); await rtspClient.ReceiveAsync(cancellationTokenSource.Token); } catch (OperationCanceledException) { Console.WriteLine("Operation was cancelled."); } catch (RtspClientException ex) { Console.WriteLine($"RTSP Error: {ex.Message}"); } } } ``` -------------------------------- ### Configure RtspClient Connection Parameters Source: https://context7.com/bogdanovkirill/rtspclientsharp/llms.txt Demonstrates various ways to configure RtspClient connection parameters, including URI-based credentials, explicit credentials, transport protocol, required tracks, timeouts, and custom user agents. Supports HTTP tunneling via the 'http://' scheme. ```csharp using System; using System.Net; using RtspClientSharp; // Basic connection with URI only (credentials extracted from URI) var uri1 = new Uri("rtsp://admin:password@192.168.1.77:554/stream"); var params1 = new ConnectionParameters(uri1); // Connection with explicit credentials var uri2 = new Uri("rtsp://192.168.1.77:554/stream"); var credentials = new NetworkCredential("admin", "password"); var params2 = new ConnectionParameters(uri2, credentials); // Full configuration with all options var connectionParams = new ConnectionParameters(uri2, credentials) { // Transport protocol: TCP (default) or UDP RtpTransport = RtpTransportProtocol.TCP, // Request only video track, audio track, or both RequiredTracks = RequiredTracks.Video, // Options: Video, Audio, All // Connection timeout (default: 30 seconds) ConnectTimeout = TimeSpan.FromSeconds(15), // Receive timeout - max time without frames before error (default: 10 seconds) ReceiveTimeout = TimeSpan.FromSeconds(20), // Cancel timeout - grace period for cancellation (default: 5 seconds) CancelTimeout = TimeSpan.FromSeconds(3), // Custom user agent string UserAgent = "MyApplication/1.0" }; // For HTTP tunneling, use http:// scheme var httpTunneledParams = new ConnectionParameters( new Uri("http://192.168.1.77:80/stream"), credentials ); ``` -------------------------------- ### Capture MJPEG Snapshots with RtspClientSharp Source: https://context7.com/bogdanovkirill/rtspclientsharp/llms.txt Captures periodic JPEG frames from an MJPEG stream and saves them to the local filesystem. Requires the RtspClientSharp library and appropriate directory permissions. ```csharp using System; using System.IO; using System.Threading; using System.Threading.Tasks; using RtspClientSharp; using RtspClientSharp.RawFrames.Video; class MjpegSnapshotMaker { public static async Task CaptureSnapshotsAsync( Uri rtspUri, string outputPath, int intervalSeconds, CancellationToken token) { Directory.CreateDirectory(outputPath); int intervalMs = intervalSeconds * 1000; int lastSaveTime = Environment.TickCount - intervalMs; var connectionParams = new ConnectionParameters(rtspUri) { RequiredTracks = RequiredTracks.Video, RtpTransport = RtpTransportProtocol.TCP }; using var rtspClient = new RtspClient(connectionParams); rtspClient.FrameReceived += (sender, frame) => { if (frame is not RawJpegFrame jpegFrame) return; int now = Environment.TickCount; if (Math.Abs(now - lastSaveTime) < intervalMs) return; lastSaveTime = now; string filename = $"snapshot_{jpegFrame.Timestamp:yyyyMMdd_HHmmss}.jpg"; string fullPath = Path.Combine(outputPath, filename); using var stream = File.OpenWrite(fullPath); stream.Write(jpegFrame.FrameSegment.Array, jpegFrame.FrameSegment.Offset, jpegFrame.FrameSegment.Count); Console.WriteLine($"Saved: {filename}"); }; await rtspClient.ConnectAsync(token); await rtspClient.ReceiveAsync(token); } } // Usage await MjpegSnapshotMaker.CaptureSnapshotsAsync( new Uri("rtsp://admin:pass@192.168.1.77:554/mjpeg"), @"C:\Snapshots", intervalSeconds: 5, CancellationToken.None ); ``` -------------------------------- ### RtspClient Class Source: https://context7.com/bogdanovkirill/rtspclientsharp/llms.txt The primary class for establishing connections to RTSP servers and receiving media frames asynchronously. ```APIDOC ## RtspClient ### Description The main entry point for establishing RTSP connections and receiving media frames from streaming devices. ### Methods - **ConnectAsync(CancellationToken token)**: Establishes the connection to the RTSP server. - **ReceiveAsync(CancellationToken token)**: Starts the asynchronous loop to receive media frames. ### Events - **FrameReceived**: Triggered when a new media frame (video or audio) is received from the server. ``` -------------------------------- ### ConnectionParameters Class Source: https://context7.com/bogdanovkirill/rtspclientsharp/llms.txt Configuration class used to define connection settings such as URI, credentials, transport protocols, and timeouts. ```APIDOC ## ConnectionParameters ### Description Configure connection settings including URI, credentials, transport protocol, timeouts, and track selection. ### Properties - **RtpTransport** (RtpTransportProtocol): Specifies TCP or UDP transport. - **RequiredTracks** (RequiredTracks): Specifies which tracks to request (Video, Audio, or All). - **ConnectTimeout** (TimeSpan): Connection timeout duration. - **ReceiveTimeout** (TimeSpan): Max time without frames before error. - **CancelTimeout** (TimeSpan): Grace period for cancellation. - **UserAgent** (string): Custom user agent string. ``` -------------------------------- ### Connect and Receive RTSP Stream in C# Source: https://github.com/bogdanovkirill/rtspclientsharp/blob/master/README.md Connect to an RTSP server and receive frames. Process received frames within the FrameReceived event handler. The frame buffer is reused, so make a deep copy if needed later. ```csharp var serverUri = new Uri("rtsp://192.168.1.77:554/ucast/11"); var credentials = new NetworkCredential("admin", "123456"); var connectionParameters = new ConnectionParameters(serverUri, credentials); connectionParameters.RtpTransport = RtpTransportProtocol.TCP; using(var rtspClient = new RtspClient(connectionParameters)) { rtspClient.FrameReceived += (sender, frame) => { //process (e.g. decode/save to file) encoded frame here or //make deep copy to use it later because frame buffer (see FrameSegment property) will be reused by client switch (frame) { case RawH264IFrame h264IFrame: case RawH264PFrame h264PFrame: case RawJpegFrame jpegFrame: case RawAACFrame aacFrame: case RawG711AFrame g711AFrame: case RawG711UFrame g711UFrame: case RawPCMFrame pcmFrame: case RawG726Frame g726Frame: break; } } await rtspClient.ConnectAsync(token); await rtspClient.ReceiveAsync(token); } ``` -------------------------------- ### Access RawFrame Properties Source: https://context7.com/bogdanovkirill/rtspclientsharp/llms.txt Demonstrates how to access common frame properties like timestamp and data. Note that the frame buffer is reused, so deep copies are required for asynchronous processing. ```csharp using System; using RtspClientSharp.RawFrames; rtspClient.FrameReceived += (sender, frame) => { // Common properties on all frames DateTime timestamp = frame.Timestamp; ArraySegment data = frame.FrameSegment; FrameType type = frame.Type; // Video or Audio // Access raw bytes byte[] rawBytes = new byte[data.Count]; Array.Copy(data.Array, data.Offset, rawBytes, 0, data.Count); Console.WriteLine($"Frame Type: {type}"); Console.WriteLine($"Timestamp: {timestamp:O}"); Console.WriteLine($"Size: {data.Count} bytes"); // IMPORTANT: Frame buffer is reused by the client! // Make a deep copy if you need to process the data later byte[] copiedData = data.ToArray(); }; ``` -------------------------------- ### Implement Automatic Reconnection Source: https://context7.com/bogdanovkirill/rtspclientsharp/llms.txt Provides a resilient wrapper for RtspClient to handle connection drops and authentication errors with retry logic. ```csharp using System; using System.Net; using System.Security.Authentication; using System.Threading; using System.Threading.Tasks; using RtspClientSharp; using RtspClientSharp.Rtsp; class ResilientRtspClient { private readonly ConnectionParameters _params; private readonly TimeSpan _retryDelay = TimeSpan.FromSeconds(5); public event EventHandler FrameReceived; public event EventHandler StatusChanged; public ResilientRtspClient(Uri uri, NetworkCredential credentials) { _params = new ConnectionParameters(uri, credentials) { RtpTransport = RtpTransportProtocol.TCP, ConnectTimeout = TimeSpan.FromSeconds(15), ReceiveTimeout = TimeSpan.FromSeconds(30) }; } public async Task RunAsync(CancellationToken token) { while (!token.IsCancellationRequested) { try { using var rtspClient = new RtspClient(_params); rtspClient.FrameReceived += (s, f) => FrameReceived?.Invoke(this, f); StatusChanged?.Invoke(this, "Connecting..."); await rtspClient.ConnectAsync(token); StatusChanged?.Invoke(this, "Receiving frames..."); await rtspClient.ReceiveAsync(token); } catch (OperationCanceledException) { StatusChanged?.Invoke(this, "Stopped"); return; } catch (InvalidCredentialException) { StatusChanged?.Invoke(this, "Invalid credentials"); await Task.Delay(_retryDelay, token); } catch (RtspClientException ex) { StatusChanged?.Invoke(this, $"Error: {ex.Message}"); await Task.Delay(_retryDelay, token); } } } } // Usage var client = new ResilientRtspClient( new Uri("rtsp://192.168.1.77:554/stream"), new NetworkCredential("admin", "password") ); client.FrameReceived += (s, frame) => Console.WriteLine($"Frame: {frame.GetType().Name}"); client.StatusChanged += (s, status) => Console.WriteLine($"Status: {status}"); using var cts = new CancellationTokenSource(); Console.CancelKeyPress += (s, e) => { e.Cancel = true; cts.Cancel(); }; await client.RunAsync(cts.Token); ``` -------------------------------- ### Process Audio Frames Source: https://context7.com/bogdanovkirill/rtspclientsharp/llms.txt Handle various audio codecs by accessing frame-specific metadata such as sample rates, channels, and configuration segments. ```csharp using System; using RtspClientSharp; using RtspClientSharp.RawFrames; using RtspClientSharp.RawFrames.Audio; rtspClient.FrameReceived += (sender, frame) => { switch (frame) { case RawAACFrame aacFrame: // AAC audio with configuration data Console.WriteLine($"AAC Frame: {aacFrame.FrameSegment.Count} bytes"); // Access AAC-specific configuration for decoder ArraySegment config = aacFrame.ConfigSegment; Console.WriteLine($"AAC Config: {config.Count} bytes"); break; case RawG711AFrame g711aFrame: // G.711 A-law (used in European telephony) Console.WriteLine($"G.711A Frame: {g711aFrame.FrameSegment.Count} bytes"); Console.WriteLine($"Sample Rate: {g711aFrame.SampleRate}, Channels: {g711aFrame.Channels}"); break; case RawG711UFrame g711uFrame: // G.711 mu-law (used in North American telephony) Console.WriteLine($"G.711U Frame: {g711uFrame.FrameSegment.Count} bytes"); Console.WriteLine($"Sample Rate: {g711uFrame.SampleRate}, Channels: {g711uFrame.Channels}"); break; case RawPCMFrame pcmFrame: // Raw PCM audio Console.WriteLine($"PCM Frame: {pcmFrame.FrameSegment.Count} bytes"); Console.WriteLine($"Sample Rate: {pcmFrame.SampleRate}"); Console.WriteLine($"Bits per Sample: {pcmFrame.BitsPerSample}"); Console.WriteLine($"Channels: {pcmFrame.Channels}"); break; case RawG726Frame g726Frame: // G.726 ADPCM audio Console.WriteLine($"G.726 Frame: {g726Frame.FrameSegment.Count} bytes"); Console.WriteLine($"Bits per Coded Sample: {g726Frame.BitsPerCodedSample}"); break; } }; ``` -------------------------------- ### Process Video Frames Source: https://context7.com/bogdanovkirill/rtspclientsharp/llms.txt Handle incoming video frames by switching on the frame type to extract H.264 NAL units or save MJPEG data to disk. ```csharp using System; using System.IO; using RtspClientSharp; using RtspClientSharp.RawFrames; using RtspClientSharp.RawFrames.Video; rtspClient.FrameReceived += (sender, frame) => { switch (frame) { case RawH264IFrame iFrame: // I-Frame (keyframe) with SPS/PPS data Console.WriteLine($"H.264 I-Frame: {iFrame.FrameSegment.Count} bytes"); // Access SPS/PPS for decoder initialization ArraySegment spsPps = iFrame.SpsPpsSegment; Console.WriteLine($"SPS/PPS: {spsPps.Count} bytes"); // Access NAL unit data byte[] nalData = new byte[iFrame.FrameSegment.Count]; Array.Copy(iFrame.FrameSegment.Array, iFrame.FrameSegment.Offset, nalData, 0, iFrame.FrameSegment.Count); break; case RawH264PFrame pFrame: // P-Frame (predicted frame) Console.WriteLine($"H.264 P-Frame: {pFrame.FrameSegment.Count} bytes"); break; case RawJpegFrame jpegFrame: // MJPEG frame - complete JPEG image Console.WriteLine($"JPEG Frame: {jpegFrame.FrameSegment.Count} bytes"); // Save JPEG directly to file string filename = $"snapshot_{jpegFrame.Timestamp:yyyyMMdd_HHmmss_fff}.jpg"; using (var stream = File.OpenWrite(filename)) { stream.Write(jpegFrame.FrameSegment.Array, jpegFrame.FrameSegment.Offset, jpegFrame.FrameSegment.Count); } break; } }; ``` -------------------------------- ### Handle RTSP Exceptions Source: https://context7.com/bogdanovkirill/rtspclientsharp/llms.txt Implements robust error management for RTSP connections, covering authentication, timeouts, and protocol-specific errors. ```csharp using System; using System.Security.Authentication; using System.Threading; using System.Threading.Tasks; using RtspClientSharp; using RtspClientSharp.Rtsp; async Task ConnectWithErrorHandlingAsync(ConnectionParameters connectionParams, CancellationToken token) { using var rtspClient = new RtspClient(connectionParams); try { await rtspClient.ConnectAsync(token); await rtspClient.ReceiveAsync(token); } catch (OperationCanceledException) { // User requested cancellation Console.WriteLine("Connection cancelled by user."); } catch (InvalidCredentialException) { // Wrong username or password Console.WriteLine("Authentication failed. Check credentials."); } catch (RtspClientException ex) when (ex.InnerException is TimeoutException) { // Connection or receive timeout Console.WriteLine($"Timeout: {ex.Message}"); } catch (RtspClientException ex) { // Other RTSP protocol errors Console.WriteLine($"RTSP Error: {ex.Message}"); if (ex.InnerException != null) Console.WriteLine($"Inner: {ex.InnerException.Message}"); } catch (InvalidOperationException ex) { // Called ReceiveAsync before ConnectAsync Console.WriteLine($"Invalid operation: {ex.Message}"); } } ``` -------------------------------- ### Configure RequiredTracks Enum Source: https://context7.com/bogdanovkirill/rtspclientsharp/llms.txt Use the RequiredTracks enum to specify which media streams to request from the server. Flags can be combined using bitwise OR operators. ```csharp using RtspClientSharp; // Receive all available tracks (video + audio) var allTracks = new ConnectionParameters(uri) { RequiredTracks = RequiredTracks.All }; // Receive only video track var videoOnly = new ConnectionParameters(uri) { RequiredTracks = RequiredTracks.Video }; // Receive only audio track var audioOnly = new ConnectionParameters(uri) { RequiredTracks = RequiredTracks.Audio }; // Combine flags for specific tracks var videoAndAudio = new ConnectionParameters(uri) { RequiredTracks = RequiredTracks.Video | RequiredTracks.Audio }; ``` -------------------------------- ### Configure RTP Transport Protocol Source: https://context7.com/bogdanovkirill/rtspclientsharp/llms.txt Specifies the transport protocol for RTP media streaming. TCP is more reliable and works through firewalls, while UDP offers lower latency but may experience packet loss. ```csharp using RtspClientSharp; // TCP transport - more reliable, works through firewalls var tcpParams = new ConnectionParameters(new Uri("rtsp://camera/stream")) { RtpTransport = RtpTransportProtocol.TCP }; // UDP transport - lower latency, may have packet loss var udpParams = new ConnectionParameters(new Uri("rtsp://camera/stream")) { RtpTransport = RtpTransportProtocol.UDP }; ``` -------------------------------- ### RtpTransportProtocol Enum Source: https://context7.com/bogdanovkirill/rtspclientsharp/llms.txt Defines the transport protocols supported by the library for RTP media streaming. ```APIDOC ## RtpTransportProtocol ### Description Specify the transport protocol for RTP media streaming. ### Values - **TCP**: More reliable, works through firewalls. - **UDP**: Lower latency, may have packet loss. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.