lactea-host 0.3.1

Host-side helpers for embedding lactea: directory texture provider, image decoding, headless GPU setup, non-blocking frame read-back, rendering on the host's own Vulkan or Metal device, WAV reading.
Documentation
//! RGBA8 read-back of rendered frames without stalling on the GPU.
//!
//! A [`FrameReader`] owns a small ring of staging buffers. Each frame records a copy of the target
//! into a free buffer ([`FrameReader::copy`]); after the submit, [`FrameReader::submitted`] asks for
//! the buffer to be mapped, and [`FrameReader::read_latest`] later hands out the newest frame the GPU
//! has finished, without waiting. That costs one or two frames of latency instead of a full GPU
//! round trip per frame, and works in the browser too (wgpu maps buffers from the event loop there).
//! [`FrameReader::read_blocking`] waits instead, for hosts that want the frame they just rendered.

use std::sync::Arc;
use std::sync::atomic::{AtomicU8, Ordering};

/// Free: may receive the next copy.
const IDLE: u8 = 0;
/// A copy was recorded; the map is requested by [`FrameReader::submitted`].
const COPIED: u8 = 1;
/// Mapping requested, not finished yet.
const PENDING: u8 = 2;
/// Mapped: holds a finished frame.
const MAPPED: u8 = 3;
/// The map failed; the buffer is not mapped.
const FAILED: u8 = 4;

struct Slot {
    buffer: wgpu::Buffer,
    /// Set by the map callback, which may run on another thread.
    state: Arc<AtomicU8>,
    /// Sequence number of the frame copied into it.
    frame: u64,
}

/// Ring of staging buffers reading back a `width` x `height` target with 4 bytes per texel
/// (`Rgba8Unorm`, `Bgra8Unorm`, ...). Make a new one when the size changes.
pub struct FrameReader {
    width: u32,
    height: u32,
    /// Row pitch in the staging buffers (`COPY_BYTES_PER_ROW_ALIGNMENT`-aligned).
    padded_row: u32,
    slots: Vec<Slot>,
    /// Frames copied so far; the next copy gets this number.
    next_frame: u64,
}

impl FrameReader {
    /// A reader with `depth` staging buffers (at least 1; 3 keeps the GPU busy without dropping
    /// frames at a steady frame rate).
    pub fn new(device: &wgpu::Device, width: u32, height: u32, depth: usize) -> Self {
        let padded_row = (width * 4).div_ceil(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT)
            * wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
        let slots = (0..depth.max(1))
            .map(|_| Slot {
                buffer: device.create_buffer(&wgpu::BufferDescriptor {
                    label: Some("lactea readback"),
                    size: u64::from(padded_row) * u64::from(height),
                    usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
                    mapped_at_creation: false,
                }),
                state: Arc::new(AtomicU8::new(IDLE)),
                frame: 0,
            })
            .collect();
        Self {
            width,
            height,
            padded_row,
            slots,
            next_frame: 0,
        }
    }

    pub fn width(&self) -> u32 {
        self.width
    }

    pub fn height(&self) -> u32 {
        self.height
    }

    /// Bytes one frame takes in the output of the read functions: tightly packed rows, row 0 on top.
    pub fn frame_len(&self) -> usize {
        self.width as usize * self.height as usize * 4
    }

    /// Record a copy of `texture` (the reader's size) into a free staging buffer. A finished frame
    /// nobody read yet is given up for it, the oldest first. Returns `false`, recording nothing, when
    /// every buffer still waits for the GPU: the frame is then not captured. Call
    /// [`Self::submitted`] once `encoder` has been submitted.
    pub fn copy(&mut self, encoder: &mut wgpu::CommandEncoder, texture: &wgpu::Texture) -> bool {
        let free = self
            .slots
            .iter()
            .position(|s| matches!(s.state.load(Ordering::Acquire), IDLE | FAILED));
        let index = free.or_else(|| {
            let oldest = self
                .slots
                .iter()
                .enumerate()
                .filter(|(_, s)| s.state.load(Ordering::Acquire) == MAPPED)
                .min_by_key(|(_, s)| s.frame)
                .map(|(i, _)| i)?;
            self.slots[oldest].buffer.unmap();
            Some(oldest)
        });
        let Some(index) = index else {
            return false;
        };
        let slot = &mut self.slots[index];
        encoder.copy_texture_to_buffer(
            wgpu::TexelCopyTextureInfo {
                texture,
                mip_level: 0,
                origin: wgpu::Origin3d::ZERO,
                aspect: wgpu::TextureAspect::All,
            },
            wgpu::TexelCopyBufferInfo {
                buffer: &slot.buffer,
                layout: wgpu::TexelCopyBufferLayout {
                    offset: 0,
                    bytes_per_row: Some(self.padded_row),
                    rows_per_image: Some(self.height),
                },
            },
            wgpu::Extent3d {
                width: self.width,
                height: self.height,
                depth_or_array_layers: 1,
            },
        );
        slot.frame = self.next_frame;
        self.next_frame += 1;
        slot.state.store(COPIED, Ordering::Release);
        true
    }

