📄 sink/src/loopback.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473
//! The v4l2loopback virtual webcam (PLAN.md, pipeline step 5 — the
//! Linux sink).
//!
//! Rendered virtual-camera frames are converted to YUYV and written to
//! a [v4l2loopback](https://github.com/v4l2loopback/v4l2loopback)
//! device, which conferencing tools (Teams, Slack, Chrome) then pick
//! up as an ordinary webcam.
//!
//! The device half is Linux-only; everything else — the RGBA→YUYV
//! conversion, the latest-frame handoff, the error handling — is
//! cross-platform and unit-tested. Creating an actual `/dev/video*`
//! device needs the v4l2loopback kernel module, which this container
//! cannot load; the device paths are exercised on a real machine.
//!
//! Typical setup (the `exclusive_caps` mode is what makes
//! Chrome-based consumers see the device):
//!
//! ```text
//! sudo apt install v4l2loopback-dkms
//! sudo modprobe v4l2loopback video_nr=10 card_label="kinect-view" exclusive_caps=1
//! kinect-view --loopback-path /dev/video10
//! ```

use std::path::Path;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread::JoinHandle;

#[cfg(target_os = "linux")]
use anyhow::Context;
use anyhow::{Result, ensure};

use render::RenderedImage;

/// One pending frame handed to the writer thread.
struct PendingFrame {
    rgba: Arc<[u8]>,
    width: u32,
    height: u32,
}

/// Where converted frames go: the v4l2loopback device, or a test
/// collector.
pub trait LoopbackWriter: Send + 'static {
    /// Write one YUYV frame — exactly `width * height * 2` bytes.
    fn write_frame(&mut self, yuyv: &[u8], width: u32, height: u32) -> Result<()>;
}

/// The loopback sink: receives rendered frames, converts them, and
/// writes them out — on the caller's thread ([`LoopbackSink::with_writer`])
/// or on a dedicated writer thread with latest-frame semantics
/// ([`LoopbackSink::open`], so a slow device never stalls the UI).
pub struct LoopbackSink {
    mode: Mode,
}

enum Mode {
    /// Writes on the calling thread (tests, tools).
    Inline(Box<dyn LoopbackWriter>),
    /// The caller stores the latest frame; a writer thread converts and
    /// writes it.
    Threaded {
        latest: Arc<Mutex<Option<PendingFrame>>>,
        error: Arc<Mutex<Option<String>>>,
        shutdown: Arc<AtomicBool>,
        worker: Option<JoinHandle<()>>,
    },
}

impl LoopbackSink {
    /// Open the v4l2loopback output device at `path` and negotiate a
    /// YUYV format at `width x height`.
    ///
    /// The device must report video-output capability (with
    /// `exclusive_caps=1`, that is the *unattached* state — once this
    /// sink produces, the device announces capture capability for the
    /// conferencing tool). Fails clearly on Linux when the device is
    /// absent, not a V4L2 output device, or refuses the format — and
    /// on every non-Linux platform.
    pub fn open(path: impl AsRef<Path>, width: u32, height: u32) -> Result<Self> {
        let writer = open_device_writer(path.as_ref(), width, height)?;
        Ok(Self::threaded(writer))
    }

    /// A sink writing to an arbitrary [`LoopbackWriter`] on the calling
    /// thread — primarily for tests.
    pub fn with_writer(writer: Box<dyn LoopbackWriter>) -> Self {
        Self {
            mode: Mode::Inline(writer),
        }
    }

    /// Is the sink still active? (A writer failure disables it.)
    pub fn is_active(&self) -> bool {
        match &self.mode {
            Mode::Inline(_) => true,
            Mode::Threaded { error, .. } => error.lock().unwrap().is_none(),
        }
    }

    /// Push one rendered frame. Cheap: with a real device this only
    /// stores the latest frame; conversion and writing happen on the
    /// writer thread.
    pub fn push(&mut self, image: &RenderedImage) -> Result<()> {
        match &mut self.mode {
            Mode::Inline(writer) => {
                let yuyv = rgba_to_yuyv(&image.rgba, image.width, image.height)?;
                writer.write_frame(&yuyv, image.width, image.height)
            }
            Mode::Threaded { latest, error, .. } => {
                if let Some(error) = error.lock().unwrap().take() {
                    anyhow::bail!("loopback writer failed: {error}");
                }
                let frame = PendingFrame {
                    rgba: Arc::from(image.rgba.as_slice()),
                    width: image.width,
                    height: image.height,
                };
                *latest.lock().unwrap() = Some(frame);
                Ok(())
            }
        }
    }

