To consume an RTSP stream, follow these steps:
- Create a
Uri for the RTSP server. - Create
NetworkCredential if authentication is required. - Initialize
ConnectionParameters with the URI and credentials. - Set the
RtpTransport protocol (e.g., RtpTransportProtocol.TCP). - Instantiate
RtspClient with the parameters. - Subscribe to the
FrameReceived event to handle incoming media frames. - Call
ConnectAsync and ReceiveAsync to start the session.
Important Note on Memory Management:
The frame object in the FrameReceived event uses a buffer (accessible via the FrameSegment property) that is reused by the client to minimize GC pressure. If you need to process the frame asynchronously or use it after the event handler returns, you must make a deep copy of the frame data.
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);
}