Sunday, November 24, 2024
0 comments

LIVE Web camera Streaming in Web Browser using RTSP protocol and ASP.NET

4:51 PM



Streaming live video from an RTSP camera in a web browser using ASP.NET requires converting the RTSP stream into a format that browsers can natively support, such as HLS (HTTP Live Streaming) or WebRTC, as most browsers do not natively support RTSP streams. 

Here's a step-by-step detailed guide:


1. Understanding the Workflow

  1. RTSP Stream: The live video feed from the camera is available in RTSP protocol.
  2. Transcoding: Use a tool like FFmpeg or a media server like GStreamer, VLC, or Wowza to transcode the RTSP stream into HLS or WebRTC.
  3. ASP.NET Backend: Manage and serve the stream or its metadata (e.g., the HLS playlist or WebRTC signaling).
  4. Browser Frontend: Use HTML5 <video> tag for HLS or a WebRTC player (e.g., simple-peer) for WebRTC.

2. 

1. Setup Requirements

Install Prerequisites

  1. FFmpeg:

    • Download from FFmpeg official site and add it to your system's PATH.
    • This tool will convert RTSP to HLS.
  2. Visual Studio:

    • Install ASP.NET Core development environment.
  3. RTSP Camera:

    • Obtain the RTSP URL of your camera.
  4. hls.js (Frontend Player):

    • Include the hls.js library for HLS playback in browsers that do not support it natively.

2. RTSP to HLS Conversion

Use FFmpeg to convert the RTSP stream to HLS format.

Command to Run FFmpeg:

ffmpeg -i rtsp://<camera-ip>:<port>/<stream> \
    -f hls \
    -hls_time 2 \
    -hls_list_size 3 \
    -hls_wrap 5 \
    -hls_segment_filename "wwwroot/streams/segment_%d.ts" \
    wwwroot/streams/stream.m3u8

Parameters:
  • -i: RTSP URL of the camera.
  • -f hls: Specifies the HLS output format.
  • -hls_time 2: Sets the duration of each HLS segment (in seconds).
  • -hls_list_size 3: Limits the number of playlist entries.
  • -hls_wrap 5: Rotates segment files to avoid storage issues.
  • wwwroot/streams/: Output directory for .m3u8 and .ts files.

3. Create ASP.NET Core Application

Step 1: Create a New Project

  1. Open Visual Studio.
  2. Create a new ASP.NET Core Web Application.
  3. Select Empty Template and click Create.

Step 2: Configure Static Files for HLS

Add the HLS files (.m3u8 and .ts) to the wwwroot/streams directory.

  1. Open Program.cs and configure static file support:var builder = WebApplication.CreateBuilder(args);

    var app = builder.Build();

    // Enable Static Files for Serving HLS

    app.UseStaticFiles();

    app.MapGet("/", () => Results.Redirect("/index.html"));

    app.Run();

2. Ensure HLS files are stored in wwwroot/streams.

Step 3: Add Controller for Stream API

Create a controller to serve the stream files dynamically.

  1. Add a new folder Controllers and create StreamController.cs:


    using Microsoft.AspNetCore.Mvc; [Route("api/stream")] public class StreamController : Controller { [HttpGet("{fileName}")] public IActionResult GetStream(string fileName) { var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "streams", fileName); if (!System.IO.File.Exists(filePath)) return NotFound(); var contentType = fileName.EndsWith(".m3u8") ? "application/vnd.apple.mpegurl" : "video/MP2T"; return PhysicalFile(filePath, contentType); } }
  2. This API serves .m3u8 and .ts files dynamically based on the request.

Step 3: Add Controller for Stream API

Create a controller to serve the stream files dynamically.

  1. Add a new folder Controllers and create StreamController.cs:

    using Microsoft.AspNetCore.Mvc; [Route("api/stream")] public class StreamController : Controller { [HttpGet("{fileName}")] public IActionResult GetStream(string fileName) { var filePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "streams", fileName); if (!System.IO.File.Exists(filePath)) return NotFound(); var contentType = fileName.EndsWith(".m3u8") ? "application/vnd.apple.mpegurl" : "video/MP2T"; return PhysicalFile(filePath, contentType); } }
  2. This API serves .m3u8 and .ts files dynamically based on the request.


4. Frontend: HTML Player for Streaming

Create a basic HTML page to play the stream.

HTML File (wwwroot/index.html):


<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Live Camera Stream</title> <script src="https://cdn.jsdelivr.net/npm/hls.js@latest"></script> </head> <body> <div class="container"> <h1>Live Camera Stream</h1> <video id="videoPlayer" controls autoplay style="width: 100%; max-width: 800px;"> Your browser does not support the video tag. </video> </div> <script> document.addEventListener("DOMContentLoaded", () => { const video = document.getElementById("videoPlayer"); const videoSrc = "/streams/stream.m3u8"; if (Hls.isSupported()) { const hls = new Hls(); hls.loadSource(videoSrc); hls.attachMedia(video); hls.on(Hls.Events.MANIFEST_PARSED, () => { video.play(); }); } else if (video.canPlayType('application/vnd.apple.mpegurl')) { video.src = videoSrc; video.addEventListener('loadedmetadata', () => { video.play(); }); } else { console.error("HLS is not supported in this browser."); } }); </script> </body> </html>

5. Run the Application

  1. Start the FFmpeg command to convert RTSP to HLS.
  2. Run the ASP.NET Core application in Visual Studio.
  3. Navigate to http://localhost:5000/ in your browser.
  4. The browser should display the live video stream.

6. Deploy the Application

  1. Deploy the application to IIS or a cloud service like Azure App Service.
  2. Ensure the FFmpeg process runs continuously on the server to transcode RTSP streams.

7. Optional: Automate FFmpeg with ASP.NET

You can automate the FFmpeg process using Process.Start in C#:

Code to Start FFmpeg:


using System.Diagnostics; public class FfmpegService { public void StartTranscoding() { var ffmpegPath = @"C:\path\to\ffmpeg.exe"; var arguments = @"-i rtsp://<camera-ip>:<port>/<stream> -f hls -hls_time 2 -hls_list_size 3 -hls_wrap 5 -hls_segment_filename ""wwwroot/streams/segment_%d.ts"" wwwroot/streams/stream.m3u8"; var processStartInfo = new ProcessStartInfo { FileName = ffmpegPath, Arguments = arguments, RedirectStandardOutput = true, UseShellExecute = false, CreateNoWindow = true }; Process.Start(processStartInfo); } }

Call this method in the application startup.


8. Additional Considerations

  • Performance: For multiple cameras, ensure the server has sufficient resources.
  • Security: Protect the stream API if needed.
  • Low Latency: Consider WebRTC for lower latency if required.

Thank You

0 comments:

 
Toggle Footer