drmkit-scene-set 0.1.2

Cross-CRTC orchestration for drmkit scenes: one commit across several outputs.
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
612
613
614
615
// SPDX-FileCopyrightText: (c) 2026 Joel Winarske
// SPDX-License-Identifier: MIT

//! Parity port of `tests/unit/test_scene_set.cpp` from drm-cxx @ `4a0b64a`.
//!
//! The partition is the part worth testing hardest: it decides how many
//! ioctls a multi-output frame costs and whether the outputs are atomic with
//! each other, and it is pure — no device, no kernel, no timing.

use crate::{LayerSpec, NarrowPolicy, SceneSet, SetError, SetLayerHandle, SlotState};
use crate::{Target, partition_for_policy};

fn engaged(wants_modeset: bool) -> SlotState {
    SlotState {
        is_hole: false,
        wants_modeset,
    }
}

const HOLE: SlotState = SlotState {
    is_hole: true,
    wants_modeset: false,
};

// --- partition ----------------------------------------------------------------

/// No slots, no commits.
#[test]
fn an_empty_set_commits_nothing() {
    for policy in [
        NarrowPolicy::Combined,
        NarrowPolicy::AutoOnModeset,
        NarrowPolicy::PerCrtc,
    ] {
        assert!(
            partition_for_policy(&[], policy).is_empty(),
            "{policy:?} invented a commit for a set with no scenes"
        );
    }
}

/// Slots that are all holes commit nothing either.
///
/// A hole is an index kept alive so the ones after it keep meaning what they
/// did. Committing for one would be an ioctl that programs nothing, and under
/// `PerCrtc` it would be one per removed output.
#[test]
fn a_set_of_only_holes_commits_nothing() {
    let slots = [HOLE, HOLE, HOLE];
    for policy in [
        NarrowPolicy::Combined,
        NarrowPolicy::AutoOnModeset,
        NarrowPolicy::PerCrtc,
    ] {
        assert!(
            partition_for_policy(&slots, policy).is_empty(),
            "{policy:?} committed for a hole"
        );
    }
}

/// `Combined` is always one group, holding every engaged slot.
#[test]
fn combined_is_one_group_of_every_engaged_slot() {
    let slots = [engaged(false), HOLE, engaged(true), engaged(false)];

    assert_eq!(
        partition_for_policy(&slots, NarrowPolicy::Combined),
        vec![vec![0, 2, 3]],
        "the modesetting slot goes in the same commit as the steady ones, \
         which is what Combined means and what makes the frame atomic"
    );
}

/// `PerCrtc` is one group per engaged slot, in index order.
#[test]
fn per_crtc_is_one_group_per_engaged_slot() {
    let slots = [engaged(false), HOLE, engaged(true)];

    assert_eq!(
        partition_for_policy(&slots, NarrowPolicy::PerCrtc),
        vec![vec![0], vec![2]],
        "one commit each, and the hole between them is not one of them"
    );
}

/// With every engaged slot steady, `AutoOnModeset` keeps them together.
///
/// The split has a cost — the outputs stop being atomic with each other — so
/// it is paid only when there is something to gain.
#[test]
fn auto_keeps_a_uniformly_steady_set_together() {
    let slots = [engaged(false), engaged(false), HOLE];

    assert_eq!(
        partition_for_policy(&slots, NarrowPolicy::AutoOnModeset),
        vec![vec![0, 1]]
    );
}

/// With every engaged slot modesetting, one group again.
///
/// Uniform is uniform in both directions: splitting here would give up
/// atomicity and buy nothing, since every output pays the modeset either way.
#[test]
fn auto_keeps_a_uniformly_modesetting_set_together() {
    let slots = [engaged(true), engaged(true)];

    assert_eq!(
        partition_for_policy(&slots, NarrowPolicy::AutoOnModeset),
        vec![vec![0, 1]]
    );
}

/// A mixed set splits, and the modeset goes first.
///
/// The order is the contract. A steady frame committed to an output that is
/// about to be reconfigured is wasted work at best, and at worst it is a
/// frame the modeset then blanks.
#[test]
fn auto_splits_a_mixed_set_with_the_modeset_first() {
    let slots = [engaged(false), engaged(true), engaged(false), engaged(true)];

    assert_eq!(
        partition_for_policy(&slots, NarrowPolicy::AutoOnModeset),
        vec![vec![1, 3], vec![0, 2]],
        "modesetting slots first, steady ones second, each in index order"
    );
}

