drmkit-scene-sources 0.1.2

Tier-1 buffer sources for drmkit scenes: dumb buffers and imported DMA-BUFs.
Documentation
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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
// SPDX-FileCopyrightText: (c) 2026 Joel Winarske
// SPDX-License-Identifier: MIT

//! The presentation state machine shared by the externally-fed sources.
//!
//! Tracks which buffer is pending and which is on screen, hands out the
//! monotonic tokens the scene's deferred-release protocol keys on, carries
//! damage forward across frames it drops, and enforces the optional fence
//! deadline.
//!
//! It owns **no buffer storage**. A buffer is only a [`SlotKey`] — a dense
//! index for a fixed ring, a stable per-buffer key for a pool — so the same
//! machine drives both without knowing which it is. It also means all of it is
//! testable with no device anywhere.
//!
//! # Threading
//!
//! `submit` runs on the producer's thread while the scene calls `acquire` and
//! `release` on its commit thread. Only the pending handoff is shared, so only
//! that is behind the lock; the scanning bookkeeping is commit-thread-only.

use std::sync::Mutex;
use std::time::Duration;

use drmkit_scene::DamageRect;
use drmkit_sync::SyncFence;

/// Opaque buffer identity: a slot index, or a pool's own key.
pub type SlotKey = u64;

/// How many damage rectangles a submit can carry.
///
/// Bounds what one submit hands across, so a producer cannot grow the handoff
/// without limit. An over-cap frame degrades to whole-frame rather than
/// truncating — a short list would under-report the dirty area, and the parts
/// left out would keep whatever the previous frame had.
pub const MAX_DAMAGE: usize = 16;

/// What the commit thread should do this vblank.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Present {
    /// Nothing to present; the adapter returns `WouldBlock`.
    None,
    /// A newly acquired frame, under a new token.
    Fresh,
    /// Re-present the buffer already on screen, under its existing token.
    Hold,
}

/// The commit thread's decision.
#[derive(Debug)]
#[non_exhaustive]
pub struct Acquired {
    /// What to do.
    pub kind: Present,
    /// Which buffer, for `Fresh` and `Hold`.
    pub key: SlotKey,
    /// The token the release protocol keys on.
    pub token: u64,
    /// The producer's render fence. `Fresh` only, and never set when a
    /// deadline is configured — see [`RingPresenter::acquire`].
    pub fence: Option<SyncFence>,
    /// Dirty regions, `Fresh` only. Empty means whole-frame.
    pub damage: Vec<DamageRect>,
}

#[derive(Default)]
struct Pending {
    key: Option<SlotKey>,
    fence: Option<SyncFence>,
    damage: Vec<DamageRect>,
}

/// Tracks pending, scanning and in-flight buffers across frames.
pub struct RingPresenter {
    pending: Mutex<Pending>,
    scanning_key: Option<SlotKey>,
    scanning_token: u64,
    next_token: u64,
    /// Tokens handed out and not yet retired, with the buffer each names.
    outstanding: Vec<(u64, SlotKey)>,
    fence_deadline: Option<Duration>,
    /// Damage from frames dropped on a deadline miss, owed to the next frame
    /// that is actually presented.
    carried_damage: Vec<DamageRect>,
    /// Whether what was dropped was a *whole-frame* update.
    ///
    /// Separate from `carried_damage` being empty, which is ambiguous: an
    /// empty list means both "nothing was dropped" and "everything was". Only
    /// the second forces the next frame to whole-frame, and without this flag
    /// the two are indistinguishable by the time that frame arrives.
    carried_whole_frame: bool,
}

impl RingPresenter {
    /// A presenter with an optional fence deadline.
    ///
    /// With a deadline set, a producer's fence is CPU-waited here and **never**
    /// handed to the kernel — see [`acquire`](Self::acquire) for why those are
    /// mutually exclusive.
    #[must_use]
    pub fn new(fence_deadline: Option<Duration>) -> Self {
        Self {
            pending: Mutex::new(Pending::default()),
            scanning_key: None,
            scanning_token: 0,
            next_token: 0,
            outstanding: Vec::new(),
            fence_deadline,
            carried_damage: Vec::new(),
            carried_whole_frame: false,
        }
    }

    /// The configured fence deadline, if any.
    #[must_use]
    pub const fn fence_deadline(&self) -> Option<Duration> {
        self.fence_deadline
    }