    /// Build the threaded sink and start its writer loop.
    fn threaded(writer: Box<dyn LoopbackWriter>) -> Self {
        let latest = Arc::new(Mutex::new(None::<PendingFrame>));
        let error = Arc::new(Mutex::new(None::<String>));
        let shutdown = Arc::new(AtomicBool::new(false));

        let worker = {
            let latest = latest.clone();
            let error = error.clone();
            let shutdown = shutdown.clone();
            std::thread::spawn(move || {
                let mut writer = writer;
                loop {
                    if shutdown.load(Ordering::Relaxed) {
                        break;
                    }
                    let frame = latest.lock().unwrap().take();
                    let Some(frame) = frame else {
                        std::thread::sleep(std::time::Duration::from_millis(5));
                        continue;
                    };
                    let result = (|| -> Result<()> {
                        let yuyv = rgba_to_yuyv(&frame.rgba, frame.width, frame.height)?;
                        writer.write_frame(&yuyv, frame.width, frame.height)
                    })();
                    if let Err(e) = result {
                        *error.lock().unwrap() = Some(format!("{e:#}"));
                        break;
                    }
                }
            })
        };

        Self {
            mode: Mode::Threaded {
                latest,
                error,
                shutdown,
                worker: Some(worker),
            },
        }
    }
}

impl Drop for LoopbackSink {
    fn drop(&mut self) {
        if let Mode::Threaded {
            shutdown, worker, ..
        } = &mut self.mode
        {
            shutdown.store(true, Ordering::Relaxed);
            if let Some(worker) = worker.take() {
                let _ = worker.join();
            }
        }
    }
}

/// Convert an RGBA8 frame to YUYV (packed YUV 4:2:2): full-range
/// BT.601, the convention virtual-webcam consumers expect. Alpha is
/// ignored — rendered frames are already composited over the
/// background.
///
/// Layout: `[Y0, U, Y1, V]` per horizontal pixel pair, the chroma
/// averaged over the pair.
pub fn rgba_to_yuyv(rgba: &[u8], width: u32, height: u32) -> Result<Vec<u8>> {
    ensure!(
        width.is_multiple_of(2),
        "YUYV needs an even width, got {width}"
    );
    let pixel_count = width as usize * height as usize;
    ensure!(
        rgba.len() == pixel_count * 4,
        "expected {pixel_count} RGBA pixels, got {}",
        rgba.len() / 4
    );

    let mut yuyv = vec![0_u8; pixel_count * 2];
    for pair in 0..(width as usize * height as usize) / 2 {
        // The pixel pair this YUYV quartet covers.
        let px = pair * 2;
        let i = px * 4;
        let (r0, g0, b0) = (rgba[i] as f32, rgba[i + 1] as f32, rgba[i + 2] as f32);
        let (r1, g1, b1) = (rgba[i + 4] as f32, rgba[i + 5] as f32, rgba[i + 6] as f32);

        // BT.601 full range. Chroma is linear in RGB, so averaging the
        // pair's RGB is exactly averaging the pair's chroma.
        let y0 = clamp_u8(0.299 * r0 + 0.587 * g0 + 0.114 * b0 + 0.5);
        let y1 = clamp_u8(0.299 * r1 + 0.587 * g1 + 0.114 * b1 + 0.5);
        let (ra, ga, ba) = ((r0 + r1) * 0.5, (g0 + g1) * 0.5, (b0 + b1) * 0.5);
        let u = clamp_u8(-0.168_736 * ra - 0.331_264 * ga + 0.5 * ba + 128.5);
        let v = clamp_u8(0.5 * ra - 0.418_688 * ga - 0.081_312 * ba + 128.5);

        let o = pair * 4;
        yuyv[o] = y0;
        yuyv[o + 1] = u;
        yuyv[o + 2] = y1;
        yuyv[o + 3] = v;
    }
    Ok(yuyv)
}