/// A hole is never what makes a set look mixed.
///
/// `SlotState::default` is a hole with `wants_modeset` false, so a
/// classification that looked at the flag without checking the hole would
/// count every removed output as a steady one — and a set of one modesetting
/// output plus a hole would split into two commits, the second empty.
#[test]
fn holes_do_not_make_a_uniform_set_look_mixed() {
    let slots = [HOLE, engaged(true), HOLE];

    assert_eq!(
        partition_for_policy(&slots, NarrowPolicy::AutoOnModeset),
        vec![vec![1]],
        "one modesetting output and two holes is uniform, not mixed"
    );
}

// --- the set ------------------------------------------------------------------

fn empty_set() -> SceneSet {
    SceneSet::new(Vec::new())
}

fn source() -> std::rc::Rc<std::cell::RefCell<dyn drmkit_scene::LayerBufferSource>> {
    std::rc::Rc::new(std::cell::RefCell::new(Stub))
}

/// A source that never produces anything, for the cases that never commit.
struct Stub;

impl drmkit_scene::LayerBufferSource for Stub {
    fn acquire(&mut self) -> Result<drmkit_scene::AcquiredBuffer, drmkit_scene::SourceError> {
        Err(drmkit_scene::SourceError::WouldBlock)
    }

    fn release(&mut self, _acquired: drmkit_scene::AcquiredBuffer) {}

    fn binding_model(&self) -> drmkit_scene::BindingModel {
        drmkit_scene::BindingModel::SceneSubmitsFbId
    }

    fn format(&self) -> drmkit_scene::SourceFormat {
        drmkit_scene::SourceFormat {
            fourcc: drmkit_fmt::fourcc::XRGB8888,
            modifier: 0,
            width: 64,
            height: 64,
        }
    }
}

/// A set with no scenes is a set, not an error.
///
/// A compositor starting before any output is connected has one of these, and
/// refusing to construct it would make the caller special-case its own
/// startup.
#[test]
fn a_set_with_no_scenes_is_constructible() {
    let set = empty_set();
    assert_eq!(set.slot_count(), 0);
    assert_eq!(set.scene_count(), 0);
    assert!(
        set.plan_commits(&[], NarrowPolicy::AutoOnModeset)
            .is_empty()
    );
}

/// An index past the end answers nothing rather than panicking.
#[test]
fn an_index_out_of_range_answers_nothing() {
    let mut set = SceneSet::new(vec![drmkit_scene::LayerScene::new(1)]);
    assert!(set.scene(0).is_some());
    assert!(set.scene(1).is_none());
    assert!(set.scene(usize::MAX).is_none());
    assert!(set.scene_mut(99).is_none());
}

/// A layer with no targets is refused.
#[test]
fn a_layer_with_no_targets_is_refused() {
    let mut set = SceneSet::new(vec![drmkit_scene::LayerScene::new(1)]);

    let error = set
        .add_layer(&LayerSpec {
            source: source(),
            targets: Vec::new(),
        })
        .expect_err("a layer that appears nowhere is a caller bug, not a no-op");

    assert_eq!(error, SetError::NoTargets);
}

/// A target naming a scene the set does not have is refused.
#[test]
fn a_target_naming_no_scene_is_refused() {
    let mut set = empty_set();

    let error = set
        .add_layer(&LayerSpec {
            source: source(),
            targets: vec![Target {
                scene_index: 0,
                display: drmkit_scene::DisplayParams::default(),
                force_composited: false,
            }],
        })
        .expect_err("there is no scene 0");

    assert_eq!(error, SetError::NoSuchScene { index: 0, count: 0 });
}

