V4L2 and zig: match made in heaven

Hi everyone,

I’ve started looking into zig 6 months ago and decided to code a video for linux library

https://codeberg.org/tiagocoutinho/v4l2.zig

I was really impressed how I could stream a video camera in zig without even needing an allocator:

const std = @import("std");
const v4l2 = @import("v4l2");      // Import the v4l2 module
const Device = v4l2.Device,        // Some helpers
const Capture = v4l2.Capture;

pub fn main() !void {
    const dev = try Device.fromId(0);          // Create the device
    defer dev.deinit();                        // Make sure to cleanup at the end
    const capture = Capture.init(dev);         // Get the video capture interface  
    try capture.setFormat(640, 480, .grey);    // Set the capture format
    try capture.setFPS(10);                    // Set the capture speed

    const stream = try capture.arm(2, .mmap);  // Arm the device. Get a reference to the stream 
    defer stream.deinit();                     // Make sure to cleanup at the end
    
    try stream.start();                        // Start the stream
    while (true) {
        var frame = try stream.next();         // Wait for a frame
        defer stream.free(&frame) catch {};    // Give back the frame when we're done with it
        std.debug.print("{f}\n", .{frame});    // Basic formatting
    }
}

Hope someone finds it useful.

Currently I’m looking at zig 0.16 async I/O and trying to find an elegant solution to make this library work with it. I know I should open de video file with O_NONBLOCK but I haven’t found a neet way to integrate. Looking for feedback/ideas

11 Likes

Hey great code, I’m also experimenting with v4l2, I have already deployed a full DMA computer vision / libcamera replacement at work sadly in C, and I’m also waiting for 0.16 to drop before trying to build a Zig version, I really like your code, and will definitely read it more, v4l2 is a really elegant API, but it’s quite brittle and really needs precision, would love to try the new ioctl and Io integration with it, and see if it’s missing something. Would love to see how to make the DMA work with multiple ISP too.

1 Like