fn clamp_u8(x: f32) -> u8 {
    x.clamp(0.0, 255.0) as u8
}

/// Open the v4l2loopback device writer. Linux only — elsewhere the
/// sink does not exist and the configuration is rejected up front.
#[cfg(target_os = "linux")]
fn open_device_writer(path: &Path, width: u32, height: u32) -> Result<Box<dyn LoopbackWriter>> {
    use std::fs::OpenOptions;

    use v4l2r::ioctl::{Capabilities, s_fmt};
    use v4l2r::{Format, PixelFormat, PlaneLayout, QueueType};

    let mut file = OpenOptions::new()
        .write(true)
        .open(path)
        .with_context(|| format!("opening {}", path.display()))?;

    // It must be an output device.
    let capability = query_capabilities(&mut file, path)?;
    if !capability
        .device_caps()
        .contains(Capabilities::VIDEO_OUTPUT)
    {
        anyhow::bail!(
            "{} does not accept video output. With exclusive_caps=1, pass the \
             v4l2loopback device *before* a producer attaches (it announces \
             output capability only until then)",
            path.display()
        );
    }

    // Negotiate YUYV at the render size.
    let frame_bytes = width as usize * height as usize * 2;
    let format = Format {
        width,
        height,
        pixelformat: PixelFormat::from_fourcc(b"YUYV"),
        plane_fmt: vec![PlaneLayout {
            bytesperline: width * 2,
            sizeimage: (frame_bytes) as u32,
        }],
    };
    let negotiated: Format = s_fmt(&mut file, (QueueType::VideoOutput, &format))
        .with_context(|| format!("negotiating the output format on {}", path.display()))?;
    if negotiated.width != width
        || negotiated.height != height
        || negotiated.pixelformat != format.pixelformat
    {
        anyhow::bail!(
            "{} refused the format: asked for YUYV {width}x{height}, got {:?} {}x{} \
             (the device was probably created with fixed dimensions — reload \
             the module or set them accordingly)",
            path.display(),
            negotiated.pixelformat.to_fourcc(),
            negotiated.width,
            negotiated.height
        );
    }

    Ok(Box::new(DeviceWriter {
        file,
        width,
        height,
        frame_bytes,
    }))
}

#[cfg(target_os = "linux")]
fn query_capabilities(file: &mut std::fs::File, path: &Path) -> Result<v4l2r::ioctl::Capability> {
    use v4l2r::ioctl::{QueryCapError, querycap};

    match querycap(file) {
        Ok(capability) => Ok(capability),
        Err(QueryCapError::IoctlError(e)) => {
            anyhow::bail!("{} is not a V4L2 device ({e})", path.display())
        }
    }
}

#[cfg(not(target_os = "linux"))]
fn open_device_writer(_path: &Path, _width: u32, _height: u32) -> Result<Box<dyn LoopbackWriter>> {
    anyhow::bail!("the v4l2loopback sink is Linux-only")
}

/// The Linux device writer: frames go out with plain `write()`, one
/// YUYV frame per call.
#[cfg(target_os = "linux")]
struct DeviceWriter {
    file: std::fs::File,
    width: u32,
    height: u32,
    frame_bytes: usize,
}

