I have a webcam sitting on a network with low bandwith and I need to create an api endpoint in order to broadcast the video stream to many clients. So far I have been able to do so, the only issue is that for each request, my controller opens up a new stream to the webcam and forwards it to the client.
What I would like to do is to have a single stream/webcam service accessing the webcam and have the listeners access to the same stream, but I wasn't able to find information online regarding a Stream with multiple listeners. Is this feasible?
Here's the code I am using
[ApiController]
[Route("[controller]")]
public class Webcam : ControllerBase
{
private readonly ILogger<Webcam> _logger;
public Webcam(ILogger<Webcam> logger)
{
_logger = logger;
_stream = new Lazy<Task<Stream>>
(
GetStream,
true
);
}
private Task<Stream> GetStream()
{
_logger.LogInformation("Opening stream");
return _cli.Value.GetStreamAsync(WebCamUrl);
}
static readonly Lazy<HttpClient> _cli = new();
const string WebCamUrl = "http://172.31.11.21/mjpg/video.mjpg?camera=3";
public readonly Lazy<Task<Stream>> _stream;
[HttpGet]
public async Task<IActionResult> Test()
{
var result = new FileStreamResult(await _stream.Value, "multipart/x-mixed-replace;boundary=myboundary")
{
EnableRangeProcessing = true
};
return result;
}
}