/// A spec with one bad target adds nothing at all.
///
/// Checked before anything is added. Adding the good targets first and then
/// failing would leave the layer on some outputs and not others, with a
/// handle the caller never received to remove it by.
#[test]
fn a_spec_with_one_bad_target_leaves_the_set_untouched() {
    let mut set = SceneSet::new(vec![
        drmkit_scene::LayerScene::new(1),
        drmkit_scene::LayerScene::new(2),
    ]);

    let error = set
        .add_layer(&LayerSpec {
            source: source(),
            targets: vec![
                Target {
                    scene_index: 0,
                    display: drmkit_scene::DisplayParams::default(),
                    force_composited: false,
                },
                Target {
                    scene_index: 7,
                    display: drmkit_scene::DisplayParams::default(),
                    force_composited: false,
                },
            ],
        })
        .expect_err("scene 7 does not exist");

    assert_eq!(error, SetError::NoSuchScene { index: 7, count: 2 });
    assert_eq!(
        set.scene(0).map(drmkit_scene::LayerScene::len),
        Some(0),
        "the good target must not have been added before the bad one was found"
    );
}

/// A mirrored layer reaches every target scene, and removing it clears them
/// all.
#[test]
fn a_mirrored_layer_reaches_every_target_and_leaves_together() {
    let mut set = SceneSet::new(vec![
        drmkit_scene::LayerScene::new(1),
        drmkit_scene::LayerScene::new(2),
    ]);

    let handle = set
        .add_layer(&LayerSpec {
            source: source(),
            targets: vec![
                Target {
                    scene_index: 0,
                    display: drmkit_scene::DisplayParams::default(),
                    force_composited: false,
                },
                Target {
                    scene_index: 1,
                    display: drmkit_scene::DisplayParams::default(),
                    force_composited: true,
                },
            ],
        })
        .expect("both scenes exist");

    assert!(handle.is_valid());
    assert_eq!(set.scene(0).map(drmkit_scene::LayerScene::len), Some(1));
    assert_eq!(set.scene(1).map(drmkit_scene::LayerScene::len), Some(1));

    // The per-target flag reaches the layer it was meant for, and only it.
    let composited = |index: usize| {
        set.scene(index)
            .and_then(|scene| scene.handles().next())
            .and_then(|handle| set.scene(index)?.layer(handle))
            .map(drmkit_scene::SceneLayer::is_force_composited)
    };
    assert_eq!(composited(0), Some(false));
    assert_eq!(
        composited(1),
        Some(true),
        "targets carry their own flags; one setting it must not set the other"
    );

    set.remove_layer(handle);
    assert_eq!(
        set.scene(0).map(drmkit_scene::LayerScene::len),
        Some(0),
        "removing a mirrored layer removes every copy, or the outputs that \
         keep theirs go on scanning out content the caller has forgotten"
    );
    assert_eq!(set.scene(1).map(drmkit_scene::LayerScene::len), Some(0));
}

/// A handle that names nothing is ignored.
///
/// The default handle is what an uninitialized field carries, and it must not
/// remove whatever happens to be first.
#[test]
fn removing_with_a_stale_or_default_handle_is_a_no_op() {
    let mut set = SceneSet::new(vec![drmkit_scene::LayerScene::new(1)]);
    let handle = set
        .add_layer(&LayerSpec {
            source: source(),
            targets: vec![Target {
                scene_index: 0,
                display: drmkit_scene::DisplayParams::default(),
                force_composited: false,
            }],
        })
        .expect("scene 0 exists");

    set.remove_layer(SetLayerHandle::default());
    assert_eq!(
        set.scene(0).map(drmkit_scene::LayerScene::len),
        Some(1),
        "a default handle is not a license to remove layer one"
    );

    set.remove_layer(handle);
    assert_eq!(set.scene(0).map(drmkit_scene::LayerScene::len), Some(0));

    // And again, now that it names a slot that has been emptied.
    set.remove_layer(handle);
}

fn one_target() -> Vec<Target> {
    vec![Target {
        scene_index: 0,
        display: drmkit_scene::DisplayParams::default(),
        force_composited: false,
    }]
}

/// A removed layer's slot is reused, as the reference reuses it, and the
/// old handle does not answer for the layer that took it.
///
/// Without reuse, a set whose layers come and go -- a notification, a
/// tooltip -- grew by a slot every time.
#[test]
fn a_removed_layers_slot_is_reused_and_its_old_handle_is_stale() {
    let mut set = SceneSet::new(vec![drmkit_scene::LayerScene::new(1)]);
    let spec = LayerSpec {
        source: source(),
        targets: one_target(),
    };

    let first = set.add_layer(&spec).expect("scene 0 exists");
    for _ in 0..8 {
        let handle = set.add_layer(&spec).expect("scene 0 exists");
        set.remove_layer(handle);
    }
    assert_eq!(set.layers.len(), 2, "two live at most, so two slots");

    set.remove_layer(first);
    let second = set.add_layer(&spec).expect("scene 0 exists");
    assert_ne!(second, first, "a reused slot carries a new generation");
    set.remove_layer(first);
    assert_eq!(
        set.scene(0).map(drmkit_scene::LayerScene::len),
        Some(1),
        "the old handle must not remove the layer that took its slot"
    );
}

