| 1 | |
| 2 | """Pace a Cage virtual display by what its viewer is doing. |
| 3 | |
| 4 | Chromium and Electron render in software here, and take their frame interval |
| 5 | from the display's RandR refresh rate. Rendering, capture, encoding, transport |
| 6 | and host decoding therefore all scale with that one number. Input restores the |
| 7 | full rate within a few frames; an unattended animation runs at a lower one. |
| 8 | """ |
| 9 | import os |
| 10 | import select |
| 11 | import signal |
| 12 | import struct |
| 13 | import sys |
| 14 | import time |
| 15 | |
| 16 | ACTIVE_RATE = 60 |
| 17 | PASSIVE_RATE = 30 |
| 18 | IDLE_RATE = 20 |
| 19 | ACTIVE_HOLD = 3.0 |
| 20 | IDLE_AFTER = 180.0 |
| 21 | |
| 22 | |
| 23 | PREFIX = 'fps' |
| 24 | PROBE_KEYSYM = 0xffd5 |
| 25 | |
| 26 | |
| 27 | def target_rate(idle): |
| 28 | if idle < ACTIVE_HOLD: |
| 29 | return ACTIVE_RATE |
| 30 | if idle < IDLE_AFTER: |
| 31 | return PASSIVE_RATE |
| 32 | return IDLE_RATE |
| 33 | |
| 34 | |
| 35 | def next_change(idle): |
| 36 | """Seconds until the target rate changes without further input.""" |
| 37 | if idle < ACTIVE_HOLD: |
| 38 | return ACTIVE_HOLD - idle |
| 39 | if idle < IDLE_AFTER: |
| 40 | return IDLE_AFTER - idle |
| 41 | return None |
| 42 | |
| 43 | |
| 44 | def mode_name(rate, width, height): |
| 45 | return f'{PREFIX}{rate}-{width}x{height}' |
| 46 | |
| 47 | |
| 48 | def governed(name): |
| 49 | rate, separator, size = name[len(PREFIX):].partition('-') |
| 50 | width, by, height = size.partition('x') |
| 51 | return name.startswith(PREFIX) and bool(separator and by) and rate.isdigit() and width.isdigit() and height.isdigit() |
| 52 | |
| 53 | |
| 54 | def mode_timing(rate, width, height): |
| 55 | |
| 56 | return { |
| 57 | 'id': 0, 'width': width, 'height': height, 'dot_clock': (width + 32) * (height + 8) * rate, |
| 58 | 'h_sync_start': width + 8, 'h_sync_end': width + 16, 'h_total': width + 32, 'h_skew': 0, |
| 59 | 'v_sync_start': height + 1, 'v_sync_end': height + 2, 'v_total': height + 8, |
| 60 | 'name_length': len(mode_name(rate, width, height)), 'flags': 1 | 8, |
| 61 | } |
| 62 | |
| 63 | |
| 64 | def raw_key(data): |
| 65 | """Keycode of an XInput2 raw key event: deviceid, time, then detail.""" |
| 66 | return struct.unpack_from('=I', data, 6)[0] if isinstance(data, (bytes, bytearray)) and len(data) >= 10 else None |
| 67 | |
| 68 | |
| 69 | def choose_mode(rate, current, base, available): |
| 70 | """Mode to show `rate` at the current size, and the remembered base mode. |
| 71 | |
| 72 | The full rate returns to the mode its size owner selected, so an attended |
| 73 | display is configured exactly as it is without this governor. |
| 74 | """ |
| 75 | name, width, height = current |
| 76 | if not governed(name): |
| 77 | base = current |
| 78 | if rate == ACTIVE_RATE and base is not None and base[1:] == (width, height) and base in available: |
| 79 | return base[0], base |
| 80 | return mode_name(rate, width, height), base |
| 81 | |
| 82 | |
| 83 | class Governor: |
| 84 | def __init__(self, connection, output='VNC-0'): |
| 85 | from Xlib.ext import randr, xinput |
| 86 | self.conn = connection |
| 87 | self.root = connection.screen().root |
| 88 | self.output_name = output |
| 89 | self.xinput = xinput |
| 90 | self.expected = None |
| 91 | self.base = None |
| 92 | self.probe_codes = None |
| 93 | |
| 94 | |
| 95 | connection.set_error_handler(lambda *_: None) |
| 96 | self.root.xrandr_select_input(randr.RRScreenChangeNotifyMask) |
| 97 | self.root.xinput_select_events([(xinput.AllMasterDevices, |
| 98 | xinput.RawKeyPressMask | xinput.RawButtonPressMask | xinput.RawMotionMask)]) |
| 99 | connection.sync() |
| 100 | |
| 101 | def state(self): |
| 102 | resources = self.root.xrandr_get_screen_resources() |
| 103 | modes, position = {}, 0 |
| 104 | for mode in resources.modes: |
| 105 | modes[mode.id] = (resources.mode_names[position:position + mode.name_length], mode.width, mode.height) |
| 106 | position += mode.name_length |
| 107 | for output in resources.outputs: |
| 108 | info = self.conn.xrandr_get_output_info(output, resources.config_timestamp) |
| 109 | if info.name == self.output_name and info.crtc: |
| 110 | crtc = self.conn.xrandr_get_crtc_info(info.crtc, resources.config_timestamp) |
| 111 | if crtc.mode in modes: |
| 112 | return resources, output, info, crtc, modes |
| 113 | return None |
| 114 | |
| 115 | def ensure_mode(self, rate, width, height): |
| 116 | state = self.state() |
| 117 | if state is None: |
| 118 | return |
| 119 | _, output, info, _, modes = state |
| 120 | name = mode_name(rate, width, height) |
| 121 | mode = next((key for key, value in modes.items() if value[0] == name), None) |
| 122 | if mode is None: |
| 123 | mode = self.root.xrandr_create_mode(mode_timing(rate, width, height), name).mode |
| 124 | if mode not in info.modes: |
| 125 | self.conn.xrandr_add_output_mode(output, mode) |
| 126 | self.conn.sync() |
| 127 | |
| 128 | def apply(self, rate): |
| 129 | """Show `rate` at the current size and report 'shown' or 'failed'. |
| 130 | |
| 131 | Reports 'foreign', leaving the display alone, when another client |
| 132 | changed the mode since the previous call: a viewer attached or resized. |
| 133 | """ |
| 134 | from Xlib import error |
| 135 | created = False |
| 136 | while True: |
| 137 | |
| 138 | |
| 139 | self.conn.grab_server() |
| 140 | try: |
| 141 | state = self.state() |
| 142 | if state is None: |
| 143 | return 'failed' |
| 144 | resources, output, info, crtc, modes = state |
| 145 | current = modes[crtc.mode] |
| 146 | foreign = self.expected is not None and current != self.expected |
| 147 | wanted, self.base = choose_mode(rate, current, self.base, set(modes.values())) |
| 148 | if foreign: |
| 149 | self.expected = current |
| 150 | return 'foreign' |
| 151 | target = next((key for key, value in modes.items() if value[0] == wanted and key in info.modes), None) |
| 152 | if wanted == current[0] or target is not None: |
| 153 | if wanted != current[0]: |
| 154 | reply = self.conn.xrandr_set_crtc_config(info.crtc, resources.config_timestamp, crtc.x, crtc.y, |
| 155 | target, crtc.rotation, crtc.outputs) |
| 156 | if reply.status != 0: |
| 157 | return 'failed' |
| 158 | self.expected = (wanted,) + current[1:] |
| 159 | for mode, (name, width, height) in modes.items(): |
| 160 | |
| 161 | if governed(name) and (width, height) != current[1:]: |
| 162 | if mode in info.modes: |
| 163 | self.conn.xrandr_delete_output_mode(output, mode) |
| 164 | self.conn.xrandr_destroy_mode(mode) |
| 165 | return 'shown' |
| 166 | except error.XError: |
| 167 | return 'failed' |
| 168 | finally: |
| 169 | self.conn.ungrab_server() |
| 170 | self.conn.sync() |
| 171 | if created: |
| 172 | return 'failed' |
| 173 | try: |
| 174 | self.ensure_mode(rate, *current[1:]) |
| 175 | except error.XError: |
| 176 | return 'failed' |
| 177 | created = True |
| 178 | |
| 179 | def probe_key(self, code): |
| 180 | if self.probe_codes is None: |
| 181 | first = self.conn.display.info.min_keycode |
| 182 | count = self.conn.display.info.max_keycode - first + 1 |
| 183 | self.probe_codes = {first + offset for offset, symbols in |
| 184 | enumerate(self.conn.get_keyboard_mapping(first, count)) |
| 185 | if len(symbols) and symbols[0] == PROBE_KEYSYM} |
| 186 | return code in self.probe_codes |
| 187 | |
| 188 | def events(self): |
| 189 | """Whether the viewer acted, and whether the screen was reconfigured.""" |
| 190 | from Xlib import X |
| 191 | from Xlib.ext import ge |
| 192 | acted = changed = False |
| 193 | while self.conn.pending_events(): |
| 194 | event = self.conn.next_event() |
| 195 | if event.type == X.MappingNotify: |
| 196 | self.probe_codes = None |
| 197 | elif event.type != ge.GenericEventCode: |
| 198 | changed = True |
| 199 | elif event.evtype != self.xinput.RawKeyPress or not self.probe_key(raw_key(event.data)): |
| 200 | acted = True |
| 201 | return acted, changed |
| 202 | |
| 203 | def run(self, clock=time.monotonic): |
| 204 | last_input, shown = clock(), None |
| 205 | while True: |
| 206 | acted, changed = self.events() |
| 207 | if acted: |
| 208 | last_input = clock() |
| 209 | rate = target_rate(clock() - last_input) |
| 210 | |
| 211 | if changed or rate != shown: |
| 212 | result = self.apply(rate) |
| 213 | if result == 'foreign': |
| 214 | last_input, rate = clock(), ACTIVE_RATE |
| 215 | result = self.apply(rate) |
| 216 | shown = rate if result == 'shown' else None |
| 217 | if acted: |
| 218 | |
| 219 | time.sleep(.25) |
| 220 | continue |
| 221 | if self.conn.pending_events(): |
| 222 | continue |
| 223 | wait = next_change(clock() - last_input) if shown is not None else 5 |
| 224 | select.select([self.conn.fileno()], [], [], None if wait is None else wait + .01) |
| 225 | |
| 226 | |
| 227 | def main(): |
| 228 | try: |
| 229 | from Xlib import display |
| 230 | except ImportError: |
| 231 | |
| 232 | print('display governor: python3-xlib is not installed', file=sys.stderr) |
| 233 | return 0 |
| 234 | for attempt in range(40): |
| 235 | try: |
| 236 | connection = display.Display() |
| 237 | break |
| 238 | except Exception: |
| 239 | |
| 240 | if attempt == 39: |
| 241 | raise |
| 242 | time.sleep(.25) |
| 243 | if not connection.has_extension('RANDR') or not connection.has_extension('XInputExtension'): |
| 244 | |
| 245 | print('display governor: RandR or XInput2 unavailable', file=sys.stderr) |
| 246 | return 0 |
| 247 | connection.xinput_query_version() |
| 248 | governor = Governor(connection, os.environ.get('CAGE_DISPLAY_OUTPUT', 'VNC-0')) |
| 249 | signal.signal(signal.SIGTERM, lambda *_: sys.exit(0)) |
| 250 | try: |
| 251 | governor.run() |
| 252 | finally: |
| 253 | |
| 254 | try: |
| 255 | if governor.apply(ACTIVE_RATE) == 'foreign': |
| 256 | governor.apply(ACTIVE_RATE) |
| 257 | except Exception: |
| 258 | pass |
| 259 | return 0 |
| 260 | |
| 261 | |
| 262 | if __name__ == '__main__': |
| 263 | sys.exit(main()) |