    /// Hand in a freshly rendered buffer. Producer thread.
    ///
    /// Replaces any previous pending frame rather than queueing: a producer
    /// that outruns the display should show its newest frame, not work through
    /// a backlog. `damage` replaces too, and an over-cap list becomes
    /// whole-frame.
    pub fn submit(&self, key: SlotKey, fence: Option<SyncFence>, damage: &[DamageRect]) {
        let mut pending = self.lock();
        pending.key = Some(key);
        pending.fence = fence;
        pending.damage.clear();
        if damage.len() <= MAX_DAMAGE {
            pending.damage.extend_from_slice(damage);
        }
    }

    /// Whether a submitted frame is waiting.
    #[must_use]
    pub fn has_fresh_frame(&self) -> bool {
        self.lock().key.is_some()
    }

    /// The buffer currently on screen, if any.
    #[must_use]
    pub const fn scanning_key(&self) -> Option<SlotKey> {
        self.scanning_key
    }

    /// Whether `key` is still on screen or named by an unretired token.
    ///
    /// A pool consults this before evicting a cached buffer: one the kernel may
    /// still be scanning out must not have its import torn down.
    #[must_use]
    pub fn is_referenced(&self, key: SlotKey) -> bool {
        self.scanning_key == Some(key) || self.outstanding.iter().any(|(_, k)| *k == key)
    }

    /// Advance one vblank. Commit thread.
    ///
    /// A configured deadline makes the fence a CPU pre-wait here, and the fence
    /// is then dropped rather than also being handed to `IN_FENCE_FD`. The two
    /// are mutually exclusive on purpose: an in-fence the kernel is already
    /// holding that never signals wedges the entire CRTC's pipeline, not just
    /// this layer. Waiting here instead keeps a stuck producer's blast radius
    /// to its own frame.
    ///
    /// Missing the deadline drops that frame and holds the last good one —
    /// frozen but alive, rather than blank. Its damage is carried forward,
    /// because those regions were never presented.
    pub fn acquire(&mut self) -> Acquired {
        let (mut key, mut fence, mut damage) = {
            let mut pending = self.lock();
            if pending.key.is_some() {
                (
                    pending.key.take(),
                    pending.fence.take(),
                    std::mem::take(&mut pending.damage),
                )
            } else {
                (None, None, Vec::new())
            }
        };

        if let (Some(deadline), true, Some(f)) = (self.fence_deadline, key.is_some(), fence.take())
        {
            // A sub-millisecond deadline rounds up: the wait polls in whole
            // milliseconds, so truncating 500µs to zero would never wait at
            // all. An explicit zero stays zero.
            let waited = if deadline.is_zero() {
                Duration::ZERO
            } else {
                deadline.max(Duration::from_millis(1))
            };
            if f.wait(waited).is_err() {
                self.carry(&damage);
                damage.clear();
                key = None;
            }
        }

        if let Some(key) = key {
            self.scanning_key = Some(key);
            self.next_token = self.next_token.wrapping_add(1);
            if self.next_token == 0 {
                // Zero is the "never submitted" sentinel, so skip it on wrap
                // rather than hand out a token release() will ignore.
                self.next_token = 1;
            }
            self.scanning_token = self.next_token;
            self.outstanding.push((self.scanning_token, key));

            let mut out = std::mem::take(&mut self.carried_damage);
            let dropped_whole_frame = std::mem::take(&mut self.carried_whole_frame);
            if dropped_whole_frame || damage.is_empty() || out.len() + damage.len() > MAX_DAMAGE {
                // A dropped whole-frame, this frame's own whole-frame, or too
                // many rectangles between them: all three degrade to
                // whole-frame rather than under-reporting, which would leave
                // stale pixels on screen.
                out.clear();
            } else {
                out.extend_from_slice(&damage);
            }

            return Acquired {
                kind: Present::Fresh,
                key,
                token: self.scanning_token,
                fence,
                damage: out,
            };
        }

        // Nothing fresh and ready. Re-present what is on screen under the
        // *same* token, so the held buffer is not mistaken for a superseded one
        // and released out from under the display. No new outstanding entry —
        // the live token already has one.
        if let Some(key) = self.scanning_key {
            return Acquired {
                kind: Present::Hold,
                key,
                token: self.scanning_token,
                fence: None,
                damage: Vec::new(),
            };
        }

        Acquired {
            kind: Present::None,
            key: 0,
            token: 0,
            fence: None,
            damage: Vec::new(),
        }
    }