    /// Request the mapping of the buffers [`Self::copy`] recorded into. Call after submitting the
    /// encoder holding those copies.
    pub fn submitted(&mut self) {
        for slot in &self.slots {
            if slot.state.load(Ordering::Acquire) != COPIED {
                continue;
            }
            slot.state.store(PENDING, Ordering::Release);
            let state = Arc::clone(&slot.state);
            slot.buffer
                .slice(..)
                .map_async(wgpu::MapMode::Read, move |r| {
                    state.store(if r.is_ok() { MAPPED } else { FAILED }, Ordering::Release);
                });
        }
    }

    /// Write the newest frame the GPU has finished into `out` (at least [`Self::frame_len`] bytes)
    /// without waiting. `Ok(false)` when no new frame is ready since the last read. Older finished
    /// frames are dropped. A failed map is reported once; the buffer is reused afterwards.
    pub fn read_latest(&mut self, device: &wgpu::Device, out: &mut [u8]) -> Result<bool, String> {
        device
            .poll(wgpu::PollType::Poll)
            .map_err(|e| format!("poll: {e:?}"))?;
        self.take_newest(out)
    }

    /// Wait for every submitted copy, then write the newest frame into `out` like
    /// [`Self::read_latest`]. `Ok(false)` only when nothing was copied since the last read.
    pub fn read_blocking(&mut self, device: &wgpu::Device, out: &mut [u8]) -> Result<bool, String> {
        device
            .poll(wgpu::PollType::wait_indefinitely())
            .map_err(|e| format!("poll: {e:?}"))?;
        self.take_newest(out)
    }

    fn take_newest(&mut self, out: &mut [u8]) -> Result<bool, String> {
        let need = self.frame_len();
        if out.len() < need {
            return Err(format!(
                "output buffer must hold {need} bytes (got {})",
                out.len()
            ));
        }
        let mut failed = false;
        for slot in &self.slots {
            if slot
                .state
                .compare_exchange(FAILED, IDLE, Ordering::AcqRel, Ordering::Acquire)
                .is_ok()
            {
                failed = true;
            }
        }
        if failed {
            return Err("mapping the read-back buffer failed".into());
        }
        let Some(newest) = self
            .slots
            .iter()
            .enumerate()
            .filter(|(_, s)| s.state.load(Ordering::Acquire) == MAPPED)
            .max_by_key(|(_, s)| s.frame)
            .map(|(i, _)| i)
        else {
            return Ok(false);
        };
        let frame = self.slots[newest].frame;
        let result = {
            let slot = &self.slots[newest];
            match slot.buffer.slice(..).get_mapped_range() {
                Ok(data) => {
                    let row = self.width as usize * 4;
                    let pitch = self.padded_row as usize;
                    for (dst, src) in out[..need]
                        .chunks_exact_mut(row)
                        .zip(data.chunks_exact(pitch))
                    {
                        dst.copy_from_slice(&src[..row]);
                    }
                    Ok(true)
                }
                Err(e) => Err(format!("mapped range: {e}")),
            }
        };
        // The frame read and every older finished one are done with.
        for slot in &self.slots {
            if slot.frame <= frame && slot.state.load(Ordering::Acquire) == MAPPED {
                slot.buffer.unmap();
                slot.state.store(IDLE, Ordering::Release);
            }
        }
        result
    }
}