Skip to main content

lactea_host/
readback.rs

1//! RGBA8 read-back of rendered frames without stalling on the GPU.
2//!
3//! A [`FrameReader`] owns a small ring of staging buffers. Each frame records a copy of the target
4//! into a free buffer ([`FrameReader::copy`]); after the submit, [`FrameReader::submitted`] asks for
5//! the buffer to be mapped, and [`FrameReader::read_latest`] later hands out the newest frame the GPU
6//! has finished, without waiting. That costs one or two frames of latency instead of a full GPU
7//! round trip per frame, and works in the browser too (wgpu maps buffers from the event loop there).
8//! [`FrameReader::read_blocking`] waits instead, for hosts that want the frame they just rendered.
9
10use std::sync::Arc;
11use std::sync::atomic::{AtomicU8, Ordering};
12
13/// Free: may receive the next copy.
14const IDLE: u8 = 0;
15/// A copy was recorded; the map is requested by [`FrameReader::submitted`].
16const COPIED: u8 = 1;
17/// Mapping requested, not finished yet.
18const PENDING: u8 = 2;
19/// Mapped: holds a finished frame.
20const MAPPED: u8 = 3;
21/// The map failed; the buffer is not mapped.
22const FAILED: u8 = 4;
23
24struct Slot {
25    buffer: wgpu::Buffer,
26    /// Set by the map callback, which may run on another thread.
27    state: Arc<AtomicU8>,
28    /// Sequence number of the frame copied into it.
29    frame: u64,
30}
31
32/// Ring of staging buffers reading back a `width` x `height` target with 4 bytes per texel
33/// (`Rgba8Unorm`, `Bgra8Unorm`, ...). Make a new one when the size changes.
34pub struct FrameReader {
35    width: u32,
36    height: u32,
37    /// Row pitch in the staging buffers (`COPY_BYTES_PER_ROW_ALIGNMENT`-aligned).
38    padded_row: u32,
39    slots: Vec<Slot>,
40    /// Frames copied so far; the next copy gets this number.
41    next_frame: u64,
42}
43
44impl FrameReader {
45    /// A reader with `depth` staging buffers (at least 1; 3 keeps the GPU busy without dropping
46    /// frames at a steady frame rate).
47    pub fn new(device: &wgpu::Device, width: u32, height: u32, depth: usize) -> Self {
48        let padded_row = (width * 4).div_ceil(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT)
49            * wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
50        let slots = (0..depth.max(1))
51            .map(|_| Slot {
52                buffer: device.create_buffer(&wgpu::BufferDescriptor {
53                    label: Some("lactea readback"),
54                    size: u64::from(padded_row) * u64::from(height),
55                    usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
56                    mapped_at_creation: false,
57                }),
58                state: Arc::new(AtomicU8::new(IDLE)),
59                frame: 0,
60            })
61            .collect();
62        Self {
63            width,
64            height,
65            padded_row,
66            slots,
67            next_frame: 0,
68        }
69    }
70
71    pub fn width(&self) -> u32 {
72        self.width
73    }
74
75    pub fn height(&self) -> u32 {
76        self.height
77    }
78
79    /// Bytes one frame takes in the output of the read functions: tightly packed rows, row 0 on top.
80    pub fn frame_len(&self) -> usize {
81        self.width as usize * self.height as usize * 4
82    }
83
84    /// Record a copy of `texture` (the reader's size) into a free staging buffer. A finished frame
85    /// nobody read yet is given up for it, the oldest first. Returns `false`, recording nothing, when
86    /// every buffer still waits for the GPU: the frame is then not captured. Call
87    /// [`Self::submitted`] once `encoder` has been submitted.
88    pub fn copy(&mut self, encoder: &mut wgpu::CommandEncoder, texture: &wgpu::Texture) -> bool {
89        let free = self
90            .slots
91            .iter()
92            .position(|s| matches!(s.state.load(Ordering::Acquire), IDLE | FAILED));
93        let index = free.or_else(|| {
94            let oldest = self
95                .slots
96                .iter()
97                .enumerate()
98                .filter(|(_, s)| s.state.load(Ordering::Acquire) == MAPPED)
99                .min_by_key(|(_, s)| s.frame)
100                .map(|(i, _)| i)?;
101            self.slots[oldest].buffer.unmap();
102            Some(oldest)
103        });
104        let Some(index) = index else {
105            return false;
106        };
107        let slot = &mut self.slots[index];
108        encoder.copy_texture_to_buffer(
109            wgpu::TexelCopyTextureInfo {
110                texture,
111                mip_level: 0,
112                origin: wgpu::Origin3d::ZERO,
113                aspect: wgpu::TextureAspect::All,
114            },
115            wgpu::TexelCopyBufferInfo {
116                buffer: &slot.buffer,
117                layout: wgpu::TexelCopyBufferLayout {
118                    offset: 0,
119                    bytes_per_row: Some(self.padded_row),
120                    rows_per_image: Some(self.height),
121                },
122            },
123            wgpu::Extent3d {
124                width: self.width,
125                height: self.height,
126                depth_or_array_layers: 1,
127            },
128        );
129        slot.frame = self.next_frame;
130        self.next_frame += 1;
131        slot.state.store(COPIED, Ordering::Release);
132        true
133    }
134
135    /// Request the mapping of the buffers [`Self::copy`] recorded into. Call after submitting the
136    /// encoder holding those copies.
137    pub fn submitted(&mut self) {
138        for slot in &self.slots {
139            if slot.state.load(Ordering::Acquire) != COPIED {
140                continue;
141            }
142            slot.state.store(PENDING, Ordering::Release);
143            let state = Arc::clone(&slot.state);
144            slot.buffer
145                .slice(..)
146                .map_async(wgpu::MapMode::Read, move |r| {
147                    state.store(if r.is_ok() { MAPPED } else { FAILED }, Ordering::Release);
148                });
149        }
150    }
151
152    /// Write the newest frame the GPU has finished into `out` (at least [`Self::frame_len`] bytes)
153    /// without waiting. `Ok(false)` when no new frame is ready since the last read. Older finished
154    /// frames are dropped. A failed map is reported once; the buffer is reused afterwards.
155    pub fn read_latest(&mut self, device: &wgpu::Device, out: &mut [u8]) -> Result<bool, String> {
156        device
157            .poll(wgpu::PollType::Poll)
158            .map_err(|e| format!("poll: {e:?}"))?;
159        self.take_newest(out)
160    }
161
162    /// Wait for every submitted copy, then write the newest frame into `out` like
163    /// [`Self::read_latest`]. `Ok(false)` only when nothing was copied since the last read.
164    pub fn read_blocking(&mut self, device: &wgpu::Device, out: &mut [u8]) -> Result<bool, String> {
165        device
166            .poll(wgpu::PollType::wait_indefinitely())
167            .map_err(|e| format!("poll: {e:?}"))?;
168        self.take_newest(out)
169    }
170
171    fn take_newest(&mut self, out: &mut [u8]) -> Result<bool, String> {
172        let need = self.frame_len();
173        if out.len() < need {
174            return Err(format!(
175                "output buffer must hold {need} bytes (got {})",
176                out.len()
177            ));
178        }
179        let mut failed = false;
180        for slot in &self.slots {
181            if slot
182                .state
183                .compare_exchange(FAILED, IDLE, Ordering::AcqRel, Ordering::Acquire)
184                .is_ok()
185            {
186                failed = true;
187            }
188        }
189        if failed {
190            return Err("mapping the read-back buffer failed".into());
191        }
192        let Some(newest) = self
193            .slots
194            .iter()
195            .enumerate()
196            .filter(|(_, s)| s.state.load(Ordering::Acquire) == MAPPED)
197            .max_by_key(|(_, s)| s.frame)
198            .map(|(i, _)| i)
199        else {
200            return Ok(false);
201        };
202        let frame = self.slots[newest].frame;
203        let result = {
204            let slot = &self.slots[newest];
205            match slot.buffer.slice(..).get_mapped_range() {
206                Ok(data) => {
207                    let row = self.width as usize * 4;
208                    let pitch = self.padded_row as usize;
209                    for (dst, src) in out[..need]
210                        .chunks_exact_mut(row)
211                        .zip(data.chunks_exact(pitch))
212                    {
213                        dst.copy_from_slice(&src[..row]);
214                    }
215                    Ok(true)
216                }
217                Err(e) => Err(format!("mapped range: {e}")),
218            }
219        };
220        // The frame read and every older finished one are done with.
221        for slot in &self.slots {
222            if slot.frame <= frame && slot.state.load(Ordering::Acquire) == MAPPED {
223                slot.buffer.unmap();
224                slot.state.store(IDLE, Ordering::Release);
225            }
226        }
227        result
228    }
229}