    /// Retire the acquisition that carried `token`.
    ///
    /// Returns the buffer to hand back, or `None` when there is nothing to
    /// release: the sentinel token, a buffer still on screen, or a token
    /// already retired.
    pub fn release(&mut self, token: u64) -> Option<SlotKey> {
        if token == 0 {
            return None;
        }
        // A buffer holding the live token is still on screen — including
        // through any number of idle holds, which all share it. Telling the
        // producer it is free would race it into overwriting a buffer the
        // kernel is scanning out.
        if token == self.scanning_token {
            return None;
        }
        // Erase on fire, so the several holds that share one token collapse to
        // a single release and a token that is absent was already retired.
        let at = self.outstanding.iter().position(|(t, _)| *t == token)?;
        Some(self.outstanding.remove(at).1)
    }

    /// Let the buffer on screen release like a superseded one.
    ///
    /// For a source the scene has retired: no newer frame will ever displace
    /// the scanning buffer, so the release that would otherwise be held back
    /// is the last chance to hand it to the producer.
    pub fn retire_scanning(&mut self) {
        self.scanning_token = 0;
    }

    /// Drop all pending, in-flight and scanning state.
    ///
    /// For a session pause: every framebuffer id is about to belong to a
    /// revoked descriptor, so presentation restarts from scratch with the
    /// producer's next submit.
    pub fn reset(&mut self) {
        let mut pending = self.lock();
        *pending = Pending::default();
        drop(pending);
        self.scanning_key = None;
        self.scanning_token = 0;
        self.outstanding.clear();
        self.carried_damage.clear();
        self.carried_whole_frame = false;
    }

    /// Accumulate damage owed by a dropped frame.
    fn carry(&mut self, damage: &[DamageRect]) {
        if damage.is_empty() || self.carried_damage.len() + damage.len() > MAX_DAMAGE {
            // A dropped whole-frame stays whole-frame, and an overflowing
            // accumulation degrades to one: reporting less than was dirtied
            // leaves stale pixels on screen.
            //
            // The flag is what carries that across to the next frame. Clearing
            // the list alone loses it -- an empty carry is indistinguishable
            // from nothing having been dropped, and the next frame would go out
            // with only its own rects while the rest of the screen stayed stale.
            self.carried_damage.clear();
            self.carried_damage.shrink_to_fit();
            self.carried_whole_frame = true;
            return;
        }
        self.carried_damage.extend_from_slice(damage);
    }

