Getting recording to work with multiple USB cameras using C# .NET on Raspberry Pi 5

Marco Enxuto 326 Reputation points
2024-03-04T23:05:03.5+00:00

Hello,

I have a question opened on the Raspberry Pi forum but I don't seem much of activity there, especially regarding .NET IoT on ARM.

I follow this article https://neilsnotes.net/Software/Coding/dotnetPiCam.html and I simply don't understand why the recording is not working as expected. Also, I find the implementation using Windows much simpler. If on Windows we just need to call the MediaCapture class to manage everything related with cameras.

Currently, I'm trying to record with only one camera, to troubleshoot why this is not working as expected.

I can take pictures, but video I cannot get it work properly. It seems something related to encoding. Don't understand what, but I installed the v4l-utils, libc6-dev, libx11-dev on the device.

The file is being populated with still image, and after I pull out the file from the Pi, I checked the metadata properties, and It says JPEG. Weird.

Here's the code I used on my .NET 8 console app project:

using System.Device.Gpio;
using Iot.Device.Graphics;
using Iot.Device.Media;

Console.WriteLine("Initializing capturing...");
VideoConnectionSettings videoConnectionSettings = new VideoConnectionSettings(0, (1920, 1080), VideoPixelFormat.H264);
VideoDevice videoDevice = VideoDevice.Create(videoConnectionSettings);
FileStream fileStream = File.Create("/home/marco/CameraRecorderPOC/test.h264");
videoDevice.NewImageBufferReady += VideoDevice_NewImageBufferReady;
videoDevice.StartCaptureContinuous();
CancellationTokenSource tokenSource = new CancellationTokenSource();
new Thread(() => { videoDevice.CaptureContinuous(tokenSource.Token); }).Start();
Console.WriteLine("Capturing video, press any key to stop");
//...code omitted for brevity....
while (!Console.KeyAvailable)
{
    Thread.SpinWait(1);
}
tokenSource.Cancel();
videoDevice.StopCaptureContinuous();
fileStream.Close();
fileStream.Dispose();
videoDevice.Dispose();
async void VideoDevice_NewImageBufferReady(object sender, NewImageBufferReadyEventArgs e)
{
    try
    {
        await fileStream.WriteAsync(e.ImageBuffer, 0, e.Length);
        Console.Write(".");
    }
    catch (ObjectDisposedException ex)
    {
        Console.WriteLine("\nException thrown: {0}", ex.Message);
        // ignore this as its thrown when the stream is stopped
    }
}
.NET Internet of things
.NET Internet of things
.NET: Microsoft Technologies based on the .NET software framework.Internet of things: A concept that aims to extend the benefits of the regular internet, including constant connectivity, remote control ability, and data sharing, to goods in the physical world.
28 questions
0 comments No comments
{count} votes