/// Records the plane calls a shared source sees.
#[derive(Default)]
struct Binding {
    bound: Vec<u32>,
    unbound: Vec<u32>,
}

impl drmkit_scene::LayerBufferSource for Binding {
    fn acquire(&mut self) -> Result<drmkit_scene::AcquiredBuffer, drmkit_scene::SourceError> {
        Err(drmkit_scene::SourceError::WouldBlock)
    }

    fn release(&mut self, _acquired: drmkit_scene::AcquiredBuffer) {}

    fn format(&self) -> drmkit_scene::SourceFormat {
        Stub.format()
    }

    fn bind_to_plane(&mut self, plane_id: u32) -> Result<(), drmkit_scene::SourceError> {
        self.bound.push(plane_id);
        Ok(())
    }

    fn unbind_from_plane(&mut self, plane_id: u32) {
        self.unbound.push(plane_id);
    }
}

/// Binding a copy to a plane reaches the shared source, as the reference
/// forwards it. Swallowed, a driver-owned producer was never bound.
#[test]
fn plane_binding_reaches_the_shared_source() {
    let mut set = SceneSet::new(vec![drmkit_scene::LayerScene::new(1)]);
    let shared = std::rc::Rc::new(std::cell::RefCell::new(Binding::default()));
    set.add_layer(&LayerSpec {
        source: shared.clone(),
        targets: one_target(),
    })
    .expect("scene 0 exists");

    let scene = set.scene_mut(0).expect("scene 0");
    let handle = scene.handles().next().expect("the copy");
    let layer = scene.layer_mut(handle).expect("the copy");
    layer.source_mut().bind_to_plane(31).expect("bind");
    layer.source_mut().unbind_from_plane(31);

    assert_eq!(shared.borrow().bound, [31]);
    assert_eq!(shared.borrow().unbound, [31]);
}

/// Removing a scene leaves a hole, and the indices after it do not move.
///
/// The index is the caller's handle to an output. Compacting would have every
/// stored index silently start naming its neighbor.
#[test]
fn removing_a_scene_leaves_a_hole_rather_than_renumbering() {
    let mut set = SceneSet::new(vec![
        drmkit_scene::LayerScene::new(1),
        drmkit_scene::LayerScene::new(2),
        drmkit_scene::LayerScene::new(3),
    ]);

    set.remove_scene(1);

    assert_eq!(set.slot_count(), 3, "the slot stays");
    assert_eq!(set.scene_count(), 2, "but it holds nothing");
    assert!(set.scene(1).is_none());
    assert_eq!(
        set.scene(2).map(drmkit_scene::LayerScene::crtc_id),
        Some(3),
        "scene 2 is still scene 2"
    );
}

/// Removing out of range, or twice, is a no-op.
#[test]
fn removing_a_scene_that_is_not_there_is_a_no_op() {
    let mut set = SceneSet::new(vec![drmkit_scene::LayerScene::new(1)]);

    set.remove_scene(99);
    set.remove_scene(0);
    set.remove_scene(0);

    assert_eq!(set.scene_count(), 0);
    assert_eq!(set.slot_count(), 1);
}

/// A new scene fills a hole before growing the set.
///
/// An output that comes and goes would otherwise leave a slot behind each
/// time, and a laptop docking all day would accumulate them.
#[test]
fn a_new_scene_fills_a_hole_before_growing_the_set() {
    let mut set = SceneSet::new(vec![
        drmkit_scene::LayerScene::new(1),
        drmkit_scene::LayerScene::new(2),
    ]);
    set.remove_scene(0);

    let index = set.add_scene(drmkit_scene::LayerScene::new(3));

    assert_eq!(index, 0, "the hole was reused");
    assert_eq!(set.slot_count(), 2, "and the set did not grow");
    assert_eq!(set.scene(0).map(drmkit_scene::LayerScene::crtc_id), Some(3));
}