    /// The pending state, recovering from a poisoned lock.
    ///
    /// A producer thread that panicked mid-submit leaves the handoff possibly
    /// half-written, but every field is replaced wholesale by the next submit
    /// and the worst case is one stale frame. Refusing to present again for the
    /// rest of the session would be the larger failure.
    fn lock(&self) -> std::sync::MutexGuard<'_, Pending> {
        self.pending
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
    }
}

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

    fn rect(x: i32, y: i32) -> DamageRect {
        DamageRect { x, y, w: 8, h: 8 }
    }

    /// A dropped whole-frame update forces the next frame to whole-frame.
    ///
    /// Empty damage means *everything changed*, and no rect list can say that.
    /// So a dropped whole-frame cannot be unioned into the next frame's rects
    /// -- carrying nothing would silently downgrade it to "only what the next
    /// frame touched", leaving the rest of the screen showing the frame before
    /// the one that was dropped.
    ///
    /// Found by the vkms parity port of upstream's
    /// `DroppedWholeFrameForcesWholeFrameCarry`. Pinned here too because it is
    /// pure logic: it needs a missed deadline, not a card.
    #[test]
    fn a_dropped_whole_frame_forces_the_next_frame_to_whole_frame() {
        let mut p = RingPresenter::new(Some(Duration::from_millis(1)));
        p.submit(0, None, &[]);
        let first = p.acquire();
        assert_eq!(first.kind, Present::Fresh);
        p.release(first.token);

        // A frame behind a fence that never signals, declaring whole-frame.
        let (read, _write) = std::io::pipe().expect("a pipe stands in for a fence");
        let fence = SyncFence::import(std::os::fd::AsFd::as_fd(&read)).expect("import");
        p.submit(1, Some(fence), &[]);
        let held = p.acquire();
        assert_eq!(held.kind, Present::Hold, "the deadline miss holds");
        p.release(held.token);

        // The next frame declares a small region; the drop must override it.
        p.submit(1, None, &[rect(5, 5)]);
        let advanced = p.acquire();
        assert_eq!(advanced.kind, Present::Fresh);
        assert!(
            advanced.damage.is_empty(),
            "a rect list here leaves everything outside it stale"
        );
    }

    /// A dropped *partial* frame is unioned in, and cleared afterwards.
    ///
    /// The counterpart to the above: a dropped frame that named its regions
    /// still has them stale on screen, so they ride along with the next frame
    /// -- once. Carrying them further would over-report every frame after.
    #[test]
    fn a_dropped_partial_frame_is_carried_into_the_next_frame_only() {
        let mut p = RingPresenter::new(Some(Duration::from_millis(1)));
        p.submit(0, None, &[]);
        let token = p.acquire().token;
        p.release(token);

        let (read, _write) = std::io::pipe().expect("a pipe stands in for a fence");
        let fence = SyncFence::import(std::os::fd::AsFd::as_fd(&read)).expect("import");
        p.submit(1, Some(fence), &[rect(1, 1)]);
        let held = p.acquire();
        assert_eq!(held.kind, Present::Hold);
        p.release(held.token);

        p.submit(1, None, &[rect(5, 5)]);
        let advanced = p.acquire();
        assert_eq!(
            advanced.damage,
            vec![rect(1, 1), rect(5, 5)],
            "the dropped region is still stale, so it repaints with this frame"
        );
        p.release(advanced.token);

        p.submit(0, None, &[rect(5, 5)]);
        let after = p.acquire();
        assert_eq!(
            after.damage,
            vec![rect(5, 5)],
            "the carry is spent; repeating it would over-report from here on"
        );
    }

    /// Nothing submitted, nothing to present.
    #[test]
    fn a_presenter_with_no_frame_yet_presents_nothing() {
        let mut p = RingPresenter::new(None);
        let out = p.acquire();
        assert_eq!(out.kind, Present::None);
        assert_eq!(out.token, 0, "the sentinel token, which release ignores");
        assert!(!p.has_fresh_frame());
    }

    /// A submitted frame is presented once, under a fresh token.
    #[test]
    fn a_submitted_frame_is_presented_once() {
        let mut p = RingPresenter::new(None);
        p.submit(3, None, &[]);
        assert!(p.has_fresh_frame());

        let first = p.acquire();
        assert_eq!(first.kind, Present::Fresh);
        assert_eq!(first.key, 3);
        assert_ne!(first.token, 0);
        assert!(!p.has_fresh_frame(), "the pending frame was taken");

        // Nothing new arrived, so the same buffer stays up.
        let second = p.acquire();
        assert_eq!(second.kind, Present::Hold);
        assert_eq!(second.key, 3);
        assert_eq!(
            second.token, first.token,
            "a hold re-presents under the live token, or the buffer on screen \
             would look superseded and be released out from under the display"
        );
    }

    /// Holding forever never accumulates outstanding tokens.
    ///
    /// A layer that is idle for a minute at 60Hz holds 3600 times. One
    /// outstanding entry per hold would be a slow leak with no upper bound.
    #[test]
    fn idle_holds_do_not_accumulate() {
        let mut p = RingPresenter::new(None);
        p.submit(0, None, &[]);
        let token = p.acquire().token;
        for _ in 0..100 {
            assert_eq!(p.acquire().kind, Present::Hold);
        }
        assert_eq!(p.outstanding.len(), 1, "one live token, however many holds");
        assert_eq!(p.release(token), None, "still on screen");
    }

    /// A buffer is released only once something newer replaces it.
    #[test]
    fn a_buffer_is_released_when_superseded() {
        let mut p = RingPresenter::new(None);
        p.submit(0, None, &[]);
        let first = p.acquire().token;
        assert_eq!(
            p.release(first),
            None,
            "releasing the buffer on screen would race the producer into \
             overwriting live scanout"
        );

        p.submit(1, None, &[]);
        let second = p.acquire().token;
        assert_ne!(second, first);
        assert_eq!(p.release(first), Some(0), "slot 0 is now off screen");
        assert_eq!(p.release(first), None, "and is not released twice");
        assert_eq!(p.release(second), None, "the new one is still up");
    }

    /// A retired presenter hands back its scanning buffer with the last
    /// acquisition that carried it, and only once.
    #[test]
    fn a_retired_presenter_releases_its_scanning_buffer() {
        let mut p = RingPresenter::new(None);
        p.submit(3, None, &[]);
        let live = p.acquire().token;
        let hold = p.acquire().token;
        assert_eq!(hold, live, "an idle hold shares the live token");
        assert_eq!(p.release(live), None, "still on screen");

        p.retire_scanning();
        assert_eq!(
            p.release(hold),
            Some(3),
            "no newer frame is coming, so the producer would never get it back"
        );
        assert_eq!(p.release(hold), None, "and not twice");
    }

    /// The sentinel token releases nothing.
    #[test]
    fn the_sentinel_token_releases_nothing() {
        let mut p = RingPresenter::new(None);
        assert_eq!(p.release(0), None);
    }

    /// A buffer stays referenced while on screen or awaiting release.
    #[test]
    fn a_buffer_is_referenced_until_retired() {
        let mut p = RingPresenter::new(None);
        p.submit(5, None, &[]);
        let first = p.acquire().token;
        assert!(p.is_referenced(5));

        p.submit(6, None, &[]);
        p.acquire();
        assert!(p.is_referenced(5), "off screen but not yet retired");
        assert!(p.is_referenced(6));

        assert_eq!(p.release(first), Some(5));
        assert!(!p.is_referenced(5), "retired, so a pool may now evict it");
    }

    /// Submitting twice before a vblank presents the newer frame.
    ///
    /// A producer outrunning the display should show its newest frame, not work
    /// through a backlog it will never catch up on.
    #[test]
    fn a_second_submit_replaces_an_unacquired_first() {
        let mut p = RingPresenter::new(None);
        p.submit(1, None, &[]);
        p.submit(2, None, &[]);
        let out = p.acquire();
        assert_eq!(out.key, 2);
        assert_eq!(p.acquire().kind, Present::Hold, "only one frame was queued");
    }

    /// Damage replaces rather than unions.
    #[test]
    fn damage_replaces_across_submits() {
        let mut p = RingPresenter::new(None);
        p.submit(0, None, &[rect(0, 0), rect(8, 0)]);
        p.submit(0, None, &[rect(16, 0)]);
        let out = p.acquire();
        assert_eq!(out.damage, vec![rect(16, 0)]);
    }

    /// Too much damage degrades to whole-frame.
    ///
    /// Truncating would under-report the dirty area, and the rectangles left
    /// out would keep whatever the previous frame had — visible as stale
    /// patches. Whole-frame is slower and correct.
    #[test]
    fn over_cap_damage_becomes_whole_frame() {
        let mut p = RingPresenter::new(None);
        let many: Vec<DamageRect> = (0..=MAX_DAMAGE)
            .map(|i| rect(i32::try_from(i).expect("small") * 8, 0))
            .collect();
        p.submit(0, None, &many);
        let out = p.acquire();
        assert!(
            out.damage.is_empty(),
            "an over-cap list must degrade to whole-frame, not truncate to \
             {MAX_DAMAGE}"
        );
    }

    /// A reset drops everything, including what is on screen.
    #[test]
    fn a_reset_forgets_the_scanning_buffer() {
        let mut p = RingPresenter::new(None);
        p.submit(4, None, &[]);
        p.acquire();
        assert_eq!(p.scanning_key(), Some(4));

        p.reset();

        assert_eq!(p.scanning_key(), None);
        assert!(!p.is_referenced(4));
        assert_eq!(
            p.acquire().kind,
            Present::None,
            "after a resume nothing is on screen to hold, so there is nothing \
             to present until the producer submits again"
        );
    }

    /// Tokens skip the sentinel when the counter wraps.
    ///
    /// Reaching zero would hand out a token `release` ignores, and that
    /// buffer would never be handed back — the producer's ring would starve one
    /// slot short, permanently.
    #[test]
    fn a_wrapping_token_skips_the_sentinel() {
        let mut p = RingPresenter::new(None);
        p.next_token = u64::MAX;
        p.submit(0, None, &[]);
        let out = p.acquire();
        assert_ne!(out.token, 0, "the sentinel must be skipped on wrap");
        assert_eq!(out.token, 1);
    }
}