Repository navigation
Expand file tree
/
Copy pathoutput.cpp
More file actions
2270 lines (2094 loc) · 89.8 KB
/
Copy pathoutput.cpp
File metadata and controls
2270 lines (2094 loc) · 89.8 KB
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
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "output/output.h"
#include "config/config.h"
#include "config/resolve.h"
#include "core/log.h"
#include "core/tracy.h"
#include "input/cursor.h"
#include "input/seat.h"
#include "layer/layer_surface.h"
#include "lock/session_lock.h"
#include "output/cursor_plane_pace.h"
#include "output/format_sequence.h"
#include "output/frame_schedule.h"
#include "output/gamma_transition.h"
#include "output/hdr_format.h"
#include "output/hdr_metadata.h"
#include "output/identity.h"
#include "output/mode_selection.h"
#include "output/rendered_state_commit.h"
#include "output/sdr_format.h"
#include "overview/overview.h"
#include "scene/cheatsheet.h"
#include "scene/config_banner.h"
#include "scene/node.h"
#include "scene/quit_confirm.h"
#include "server/color_manager.h"
#include "server/ipc.h"
#include "server/server.h"
#include "view/view.h"
#include "wlr.h"
#include "workspace/scratchpad.h"
#include "workspace/workspace.h"
extern "C" {
#include <umbrielfx/render/effect.h>
#include <wlr/util/transform.h>
}
#include <algorithm>
#include <cassert>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <drm_fourcc.h>
#include <format>
#ifdef TRACY_ENABLE
#include <set>
#endif
namespace umbriel {
namespace {
constexpr Logger kLog("output");
constexpr int kFrameRetryDelayMs = 16;
std::string_view directScanoutReason(wlr_scene_direct_scanout_status status) {
switch (status) {
case WLR_SCENE_DIRECT_SCANOUT_ACTIVE:
return "";
case WLR_SCENE_DIRECT_SCANOUT_DISABLED:
return "disabled";
case WLR_SCENE_DIRECT_SCANOUT_NO_CANDIDATE:
return "no_candidate";
case WLR_SCENE_DIRECT_SCANOUT_COMPOSITED:
return "composited";
case WLR_SCENE_DIRECT_SCANOUT_EFFECTS:
return "effects";
case WLR_SCENE_DIRECT_SCANOUT_COLOR:
return "color_conversion";
case WLR_SCENE_DIRECT_SCANOUT_CAPTURE:
return "capture";
case WLR_SCENE_DIRECT_SCANOUT_CROPPED:
return "cropped";
case WLR_SCENE_DIRECT_SCANOUT_TRANSFORM:
return "transform";
case WLR_SCENE_DIRECT_SCANOUT_MODESET:
return "modeset";
case WLR_SCENE_DIRECT_SCANOUT_RENDER_LOCKED:
return "render_locked";
case WLR_SCENE_DIRECT_SCANOUT_SOFTWARE_CURSOR:
return "software_cursor";
case WLR_SCENE_DIRECT_SCANOUT_REJECTED:
return "rejected";
case WLR_SCENE_DIRECT_SCANOUT_DEBUG_DAMAGE:
return "debug_damage";
}
return "unknown";
}
struct OutputFrameScope {
explicit OutputFrameScope(Server& owner) : server(owner) { server.beginOutputFrame(); }
~OutputFrameScope() { server.endOutputFrame(); }
Server& server;
};
wlr_box
pendingSceneBox(const wlr_output& output, const wlr_output_state& state, const wlr_scene_output& sceneOutput) {
int width = output.width;
int height = output.height;
if ((state.committed & WLR_OUTPUT_STATE_MODE) != 0) {
if (state.mode_type == WLR_OUTPUT_STATE_MODE_FIXED && state.mode != nullptr) {
width = state.mode->width;
height = state.mode->height;
} else if (state.mode_type == WLR_OUTPUT_STATE_MODE_CUSTOM) {
width = state.custom_mode.width;
height = state.custom_mode.height;
}
}
const wl_output_transform transform =
(state.committed & WLR_OUTPUT_STATE_TRANSFORM) != 0 ? state.transform : output.transform;
wlr_output_transform_coords(transform, &width, &height);
const float scale = (state.committed & WLR_OUTPUT_STATE_SCALE) != 0 ? state.scale : output.scale;
if (scale > 0.0F) {
width = static_cast<int>(std::ceil(static_cast<double>(width) / scale));
height = static_cast<int>(std::ceil(static_cast<double>(height) / scale));
}
return {.x = sceneOutput.x, .y = sceneOutput.y, .width = width, .height = height};
}
// Staging any mode, even the live one, makes wlroots request ALLOW_MODESET, which makes the display resync.
wlr_output_mode* keepLiveModeOrStage(wlr_output_state& state, const wlr_output& output, wlr_output_mode* mode) {
if (!liveModeMatches(output, mode)) {
wlr_output_state_set_mode(&state, mode);
return nullptr;
}
kLog.info("output '{}': keeping live mode {}x{}@{}mHz", output.name, mode->width, mode->height, mode->refresh);
return mode;
}
#ifdef TRACY_ENABLE
// Tracy keeps a plot's name pointer and reads it while a capture runs, so
// the per-output names live for the rest of the process.
const char* tracyPlotName(std::string name) {
static std::set<std::string> names;
return names.insert(std::move(name)).first->c_str();
}
#endif
} // namespace
OutputIdentity Output::identity() const {
const auto text = [](const char* value) { return value != nullptr ? std::string_view(value) : std::string_view(); };
return m_output != nullptr
? OutputIdentity{
.connector = text(m_output->name),
.make = text(m_output->make),
.model = text(m_output->model),
.serial = text(m_output->serial),
}
: OutputIdentity{};
}
Output::Output(Server& server, wlr_output* output)
: m_server(&server), m_output(output), m_defaultScale(output->scale),
m_hdrStaticMetadata(hdrStaticMetadataForOutput(output)) {
m_output->data = this;
wlr_output_init_render(m_output, m_server->allocator(), m_server->renderer());
// Create the scene output before the initial configuration so startup and
// resume modesets carry rendered content instead of wlroots' empty buffer.
m_sceneOutput = wlr_scene_output_create(m_server->scene(), m_output);
if (m_sceneOutput == nullptr) {
kLog.error("output '{}': failed to create scene output", m_output->name);
std::abort();
}
wlr_scene_output_set_direct_scanout_enabled(m_sceneOutput, configuredDirectScanoutEnabled());
m_frame.notify = onFrame;
wl_signal_add(&m_output->events.frame, &m_frame);
m_requestState.notify = onRequestState;
wl_signal_add(&m_output->events.request_state, &m_requestState);
m_present.notify = onPresent;
wl_signal_add(&m_output->events.present, &m_present);
m_destroy.notify = onDestroy;
wl_signal_add(&m_output->events.destroy, &m_destroy);
m_frameRetryTimer =
wl_event_loop_add_timer(wl_display_get_event_loop(m_server->display()), onFrameRetryTimer, this);
m_directScanoutTimer =
wl_event_loop_add_timer(wl_display_get_event_loop(m_server->display()), onDirectScanoutTimer, this);
applyCursorConfig();
m_desktopEnabled = m_server->initialOutputEnabled(*this);
if (!applyConfiguredState()) {
// Do not advertise a logical output whose initial backend enable failed.
// Keeping it disabled lets a later output-enable action retry the commit.
m_desktopEnabled = false;
}
updateSceneSdrWhite();
if (desktopEnabled()) {
wlr_output_layout_output* layoutOutput = addToLayout();
wlr_scene_output_layout_add_output(m_server->sceneLayout(), layoutOutput, m_sceneOutput);
}
m_server->resolveOutputEffect(*this);
applyOutputEffects();
for (uint32_t layer = 0; layer < kLayerCount; ++layer) {
m_layerTrees[layer] = wlr_scene_tree_create(m_server->shellLayerTree(layer));
m_layerPopupTrees[layer] = wlr_scene_tree_create(m_server->shellLayerTree(layer));
}
m_backgroundUpdate.notify = onBackgroundUpdate;
if (!wlr_scene_node_add_update_listener(
&layerTree(ZWLR_LAYER_SHELL_V1_LAYER_BACKGROUND)->node, &m_backgroundUpdate
)) {
kLog.error("output '{}': failed to watch background scene updates", m_output->name);
std::abort();
}
m_backgroundPopupUpdate.notify = onBackgroundPopupUpdate;
if (!wlr_scene_node_add_update_listener(
&layerPopupTree(ZWLR_LAYER_SHELL_V1_LAYER_BACKGROUND)->node, &m_backgroundPopupUpdate
)) {
kLog.error("output '{}': failed to watch background popup updates", m_output->name);
std::abort();
}
m_viewRoot = wlr_scene_tree_create(m_server->xdgTree());
m_fullscreenRoot = wlr_scene_tree_create(m_server->fullscreenTree());
m_pinnedRoot = wlr_scene_tree_create(m_server->pinnedTree());
arrangeLayers();
m_workspaceGroup = std::make_unique<WorkspaceGroup>(*m_server, *this);
}
bool Output::configuredEnabled() const {
const OutputRule* rule = findOutputRule(config(), identity());
return rule != nullptr ? rule->enabled : outputCanAutoEnable(m_output);
}
void Output::scheduleEffectFrame() {
if (m_handlingFrame) {
return; // handleFrame arms the next effect frame after its tick
}
m_effectFrameDue = true;
wlr_output_schedule_frame(m_output);
}
void Output::scheduleAudioFrame() {
if (m_server->sessionLocked() || !outputFrameAllowed(m_server->stopping(), m_server->session())) {
m_effectAudio = {};
wlr_scene_output_set_effect_audio(m_sceneOutput, m_effectAudio.data());
return;
}
if (!wlr_scene_output_audio_active(m_sceneOutput)) {
return;
}
timespec now{};
clock_gettime(CLOCK_MONOTONIC, &now);
armEffectFrame(static_cast<uint64_t>(now.tv_sec) * 1000 + static_cast<uint64_t>(now.tv_nsec) / 1'000'000);
}
bool Output::audioPending() const {
return m_effectAudio != m_server->effects().audio() && wlr_scene_output_audio_active(m_sceneOutput);
}
void Output::applyOutputEffects() {
EffectRegistry& registry = m_server->effects();
const Effects& settings = config().effects;
// Nothing configured: touch nothing (no addon, no scene calls). The registry's counts are zero too; a bound
// screen or cursor slot keeps a ledger instance, so it is still detached below.
if (settings.presets.empty() && !registry.active() && !registry.persistentReferenced()) {
return;
}
wlr_scene_output_set_effect_capture_policy(m_sceneOutput, settings.inCapture);
const std::string_view screenName = m_screenEffectSlot.effectiveName();
const std::string_view cursorName = m_server->cursorEffectSlot().effectiveName();
const bool suspended = registry.ledger().suspended();
fx_effect_shader* screen = suspended ? nullptr : registry.preset(screenName, EffectKind::Screen);
const EffectPreset* screenPreset = screen != nullptr ? registry.presetConfig(screenName) : nullptr;
fx_effect_shader* cursor = suspended ? nullptr : registry.preset(cursorName, EffectKind::Cursor);
const EffectPreset* cursorPreset = cursor != nullptr ? registry.presetConfig(cursorName) : nullptr;
bool advancing = true;
#ifdef UMBRIEL_HARNESS
advancing = !m_server->animationClockFrozen();
#endif
wlr_scene_output_set_effect_time(m_sceneOutput, m_server->animationClockMsec());
m_outputEffectsTimed = false;
// Register demand after the cursor program and motion history have been updated.
const auto bind = [&](const void* owner, fx_effect_shader* shader, bool visible) {
const bool motion = fx_effect_shader_reads(shader, "umbriel_pointer_history")
|| fx_effect_shader_reads(shader, "umbriel_pointer_path");
const bool readsTime = fx_effect_shader_reads(shader, "umbriel_time")
|| (motion && wlr_scene_output_cursor_motion_active(m_sceneOutput));
m_outputEffectsTimed = m_outputEffectsTimed || (readsTime && visible);
registry.updateInstance(
owner, {.output = this, .visible = visible, .readsTime = readsTime, .advancing = advancing}
);
};
if (screenPreset != nullptr) {
fx_animation_parameters parameters{};
registry.fillTimeUniforms(parameters, m_effectSeconds, *screenPreset, screen);
bind(this, screen, m_output->enabled);
wlr_scene_output_set_screen_effect(m_sceneOutput, screen, ¶meters);
} else {
wlr_scene_output_set_screen_effect(m_sceneOutput, nullptr, nullptr);
registry.removeInstance(this);
}
const Cursor* pointer = m_server->cursor();
if (cursorPreset != nullptr && pointer != nullptr) {
const double lx = pointer->wlr()->x;
const double ly = pointer->wlr()->y;
const bool here = wlr_output_layout_output_at(m_server->outputLayout(), lx, ly) == m_output;
fx_animation_parameters parameters{};
registry.fillTimeUniforms(parameters, m_effectSeconds, *cursorPreset, cursor);
wlr_scene_output_set_cursor_effect(m_sceneOutput, cursor, ¶meters, cursorPreset->radius);
// A newly set cursor program draws nothing until the pointer is pushed after it.
wlr_scene_output_set_effect_time(m_sceneOutput, m_server->animationClockMsec());
wlr_scene_output_set_effect_pointer(m_sceneOutput, lx, ly, pointer->visible());
bind(&m_cursorEffectOwner, cursor, m_output->enabled && here && pointer->visible());
} else {
wlr_scene_output_set_cursor_effect(m_sceneOutput, nullptr, nullptr, 0);
registry.removeInstance(&m_cursorEffectOwner);
}
}
void Output::scheduleEffectCaptureRelease() {
if (m_effectCaptureBuilt && outputFrameAllowed(m_server->stopping(), m_server->session())) {
wlr_output_schedule_frame(m_output);
}
}
int Output::externalRenderLocks() const { return m_output->attach_render_locks - (m_animationRenderLocked ? 1 : 0); }
bool Output::effectCapturePending(int captureLocks) const {
// Keyed on configuration, not instances: a close snapshot keeps its window slots after its instances leave.
return captureLocks > 0 && !config().effects.inCapture && m_server->effects().inPlaceReferenced();
}
bool Output::captureExclusionPending(int captureLocks) const {
return captureLocks > 0 && umbrielfx_scene_has_capture_exclusion(m_sceneOutput->scene);
}
unsigned Output::effectEligible() const { return m_server->effects().ledger().eligible(this); }
wlr_box Output::layoutBox() const {
wlr_box box{.x = m_arrangedLayoutX, .y = m_arrangedLayoutY, .width = 0, .height = 0};
wlr_output_effective_resolution(m_output, &box.width, &box.height);
if (const wlr_output_layout_output* layoutOutput = wlr_output_layout_get(m_server->outputLayout(), m_output)) {
box.x = layoutOutput->x;
box.y = layoutOutput->y;
}
return box;
}
wlr_box Output::usableArea() const {
wlr_box area = m_localUsableArea;
const wlr_box box = layoutBox();
area.x += box.x;
area.y += box.y;
return area;
}
HdrMode Output::hdrMode() const {
const OutputRule* rule = findOutputRule(config(), identity());
return rule != nullptr ? rule->hdr : HdrMode::Off;
}
bool Output::hdrRequested() const {
if (wlr_surface* surface = m_server->seat()->wlr()->keyboard_state.focused_surface) {
if (View* view = View::fromSurface(surface); view != nullptr && view->mapped() && view->currentOutput() == this) {
if (const std::optional<HdrMode> mode = view->resolvedRules().hdr) {
const bool fullscreen = view->layoutFullscreen() || view->currentFullscreen();
return hdrEnabled(*mode, fullscreen, autoHdrEligible(view));
}
}
}
const HdrMode mode = hdrMode();
return hdrEnabled(mode, m_fullscreenHdrRequested, m_autoHdrOwner != nullptr);
}
bool Output::hdrActive() const { return m_output->image_description != nullptr; }
bool Output::automaticHdrAvailable() const {
if (!m_output->enabled || !m_desktopEnabled || !m_hdrAvailable) {
return false;
}
HdrMode mode = hdrMode();
if (wlr_surface* surface = m_server->seat()->wlr()->keyboard_state.focused_surface) {
if (View* view = View::fromSurface(surface); view != nullptr && view->mapped() && view->currentOutput() == this) {
mode = view->resolvedRules().hdr.value_or(mode);
}
}
return mode == HdrMode::Auto;
}
void Output::updateHdrAvailability(bool activationRejected) {
m_hdrAvailable = false;
if (!m_output->enabled
|| !m_desktopEnabled
|| (m_output->supported_transfer_functions & WLR_COLOR_TRANSFER_FUNCTION_ST2084_PQ) == 0
|| (m_output->supported_primaries & WLR_COLOR_NAMED_PRIMARIES_BT2020) == 0
|| !m_server->renderer()->features.output_color_transform) {
return;
}
if (hdrActive()) {
m_hdrAvailable = true;
return;
}
// A successful SDR fallback after a rejected HDR request is not evidence
// that HDR became available. A later configuration retry can probe again.
if (activationRejected) {
return;
}
const wlr_drm_format_set* formats = wlr_output_get_primary_formats(m_output, m_server->allocator()->buffer_caps);
wlr_output_state state{};
wlr_output_state_init(&state);
state.allow_reconfiguration = true;
wlr_output_state_set_color_transform(&state, nullptr);
const auto description = makeHdrOutputDescription(m_output->default_primaries, m_hdrStaticMetadata);
if (wlr_output_state_set_image_description(&state, &description)) {
m_hdrAvailable = selectHdrRenderFormat(m_output->render_format, [&](uint32_t format) {
if (formats != nullptr && wlr_drm_format_set_get(formats, format) == nullptr) {
return false;
}
wlr_output_state_set_render_format(&state, format);
if (wlr_output_test_state(m_output, &state)) {
return true;
}
// The real activation path can drop VRR when HDR needs it disabled.
if (m_output->adaptive_sync_supported
&& m_output->adaptive_sync_status == WLR_OUTPUT_ADAPTIVE_SYNC_ENABLED) {
wlr_output_state_set_adaptive_sync_enabled(&state, false);
return wlr_output_test_state(m_output, &state);
}
return false;
}).has_value();
}
wlr_output_state_finish(&state);
if (m_hdrAvailable && hdrRequested()) {
// A mode change can make a previously rejected request usable. Retry at
// the frame boundary instead of treating its old SDR fallback as final.
m_hdrTransition.recordCommit(true, false, true);
scheduleFullFrame();
}
}
bool Output::bitDepthActive() const {
return deriveTenBitSdrActive(m_output->enabled, hdrActive(), m_output->render_format);
}
float Output::configuredSdrWhite() const {
const OutputRule* rule = findOutputRule(config(), identity());
return rule != nullptr ? rule->sdrWhite : 203.0F;
}
float Output::sdrWhite() const { return m_runtimeSdrWhite.value_or(configuredSdrWhite()); }
SdrTransfer Output::configuredSdrTransfer() const {
const OutputRule* rule = findOutputRule(config(), identity());
return rule != nullptr ? rule->sdrTransfer : SdrTransfer::Gamma22;
}
void Output::setRuntimeSdrWhite(float nits) {
if (m_runtimeSdrWhite && *m_runtimeSdrWhite == nits) {
return;
}
m_runtimeSdrWhite = nits;
kLog.info("output '{}': live SDR white {} cd/m2", m_output->name, nits);
updateSceneSdrWhite();
markBlurBackgroundDirty();
m_server->updateColorPreferences();
wlr_output_schedule_frame(m_output);
}
int Output::configuredBitDepth() const {
const OutputRule* rule = findOutputRule(config(), identity());
return rule != nullptr ? rule->bitDepth : 8;
}
bool Output::configuredDirectScanoutEnabled() const {
const OutputRule* rule = findOutputRule(config(), identity());
return rule == nullptr || rule->directScanout;
}
bool Output::configuredTearingAllowed() const {
const OutputRule* rule = findOutputRule(config(), identity());
return rule != nullptr && rule->allowTearing;
}
bool Output::configuredCyclicWorkspaces() const {
const OutputRule* rule = findOutputRule(config(), identity());
return rule != nullptr && rule->cyclicWorkspaces;
}
View* Output::tearingCandidate() const {
const Workspace* workspace = m_workspaceGroup != nullptr ? m_workspaceGroup->active() : nullptr;
if (workspace == nullptr) {
return nullptr;
}
const auto eligible = [this](View* view) {
return view != nullptr
&& view->mapped()
&& view->onActiveWorkspace()
&& view->currentOutput() == this
&& view->layoutFullscreen()
&& view->currentFullscreen();
};
if (View* focused = workspace->focusedView(); eligible(focused)) {
return focused;
}
const auto& views = workspace->allViews();
const auto candidate = std::ranges::find_if(views, eligible);
return candidate != views.end() ? *candidate : nullptr;
}
bool Output::clientTearingHintAsync(const View* view) const {
if (view == nullptr || m_server->tearingControlManager() == nullptr) {
return false;
}
return wlr_tearing_control_manager_v1_surface_hint_from_surface(
m_server->tearingControlManager(), view->rootSurface()
)
== WP_TEARING_CONTROL_V1_PRESENTATION_HINT_ASYNC;
}
bool Output::tearingEligible(View* view) const {
if (view == nullptr || tearingCandidate() != view) {
return false;
}
return tearingEnabled(configuredTearingAllowed(), view->resolvedRules().allowTearing, clientTearingHintAsync(view));
}
bool Output::tearingRequested() const { return tearingEligible(tearingCandidate()); }
std::optional<bool> Output::lastPresentationVsync() const {
if (!m_lastPresentationFlags || *m_lastPresentationFlags == 0) {
return std::nullopt;
}
return (*m_lastPresentationFlags & WLR_OUTPUT_PRESENT_VSYNC) != 0;
}
void Output::resetTearingState() {
m_tearingFallbackReason.clear();
m_tearingRecovery.reset();
wlr_output_schedule_frame(m_output);
}
void Output::applyDirectScanoutConfig() {
wlr_scene_output_set_direct_scanout_enabled(m_sceneOutput, configuredDirectScanoutEnabled());
}
void Output::setHdrFallbackReason(std::string_view reason) {
if (m_hdrFallbackReason == reason) {
return;
}
m_hdrFallbackReason = reason;
if (!reason.empty()) {
kLog.warn("output '{}': HDR unavailable: {}", m_output->name, reason);
}
}
void Output::setBitDepthFallbackReason(std::string_view reason) {
if (m_bitDepthFallbackReason == reason) {
return;
}
m_bitDepthFallbackReason = reason;
if (!reason.empty()) {
kLog.warn("output '{}': 10-bit SDR unavailable: {}", m_output->name, reason);
}
}
void Output::updateSceneSdrWhite() {
if (m_sceneOutput == nullptr) {
return;
}
const float level = hdrActive() ? sdrWhite() : 0.0F;
wlr_scene_output_set_sdr_white_level(m_sceneOutput, level);
updateSceneHdrWhitePoint(wlr_gamma_control_manager_v1_get_control(m_server->gammaManager(), m_output));
}
void Output::updateSceneHdrWhitePoint(wlr_gamma_control_v1* control) {
if (m_sceneOutput == nullptr) {
return;
}
const auto white = hdrWhitePointFromGamma(
control != nullptr ? control->table : nullptr, control != nullptr ? control->ramp_size : 0
);
wlr_scene_output_set_hdr_white_point(m_sceneOutput, white.data());
}
wlr_scene_rect* Output::createConfiguredFrameMask(const wlr_output_state& state) const {
const wlr_box box = pendingSceneBox(*m_output, state, *m_sceneOutput);
if (box.width <= 0 || box.height <= 0) {
kLog.error("output '{}': configured frame has no secure logical extent", m_output->name);
return nullptr;
}
auto color = config().colors.backdrop;
color[3] = 1.0F;
wlr_scene_rect* mask = wlr_scene_rect_create(&m_server->scene()->tree, box.width, box.height, color.data());
if (mask == nullptr) {
kLog.error("output '{}': failed to create secure mask for configured frame", m_output->name);
return nullptr;
}
wlr_scene_node_set_position(&mask->node, box.x, box.y);
wlr_scene_node_raise_to_top(&mask->node);
return mask;
}
bool Output::applyConfiguredState(bool stageGeometry) {
if (m_workspaceGroup != nullptr) {
m_workspaceGroup->abandonReveal();
}
const OutputRule* rule = findOutputRule(config(), identity());
const auto sdrTransfer = configuredSdrTransfer() == SdrTransfer::Srgb ? WLR_COLOR_TRANSFER_FUNCTION_SRGB
: WLR_COLOR_TRANSFER_FUNCTION_GAMMA22;
if (!wlr_scene_output_set_sdr_transfer_function(m_sceneOutput, sdrTransfer)) {
kLog.error("output '{}': failed to apply SDR transfer function", m_output->name);
return false;
}
const std::optional<double> configuredScale = rule != nullptr ? rule->scale : std::nullopt;
const bool enabled = desktopEnabled() && !m_dpmsOff;
wlr_output_state state{};
wlr_output_state_init(&state);
if (stageGeometry && outputEnableNeedsStaging(*m_output, enabled)) {
wlr_output_state_set_enabled(&state, enabled);
}
const bool hdrWasActive = hdrActive();
const bool hdrRequested = this->hdrRequested();
// Stage geometry.
bool scaleStaged = false;
const OutputMode* configuredModeSpec = nullptr;
wlr_output_mode* stagedMode = nullptr;
wlr_output_mode* keptLiveMode = nullptr;
if (enabled && stageGeometry) {
if (rule != nullptr && rule->mode) {
if (wlr_output_is_wl(m_output)) {
kLog.info("output '{}': mode is ignored in nested sessions", m_output->name);
} else {
configuredModeSpec = &*rule->mode;
stagedMode = selectOutputMode(m_output, *rule->mode);
if (stagedMode != nullptr) {
keptLiveMode = keepLiveModeOrStage(state, *m_output, stagedMode);
} else {
wlr_output_state_set_custom_mode(&state, rule->mode->width, rule->mode->height, rule->mode->refreshMHz);
}
}
} else if (!wlr_output_is_wl(m_output)) {
if (wlr_output_mode* mode = wlr_output_preferred_mode(m_output)) {
keptLiveMode = keepLiveModeOrStage(state, *m_output, mode);
}
}
if (configuredScale) {
wlr_output_state_set_scale(&state, static_cast<float>(*configuredScale));
scaleStaged = true;
} else if (m_appliedConfiguredScale) {
wlr_output_state_set_scale(&state, m_defaultScale);
scaleStaged = true;
}
if (rule != nullptr && rule->transform) {
wlr_output_state_set_transform(&state, static_cast<wl_output_transform>(*rule->transform));
}
}
if (enabled && !stageGeometry) {
// Image-description and max-bpc changes may require a modeset even
// though the live mode and geometry stay unchanged.
state.allow_reconfiguration = true;
}
// VRR variants. Try with VRR first (if requested and supported), then without.
const bool vrrRequested = enabled && configuredVrrEnabled();
const bool vrrSupported = m_output->adaptive_sync_supported;
if (vrrRequested && !vrrSupported) {
kLog.warn("output '{}': VRR requested but adaptive sync is not supported", m_output->name);
}
const bool tryVrrOn = vrrRequested && vrrSupported;
// HDR pre-flight.
std::string_view earlyHdrFail;
bool imageDescAvailable = false;
wlr_output_image_description hdrDescription{};
if (enabled && hdrRequested) {
if ((m_output->supported_transfer_functions & WLR_COLOR_TRANSFER_FUNCTION_ST2084_PQ) == 0) {
earlyHdrFail = "display does not advertise PQ";
} else if ((m_output->supported_primaries & WLR_COLOR_NAMED_PRIMARIES_BT2020) == 0) {
earlyHdrFail = "display does not advertise BT.2020 primaries";
} else if (!m_server->renderer()->features.output_color_transform) {
earlyHdrFail = "renderer lacks FP16 output transform";
} else {
hdrDescription = makeHdrOutputDescription(m_output->default_primaries, m_hdrStaticMetadata);
if (!wlr_output_state_set_image_description(&state, &hdrDescription)) {
earlyHdrFail = "failed to stage HDR image description";
} else {
imageDescAvailable = true;
}
}
}
const wlr_drm_format_set* primaryFormats =
enabled ? wlr_output_get_primary_formats(m_output, m_server->allocator()->buffer_caps) : nullptr;
const int bitDepth = configuredBitDepth();
const auto tenBitFormatName = [](uint32_t fmt) { return fmt == DRM_FORMAT_XRGB2101010 ? "XR30" : "XB30"; };
const auto isPrimaryFormat = [&](uint32_t fmt) {
return primaryFormats == nullptr || wlr_drm_format_set_get(primaryFormats, fmt) != nullptr;
};
const auto stageVrr = [&](bool vrr) {
if (vrrSupported) {
wlr_output_state_set_adaptive_sync_enabled(&state, vrr);
}
};
const GammaTransitionOps gammaOps{
.clear = [&] { wlr_output_state_set_color_transform(&state, nullptr); },
.apply =
[&] {
wlr_gamma_control_v1* control =
wlr_gamma_control_manager_v1_get_control(m_server->gammaManager(), m_output);
if (wlr_gamma_control_v1_apply(control, &state)) {
return true;
}
if (control != nullptr) {
wlr_gamma_control_v1_send_failed_and_destroy(control);
}
return false;
},
};
// wlroots writes max bpc only in commits that allow a modeset, and the kernel may require one to change
// colorspace or to switch HDR on or off.
const auto allowModesetForColorChange = [&](uint32_t fmt, bool hdr) {
if (colorChangeNeedsModeset(*m_output, fmt, hdr)) {
state.allow_reconfiguration = true;
}
};
const auto stageHdr = [&](uint32_t fmt, bool vrr) -> bool {
if (!isPrimaryFormat(fmt)) {
return false;
}
stageVrr(vrr);
(void)stageGammaForOutputMode(GammaOutputMode::Hdr, gammaOps);
wlr_output_state_set_image_description(&state, &hdrDescription);
wlr_output_state_set_render_format(&state, fmt);
allowModesetForColorChange(fmt, true);
return true;
};
const auto stageSdr = [&](uint32_t fmt, bool vrr) -> bool {
if (fmt != DRM_FORMAT_XRGB8888 && !isPrimaryFormat(fmt)) {
return false;
}
stageVrr(vrr);
(void)stageGammaForOutputMode(GammaOutputMode::Sdr, gammaOps);
wlr_output_state_set_render_format(&state, fmt);
allowModesetForColorChange(fmt, false);
return true;
};
// Run the format sequence, retrying with the preferred mode on failure.
bool anyCommitted = false;
bool usedModeFallback = false;
std::string_view pendingHdrFail = earlyHdrFail;
std::string_view pendingSdr10Fail;
bool hdrRejected = !earlyHdrFail.empty();
if (enabled) {
const FormatSequenceParams seqParams{
.hdrRequested = hdrRequested,
.imageDescAvailable = imageDescAvailable,
.hdrWasActive = hdrWasActive,
.currentRenderFormat = m_output->render_format,
.bitDepth = bitDepth,
.tryVrrOn = tryVrrOn,
.configuredModeSpec = stageGeometry ? configuredModeSpec : nullptr,
.preferredMode = stageGeometry ? preferredFallbackMode(m_output, stagedMode) : nullptr,
.keptLiveMode = keptLiveMode,
.modeFallbackAlreadyWarned = m_modeFallbackWarned,
.vrrDroppedTier = m_vrrDroppedTier,
.earlyHdrFail = earlyHdrFail,
};
const auto commitStagedState = [&] -> FormatCommitResult {
const bool targetHdr = state.image_description != nullptr;
wlr_scene_output_set_sdr_white_level(m_sceneOutput, targetHdr ? sdrWhite() : 0.0F);
wlr_damage_ring_add_whole(&m_sceneOutput->damage_ring);
// The cache may need a new size, format or SDR curve; re-render it in this frame.
markBlurBackgroundDirty();
wlr_output_state frameState{};
wlr_output_state_init(&frameState);
if (!wlr_output_state_copy(&frameState, &state)) {
wlr_output_state_finish(&frameState);
return FormatCommitResult::Retry;
}
wlr_scene_rect* secureMask = nullptr;
const bool unbound = wlr_output_layout_get(m_server->outputLayout(), m_output) == nullptr;
if (stageGeometry && (m_server->sessionLocked() || unbound)) {
// An unbound scene output still samples the scene origin, and a
// locked geometry change can outgrow the permanent blank until the
// layout callback resizes it. Render this configured frame through
// a temporary opaque mask so neither path exposes unrelated content.
secureMask = createConfiguredFrameMask(frameState);
if (secureMask == nullptr) {
wlr_output_state_finish(&frameState);
return FormatCommitResult::Retry;
}
}
const int captureLocks = externalRenderLocks();
wlr_scene_output_state_options sceneOptions{};
sceneOptions.capture_sdr = targetHdr && captureLocks > 0;
sceneOptions.effect_capture_pending = effectCapturePending(captureLocks);
sceneOptions.capture_exclusion = captureExclusionPending(captureLocks);
m_effectCaptureBuilt = sceneOptions.effect_capture_pending || sceneOptions.capture_exclusion;
const RenderedStateCommitResult commitResult = commitRenderedState(
frameState,
[&](wlr_output_state& pending) {
return wlr_scene_output_build_state(m_sceneOutput, &pending, &sceneOptions);
},
[&](const wlr_output_state& pending) {
SceneCommit observation(*this, pending);
return wlr_output_commit_state(m_output, &pending);
}
);
if (secureMask != nullptr) {
wlr_scene_node_destroy(&secureMask->node);
}
const bool commitAttempted = commitResult == RenderedStateCommitResult::Committed
|| commitResult == RenderedStateCommitResult::CommitFailed;
const bool commitOk = commitResult == RenderedStateCommitResult::Committed;
if (commitResult == RenderedStateCommitResult::MissingBuffer) {
kLog.error("output '{}': configured scene state has no buffer", m_output->name);
}
const bool recoveringFromFailedCommit = m_tearingRecovery.regularCommitPending();
if (commitAttempted) {
m_tearingRecovery.recordCommit(false, commitOk);
}
if (commitOk) {
m_lastCommitTearing = false;
m_trackingPresentation = true;
m_trackedPresentationCommitSeq = m_output->commit_seq;
m_lastPresentationPresented.reset();
m_lastPresentationFlags.reset();
if (recoveringFromFailedCommit && !m_tearingRecovery.regularCommitPending()) {
m_tearingFallbackReason = "recovered with regular page flip";
}
if (SessionLock* lock = m_server->sessionLock()) {
lock->handleOutputCommit(*this, m_output->commit_seq);
}
}
wlr_output_state_finish(&frameState);
switch (commitResult) {
case RenderedStateCommitResult::Committed:
return FormatCommitResult::Committed;
case RenderedStateCommitResult::CommitFailed:
return FormatCommitResult::Rejected;
case RenderedStateCommitResult::BuildFailed:
case RenderedStateCommitResult::MissingBuffer:
return FormatCommitResult::Retry;
}
return FormatCommitResult::Retry;
};
const FormatSequenceOps seqOps{
.stageSdr = stageSdr,
.stageHdr = stageHdr,
.test =
[&] {
// A kept live mode leaves wlroots nothing to change, so it skips the KMS test unless a buffer is sent.
if (keptLiveMode != nullptr
&& !wlr_output_configure_primary_swapchain(m_output, &state, &m_output->swapchain)) {
return false;
}
return wlr_output_test_state(m_output, &state);
},
.commit = commitStagedState,
.clearImageDescription = [&] { wlr_output_state_set_image_description(&state, nullptr); },
.stageMode = [&](wlr_output_mode* mode) { wlr_output_state_set_mode(&state, mode); },
.warnModeFallback =
[&](std::string_view requested, const wlr_output_mode& fallback) {
kLog.warn(
"output '{}': configured mode {} could not be applied, using preferred mode "
"{}x{}@{}mHz",
m_output->name, requested, fallback.width, fallback.height, fallback.refresh
);
},
.warnVrrDropped =
[&](FormatTier tier) {
switch (tier) {
case FormatTier::Hdr:
kLog.warn("output '{}': HDR is incompatible with VRR, keeping VRR disabled", m_output->name);
break;
case FormatTier::Sdr10:
kLog.warn("output '{}': 10-bit SDR is incompatible with VRR, keeping VRR disabled", m_output->name);
break;
case FormatTier::Sdr8:
kLog.warn(
"output '{}': configured state commit failed with VRR enabled, keeping VRR disabled",
m_output->name
);
break;
}
},
};
const FormatSequenceResult seq = runFormatSequence(seqParams, seqOps);
anyCommitted = seq.committed;
usedModeFallback = seq.usedModeFallback;
if (seq.usedLiveModeRetry) {
kLog.info(
"output '{}': backend rejected keeping live mode {}x{}@{}mHz, retried with a modeset", m_output->name,
keptLiveMode->width, keptLiveMode->height, keptLiveMode->refresh
);
}
if (seq.modeFallbackWarnedNow) {
m_modeFallbackWarned = true;
}
if (seq.committed) {
m_vrrDroppedTier = seq.vrrDropped ? std::optional(seq.committedTier) : std::nullopt;
if (seq.committedTier == FormatTier::Hdr) {
kLog.info(
"output '{}': selected HDR render format {}", m_output->name, tenBitFormatName(seq.committedFormat)
);
} else if (seq.committedTier == FormatTier::Sdr10) {
kLog.info(
"output '{}': selected 10-bit SDR render format {}", m_output->name, tenBitFormatName(seq.committedFormat)
);
}
}
pendingHdrFail = seq.hdrFail;
pendingSdr10Fail = seq.sdr10Fail;
hdrRejected = hdrRequested && !seq.retry && !seq.hdrFail.empty();
} else {
if (!hdrRequested && hdrWasActive) {
wlr_output_state_set_image_description(&state, nullptr);
wlr_output_state_set_render_format(&state, DRM_FORMAT_XRGB8888);
}
anyCommitted = wlr_output_commit_state(m_output, &state);
}
wlr_output_state_finish(&state);
m_hdrTransition.recordCommit(enabled, hdrRequested, anyCommitted);
if (hdrRejected) {
m_hdrAvailable = false;
}
if (!anyCommitted) {
// A failed candidate may have prepared the scene for the requested
// transfer function. Keep the renderer aligned with the live output.
updateSceneSdrWhite();
markBlurBackgroundDirty();
m_server->updateColorPreferences();
kLog.error("output '{}': failed to commit configured state", m_output->name);
return false;
}
if (stageGeometry && !usedModeFallback) {
m_modeFallbackWarned = false;
}
if (enabled && scaleStaged) {
m_appliedConfiguredScale = configuredScale.has_value();
}
if (enabled) {
// Every successful enabled-state commit above staged either an HDR bypass
// or the latest SDR gamma table.
m_gammaDirty = false;
}
const bool hdrIsActive = hdrActive();
if (hdrIsActive) {
m_hdrAvailable = true;
setHdrFallbackReason({});
} else {
if (!hdrRequested) {
setHdrFallbackReason({});
} else if (enabled) {
if (!pendingHdrFail.empty()) {
m_hdrAvailable = false;
}
setHdrFallbackReason(pendingHdrFail);
}
}
if (!enabled || bitDepthActive() || hdrIsActive || bitDepth != 10) {
setBitDepthFallbackReason({});
} else {
setBitDepthFallbackReason(pendingSdr10Fail);
}
updateSceneSdrWhite();
m_server->updateIdleInhibit();
if (enabled) {
kLog.info(
"output '{}': applied mode={}x{}@{}mHz scale={} transform={}", m_output->name, m_output->width,
m_output->height, m_output->refresh, m_output->scale, static_cast<int>(m_output->transform)
);
} else if (!desktopEnabled()) {
const OutputRule* rule = findOutputRule(config(), identity());
if (rule == nullptr && !outputCanAutoEnable(m_output)) {
kLog.info(
"output '{}': not enabled automatically because it has no preferred mode or display identity",
m_output->name
);
} else {
kLog.info("output '{}': disabled by {}", m_output->name, configuredEnabled() ? "output management" : "config");
}