#[cfg(target_os = "linux")]
impl LoopbackWriter for DeviceWriter {
    fn write_frame(&mut self, yuyv: &[u8], width: u32, height: u32) -> Result<()> {
        use std::io::Write;
        ensure!(
            width == self.width && height == self.height,
            "frame size changed: wrote {}x{}, now {width}x{height}",
            self.width,
            self.height
        );
        ensure!(
            yuyv.len() == self.frame_bytes,
            "expected a {}-byte frame, got {}",
            self.frame_bytes,
            yuyv.len()
        );
        self.file
            .write_all(yuyv)
            .context("writing the frame (was the device removed?)")
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// A writer that records everything it receives.
    struct Collector {
        frames: CollectedFrames,
    }

    /// What the collector writer received: `(yuyv, width, height)` per
    /// frame.
    type CollectedFrames = Arc<Mutex<Vec<(Vec<u8>, u32, u32)>>>;

    impl LoopbackWriter for Collector {
        fn write_frame(&mut self, yuyv: &[u8], width: u32, height: u32) -> Result<()> {
            self.frames
                .lock()
                .unwrap()
                .push((yuyv.to_vec(), width, height));
            Ok(())
        }
    }

    /// A writer that always fails.
    struct Failing;

    impl LoopbackWriter for Failing {
        fn write_frame(&mut self, _: &[u8], _: u32, _: u32) -> Result<()> {
            anyhow::bail!("writer exploded")
        }
    }

    fn image(width: u32, height: u32, rgba: &[u8]) -> RenderedImage {
        RenderedImage {
            width,
            height,
            rgba: rgba.to_vec(),
        }
    }

    #[test]
    fn yuyv_known_colours() {
        // BT.601 full range: Y' = 0.299R + 0.587G + 0.114B. Chroma
        // belongs to a pixel *pair*: computed from their average RGB.

        // A 2x1 image: red | white.
        let rgba = [255, 0, 0, 255, 255, 255, 255, 255];
        let out = rgba_to_yuyv(&rgba, 2, 1).expect("converts");
        assert_eq!(out.len(), 4);
        // Luma per pixel: red ≈ 76, white = 255.
        assert_eq!(out[0], 76);
        assert_eq!(out[2], 255);
        // Chroma of the red|white pair: averaged RGB (255, 127.5, 127.5)
        // → U ≈ 107, V ≈ 192.
        assert_eq!(out[1], 106);
        assert_eq!(out[3], 192);

        // Black is neutral: Y 0, U/V 128.
        let out = rgba_to_yuyv(&[0, 0, 0, 255, 0, 0, 0, 255], 2, 1).expect("converts");
        assert_eq!(out, vec![0, 128, 0, 128]);

        // Odd width is rejected.
        assert!(rgba_to_yuyv(&[0, 0, 0, 255], 1, 1).is_err());
        // Wrong buffer length is rejected.
        assert!(rgba_to_yuyv(&[0; 7], 2, 1).is_err());
    }

    #[test]
    fn inline_sink_pushes_converted_frames() {
        let frames = Arc::new(Mutex::new(Vec::new()));
        let mut sink = LoopbackSink::with_writer(Box::new(Collector {
            frames: frames.clone(),
        }));

        // A 2x2 red frame.
        let rgba = [255, 0, 0, 255].repeat(4);
        sink.push(&image(2, 2, &rgba)).expect("push");
        sink.push(&image(2, 2, &rgba)).expect("push");

        let frames = frames.lock().unwrap();
        assert_eq!(frames.len(), 2, "every pushed frame is written");
        for (yuyv, w, h) in frames.iter() {
            assert_eq!((*w, *h), (2, 2));
            assert_eq!(yuyv.len(), 2 * 2 * 2);
            // All red: each pixel pair is one YUYV quartet
            // [Y0, U, Y1, V] = [76, 85, 76, 255]; two rows.
            assert_eq!(yuyv, &[76, 85, 76, 255, 76, 85, 76, 255]);
        }
    }

    #[test]
    fn writer_errors_disable_the_sink() {
        let mut sink = LoopbackSink::with_writer(Box::new(Failing));
        let rgba = [0, 0, 0, 255].repeat(4);
        assert!(sink.push(&image(2, 2, &rgba)).is_err());
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn device_open_failures_are_clear() {
        // A nonexistent path.
        let err = match LoopbackSink::open("/nonexistent/video", 640, 480) {
            Ok(_) => panic!("opened a nonexistent device?"),
            Err(e) => e,
        };
        assert!(err.to_string().contains("opening"), "got: {err:#}");

        // A file that is not a V4L2 device.
        let err = match LoopbackSink::open("/dev/null", 640, 480) {
            Ok(_) => panic!("/dev/null is not a video device"),
            Err(e) => e,
        };
        assert!(
            err.to_string().contains("not a V4L2 device"),
            "got: {err:#}"
        );
    }

    #[cfg(not(target_os = "linux"))]
    #[test]
    fn device_open_fails_off_linux() {
        let err = match LoopbackSink::open("/dev/video0", 640, 480) {
            Ok(_) => panic!("opened a loopback device off Linux?"),
            Err(e) => e,
        };
        assert!(err.to_string().contains("Linux-only"));
    }
}