1use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
8use std::sync::{Arc, RwLock};
9use std::time::Instant;
10
11use crate::compositor::{DisplayList, DrawCommand};
12use strata_layout::Rect;
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16pub enum SlotState {
17 Available,
19 Writing,
21 Committed,
23 Acquired,
25}
26
27#[derive(Debug, Clone)]
29pub struct ShmFrameSlot {
30 pub sequence: u64,
32 pub timestamp: Instant,
34 pub width: u32,
36 pub height: u32,
38 pub stride: u32,
40 pub damage_rects: Vec<Rect>,
42 pub display_list: DisplayList,
44 pub pixel_buffer: Vec<u8>,
46}
47
48impl Default for ShmFrameSlot {
49 fn default() -> Self {
50 Self {
51 sequence: 0,
52 timestamp: Instant::now(),
53 width: 0,
54 height: 0,
55 stride: 0,
56 damage_rects: Vec::new(),
57 display_list: DisplayList::default(),
58 pixel_buffer: Vec::new(),
59 }
60 }
61}
62
63pub struct ShmRingBuffer {
65 capacity: usize,
67 slots: Vec<RwLock<ShmFrameSlot>>,
69 slot_states: Vec<RwLock<SlotState>>,
71 head_sequence: AtomicU64,
73 tail_sequence: AtomicU64,
75 latest_committed_index: AtomicUsize,
77 dropped_frames: AtomicU64,
79}
80
81impl ShmRingBuffer {
82 pub fn new(capacity: usize) -> Arc<Self> {
84 let cap = capacity.max(2);
85 let mut slots = Vec::with_capacity(cap);
86 let mut slot_states = Vec::with_capacity(cap);
87
88 for _ in 0..cap {
89 slots.push(RwLock::new(ShmFrameSlot::default()));
90 slot_states.push(RwLock::new(SlotState::Available));
91 }
92
93 Arc::new(Self {
94 capacity: cap,
95 slots,
96 slot_states,
97 head_sequence: AtomicU64::new(0),
98 tail_sequence: AtomicU64::new(0),
99 latest_committed_index: AtomicUsize::new(usize::MAX),
100 dropped_frames: AtomicU64::new(0),
101 })
102 }
103
104 pub fn capacity(&self) -> usize {
106 self.capacity
107 }
108
109 pub fn dropped_frames(&self) -> u64 {
111 self.dropped_frames.load(Ordering::Relaxed)
112 }
113
114 pub fn begin_write(&self) -> usize {
117 let seq = self.head_sequence.fetch_add(1, Ordering::SeqCst);
118 let slot_idx = (seq as usize) % self.capacity;
119
120 if let Ok(mut state) = self.slot_states[slot_idx].write() {
121 *state = SlotState::Writing;
122 }
123
124 slot_idx
125 }
126
127 pub fn commit_write(
129 &self,
130 slot_idx: usize,
131 width: u32,
132 height: u32,
133 damage_rects: Vec<Rect>,
134 display_list: DisplayList,
135 pixel_buffer: Option<Vec<u8>>,
136 ) {
137 if slot_idx >= self.capacity {
138 return;
139 }
140
141 let seq = self.head_sequence.load(Ordering::SeqCst);
142 {
143 if let Ok(mut slot) = self.slots[slot_idx].write() {
144 slot.sequence = seq;
145 slot.timestamp = Instant::now();
146 slot.width = width;
147 slot.height = height;
148 slot.stride = width * 4;
149 slot.damage_rects = damage_rects;
150 slot.display_list = display_list;
151 if let Some(pixels) = pixel_buffer {
152 slot.pixel_buffer = pixels;
153 }
154 }
155 }
156
157 if let Ok(mut state) = self.slot_states[slot_idx].write() {
158 *state = SlotState::Committed;
159 }
160
161 let prev = self.latest_committed_index.swap(slot_idx, Ordering::SeqCst);
162 if prev != usize::MAX && prev != slot_idx {
163 let tail_seq = self.tail_sequence.load(Ordering::SeqCst);
164 if let Ok(prev_slot) = self.slots[prev].read() {
165 if prev_slot.sequence > tail_seq {
166 self.dropped_frames.fetch_add(1, Ordering::Relaxed);
167 }
168 }
169 }
170 }
171
172 pub fn acquire_latest(&self, last_sequence: u64) -> Option<(u64, ShmFrameSlot)> {
175 let committed_idx = self.latest_committed_index.load(Ordering::SeqCst);
176 if committed_idx == usize::MAX || committed_idx >= self.capacity {
177 return None;
178 }
179
180 if let Ok(slot) = self.slots[committed_idx].read() {
181 if slot.sequence > last_sequence {
182 self.tail_sequence.store(slot.sequence, Ordering::SeqCst);
183 return Some((slot.sequence, slot.clone()));
184 }
185 }
186
187 None
188 }
189
190 pub fn has_new_frame(&self, last_sequence: u64) -> bool {
192 let committed_idx = self.latest_committed_index.load(Ordering::Relaxed);
193 if committed_idx == usize::MAX || committed_idx >= self.capacity {
194 return false;
195 }
196
197 if let Ok(slot) = self.slots[committed_idx].read() {
198 slot.sequence > last_sequence
199 } else {
200 false
201 }
202 }
203}
204
205#[derive(Debug, Default, Clone)]
207pub struct CompositorTelemetry {
208 pub total_frames_composited: u64,
209 pub total_frames_dropped: u64,
210 pub last_frame_time_us: u64,
211 pub p95_frame_time_us: u64,
212 recent_latencies: Vec<u64>,
213}
214
215impl CompositorTelemetry {
216 pub fn record_frame(&mut self, latency_us: u64) {
217 self.total_frames_composited += 1;
218 self.last_frame_time_us = latency_us;
219 self.recent_latencies.push(latency_us);
220 if self.recent_latencies.len() > 100 {
221 self.recent_latencies.remove(0);
222 }
223
224 let mut sorted = self.recent_latencies.clone();
225 sorted.sort_unstable();
226 let idx = (sorted.len() as f32 * 0.95) as usize;
227 if idx < sorted.len() {
228 self.p95_frame_time_us = sorted[idx];
229 }
230 }
231}
232
233struct AttachedSurface {
235 surface_id: usize,
236 ring_buffer: Arc<ShmRingBuffer>,
237 last_sequence: u64,
238 viewport_offset: (f32, f32),
239 visible: bool,
240}
241
242pub struct ZeroCopyCompositor {
244 surfaces: Vec<AttachedSurface>,
245 telemetry: CompositorTelemetry,
246}
247
248impl Default for ZeroCopyCompositor {
249 fn default() -> Self {
250 Self::new()
251 }
252}
253
254impl ZeroCopyCompositor {
255 pub fn new() -> Self {
257 Self {
258 surfaces: Vec::new(),
259 telemetry: CompositorTelemetry::default(),
260 }
261 }
262
263 pub fn attach_surface(&mut self, surface_id: usize, ring_buffer: Arc<ShmRingBuffer>) {
265 self.surfaces.retain(|s| s.surface_id != surface_id);
266 self.surfaces.push(AttachedSurface {
267 surface_id,
268 ring_buffer,
269 last_sequence: 0,
270 viewport_offset: (0.0, 0.0),
271 visible: true,
272 });
273 }
274
275 pub fn detach_surface(&mut self, surface_id: usize) {
277 self.surfaces.retain(|s| s.surface_id != surface_id);
278 }
279
280 pub fn set_surface_layout(&mut self, surface_id: usize, offset: (f32, f32), visible: bool) {
282 if let Some(surf) = self
283 .surfaces
284 .iter_mut()
285 .find(|s| s.surface_id == surface_id)
286 {
287 surf.viewport_offset = offset;
288 surf.visible = visible;
289 }
290 }
291
292 pub fn composite_into(&mut self, master_display_list: &mut DisplayList) -> usize {
295 let t_start = Instant::now();
296 let mut new_frames_count = 0;
297
298 for surf in &mut self.surfaces {
299 if !surf.visible {
300 continue;
301 }
302
303 if let Some((seq, slot)) = surf.ring_buffer.acquire_latest(surf.last_sequence) {
304 surf.last_sequence = seq;
305 new_frames_count += 1;
306
307 let (dx, dy) = surf.viewport_offset;
308 if dx == 0.0 && dy == 0.0 {
309 for cmd in slot.display_list.commands {
311 master_display_list.push(cmd);
312 }
313 } else {
314 for cmd in slot.display_list.commands {
316 master_display_list.push(translate_cmd(&cmd, (dx, dy)));
317 }
318 }
319 }
320 }
321
322 let elapsed_us = t_start.elapsed().as_micros() as u64;
323 self.telemetry.record_frame(elapsed_us);
324
325 new_frames_count
326 }
327
328 pub fn telemetry(&self) -> &CompositorTelemetry {
330 &self.telemetry
331 }
332}
333
334fn translate_cmd(cmd: &DrawCommand, offset: (f32, f32)) -> DrawCommand {
336 let (dx, dy) = offset;
337 match cmd {
338 DrawCommand::DrawRect { bounds, color } => DrawCommand::DrawRect {
339 bounds: Rect::new(bounds.x + dx, bounds.y + dy, bounds.width, bounds.height),
340 color: *color,
341 },
342 DrawCommand::DrawRoundedRect {
343 bounds,
344 color,
345 border_radius,
346 border_width,
347 border_color,
348 } => DrawCommand::DrawRoundedRect {
349 bounds: Rect::new(bounds.x + dx, bounds.y + dy, bounds.width, bounds.height),
350 color: *color,
351 border_radius: *border_radius,
352 border_width: *border_width,
353 border_color: *border_color,
354 },
355 DrawCommand::DrawShadow {
356 bounds,
357 shadow,
358 border_radius,
359 } => DrawCommand::DrawShadow {
360 bounds: Rect::new(bounds.x + dx, bounds.y + dy, bounds.width, bounds.height),
361 shadow: shadow.clone(),
362 border_radius: *border_radius,
363 },
364 DrawCommand::DrawInsetShadow {
365 bounds,
366 shadow,
367 border_radius,
368 } => DrawCommand::DrawInsetShadow {
369 bounds: Rect::new(bounds.x + dx, bounds.y + dy, bounds.width, bounds.height),
370 shadow: shadow.clone(),
371 border_radius: *border_radius,
372 },
373 DrawCommand::DrawLinearGradient {
374 bounds,
375 angle_deg,
376 stops,
377 border_radius,
378 } => DrawCommand::DrawLinearGradient {
379 bounds: Rect::new(bounds.x + dx, bounds.y + dy, bounds.width, bounds.height),
380 angle_deg: *angle_deg,
381 stops: stops.clone(),
382 border_radius: *border_radius,
383 },
384 DrawCommand::DrawRadialGradient {
385 bounds,
386 center,
387 stops,
388 border_radius,
389 } => DrawCommand::DrawRadialGradient {
390 bounds: Rect::new(bounds.x + dx, bounds.y + dy, bounds.width, bounds.height),
391 center: *center,
392 stops: stops.clone(),
393 border_radius: *border_radius,
394 },
395 DrawCommand::PushBackdropFilter {
396 bounds,
397 radius,
398 filter,
399 } => DrawCommand::PushBackdropFilter {
400 bounds: Rect::new(bounds.x + dx, bounds.y + dy, bounds.width, bounds.height),
401 radius: *radius,
402 filter: filter.clone(),
403 },
404 DrawCommand::PopBackdropFilter => DrawCommand::PopBackdropFilter,
405 DrawCommand::DrawBorder {
406 bounds,
407 widths,
408 color,
409 border_radius,
410 style,
411 } => DrawCommand::DrawBorder {
412 bounds: Rect::new(bounds.x + dx, bounds.y + dy, bounds.width, bounds.height),
413 widths: *widths,
414 color: *color,
415 border_radius: *border_radius,
416 style: *style,
417 },
418 DrawCommand::DrawText {
419 origin,
420 bounds_width,
421 bounds_height,
422 text_align,
423 text,
424 font_size,
425 line_height,
426 font_weight,
427 color,
428 is_monospace,
429 font_family,
430 } => DrawCommand::DrawText {
431 origin: (origin.0 + dx, origin.1 + dy),
432 bounds_width: *bounds_width,
433 bounds_height: *bounds_height,
434 text_align: *text_align,
435 text: text.clone(),
436 font_size: *font_size,
437 line_height: *line_height,
438 font_weight: *font_weight,
439 color: *color,
440 is_monospace: *is_monospace,
441 font_family: *font_family,
442 },
443 DrawCommand::PushClip { bounds, radius } => DrawCommand::PushClip {
444 bounds: Rect::new(bounds.x + dx, bounds.y + dy, bounds.width, bounds.height),
445 radius: *radius,
446 },
447 DrawCommand::PopClip => DrawCommand::PopClip,
448 other => other.clone(),
449 }
450}