/// With no hole, a new scene goes on the end.
#[test]
fn a_new_scene_with_no_hole_to_fill_goes_on_the_end() {
    let mut set = SceneSet::new(vec![drmkit_scene::LayerScene::new(1)]);

    assert_eq!(set.add_scene(drmkit_scene::LayerScene::new(2)), 1);
    assert_eq!(set.slot_count(), 2);
}

/// The plan reflects the holes and the caller's modeset list.
#[test]
fn the_commit_plan_follows_the_set_and_what_the_caller_says_needs_a_modeset() {
    let mut set = SceneSet::new(vec![
        drmkit_scene::LayerScene::new(1),
        drmkit_scene::LayerScene::new(2),
        drmkit_scene::LayerScene::new(3),
    ]);
    set.remove_scene(1);

    assert_eq!(
        set.plan_commits(&[], NarrowPolicy::AutoOnModeset),
        vec![vec![0, 2]],
        "nothing is modesetting, so the two engaged outputs stay atomic"
    );
    assert_eq!(
        set.plan_commits(&[2], NarrowPolicy::AutoOnModeset),
        vec![vec![2], vec![0]],
        "one modesetting and one steady is mixed, and the modeset leads"
    );
    assert_eq!(
        set.plan_commits(&[1], NarrowPolicy::AutoOnModeset),
        vec![vec![0, 2]],
        "a modeset named on a hole changes nothing -- there is no output there"
    );
}

/// A mirrored copy can be read for composition, as the reference forwards
/// `map`: the scene reads it through `with_mapping`, which the shared source
/// forwards with its borrow held for the read. Without it every mirrored copy
/// that fell to composition left the screen.
#[test]
#[ignore = "needs a DRM device; run under the vkms lane with --include-ignored"]
fn a_mirrored_copy_can_be_read_for_composition_vkms() {
    use drmkit_dumb::MapAccess;
    use drmkit_scene::LayerBufferSource as _;

    let path = std::env::var("DRMKIT_TEST_CARD").unwrap_or_else(|_| "/dev/dri/card0".to_owned());
    let device = match drmkit_core::Device::open(&path) {
        Ok(device) => device,
        Err(error) => {
            assert!(
                std::env::var_os("DRMKIT_REQUIRE_MASTER").is_none(),
                "{path}: {error}, but DRMKIT_REQUIRE_MASTER is set"
            );
            drmkit_testkit::skipped(&format!("no DRM device at {path} ({error})"));
            return;
        }
    };
    let mut painted = drmkit_scene_sources::DumbBufferSource::create(
        &device,
        16,
        16,
        drmkit_fmt::fourcc::ARGB8888,
    )
    .expect("a 16x16 dumb buffer");
    painted
        .map(MapAccess::Write)
        .expect("a dumb buffer maps")
        .pixels_mut()
        .fill(0x5a);
    let shared: std::rc::Rc<std::cell::RefCell<dyn drmkit_scene::LayerBufferSource>> =
        std::rc::Rc::new(std::cell::RefCell::new(painted));

    let mut set = SceneSet::new(vec![
        drmkit_scene::LayerScene::new(1),
        drmkit_scene::LayerScene::new(2),
    ]);
    set.add_layer(&LayerSpec {
        source: shared,
        targets: (0..2)
            .map(|scene_index| Target {
                scene_index,
                display: drmkit_scene::DisplayParams::default(),
                force_composited: true,
            })
            .collect(),
    })
    .expect("both scenes exist");

    for index in 0..2 {
        let scene = set.scene_mut(index).expect("the scene");
        let handle = scene.handles().next().expect("its copy");
        let layer = scene.layer_mut(handle).expect("its copy");
        let mut seen = Vec::new();
        layer
            .source_mut()
            .with_mapping(MapAccess::Read, &mut |mapping| {
                seen.extend_from_slice(mapping.row(0).unwrap_or_default());
            })
            .unwrap_or_else(|error| panic!("scene {index}: the copy cannot be read: {error}"));
        assert_eq!(seen.len(), 16 * 4, "scene {index}: one row of ARGB8888");
        assert!(seen.iter().all(|byte| *byte == 0x5a), "scene {index}");
    }
}