mirror of
https://github.com/LGUG2Z/komorebi.git
synced 2026-11-28 11:22:47 +01:00
refactor(repo): move the KDE and macOS nix files under nix/ (pure move)
komorebi-for-kde/nix/ -> nix/linux/ komorebi-for-mac/nix/ -> nix/macos/ The nix expressions of the platforms (modules, option files, VM test suites, kwin effects, the darwin module) sit next to the existing nix/workspace-src.nix. Renames only (252 files); the flakes that import them are replaced by one root flake later in this stack, so nix does not evaluate at this revision.
This commit is contained in:
1 parent
d781028a2a
commit
f01853ceca
252 files changed
No files matched your search
@@ -0,0 +1,107 @@
|
||||
# KRDP, Plasma's RDP server, in the Plasma session of every user who logs in. The session guest
|
||||
# of plasma-vm.nix enables it, and so does the VM suite `rdp`, which checks that a client can log
|
||||
# in and get a picture of the desktop (docs/dev/PLATFORM.md says what it does not check).
|
||||
#
|
||||
# The password is not in the repository: the unit starts once the user has written one to
|
||||
# ~/.config/komorebi-vm/rdp-password, and a client logs in with the user's name and that password.
|
||||
# A guest whose password comes from outside, as the demo guest's does (run-kde.nix), names a file
|
||||
# of the guest in `passwordFile`, which the unit reads in place of that one when it is there.
|
||||
{
|
||||
config,
|
||||
lib,
|
||||
pkgs,
|
||||
...
|
||||
}:
|
||||
let
|
||||
cfg = config.komorebi.krdp;
|
||||
|
||||
# KRDP asks for the H.264 Constrained Baseline profile and nothing else. A guest whose VA-API
|
||||
# drives the host's encoder (virgl, with the QEMU of run-kde.nix) lists Main and High and no
|
||||
# Constrained Baseline, so ffmpeg's h264_vaapi finds no profile it can use and KRDP encodes on
|
||||
# the CPUs. Main is in RDP's H.264 mode as well, and the software encoder takes it too.
|
||||
krdp = pkgs.kdePackages.krdp.overrideAttrs (old: {
|
||||
postPatch = (old.postPatch or "") + ''
|
||||
substituteInPlace src/VideoStreamSurface.cpp --replace-fail H264Baseline H264Main
|
||||
'';
|
||||
});
|
||||
|
||||
startKrdp = pkgs.writeShellScript "krdp-start" ''
|
||||
set -eu
|
||||
dir=$HOME/.config/komorebi-vm
|
||||
password_file=$dir/rdp-password
|
||||
${lib.optionalString (cfg.passwordFile != null) ''
|
||||
if [ -r ${lib.escapeShellArg cfg.passwordFile} ]; then
|
||||
password_file=${lib.escapeShellArg cfg.passwordFile}
|
||||
fi
|
||||
''}
|
||||
mkdir -p "$dir"
|
||||
# krdpserver refuses to run without a TLS certificate and key (its --help promises a temporary
|
||||
# one, but it only checks that the files exist), so make a throwaway self-signed pair
|
||||
if [ ! -f "$dir/rdp.crt" ] || [ ! -f "$dir/rdp.key" ]; then
|
||||
${pkgs.openssl}/bin/openssl req -x509 -newkey rsa:2048 -nodes -days 3650 -subj /CN=komorebi-vm \
|
||||
-addext subjectAltName=DNS:localhost,IP:127.0.0.1 -keyout "$dir/rdp.key" -out "$dir/rdp.crt"
|
||||
chmod 600 "$dir/rdp.key"
|
||||
fi
|
||||
# --plasma asks KWin for the screen and for input directly, with no portal prompt to click
|
||||
exec ${krdp}/bin/krdpserver --plasma --address 0.0.0.0 --port 3389 \
|
||||
--certificate "$dir/rdp.crt" --certificate-key "$dir/rdp.key" \
|
||||
--username "$USER" --password "$(cat "$password_file")"
|
||||
'';
|
||||
in
|
||||
{
|
||||
options.komorebi.krdp = {
|
||||
enable = lib.mkEnableOption "KRDP, an RDP server, in every Plasma session";
|
||||
|
||||
passwordFile = lib.mkOption {
|
||||
type = lib.types.nullOr lib.types.str;
|
||||
default = null;
|
||||
example = "/run/run-kde-guest/rdp-password";
|
||||
description = ''
|
||||
The path, in the guest, of a file with the password a client logs in with. It is a path in
|
||||
the running guest and not a file of the Nix store, so that no password is part of the
|
||||
system. The unit reads it in place of `~/.config/komorebi-vm/rdp-password` when it exists,
|
||||
and starts when either exists.
|
||||
'';
|
||||
};
|
||||
};
|
||||
|
||||
config = lib.mkIf cfg.enable {
|
||||
environment.systemPackages = [
|
||||
krdp
|
||||
# A client, to try the server from inside the guest. FreeRDP decodes H.264 with OpenH264
|
||||
# when it is built with it, and OpenH264 shows nothing of the video KRDP sends; without it,
|
||||
# FreeRDP decodes with FFmpeg (the VM suite `rdp`, docs/dev/PLATFORM.md).
|
||||
(pkgs.freerdp.override { openh264 = null; })
|
||||
];
|
||||
|
||||
# krdp streams the screen through pipewire
|
||||
services.pipewire = {
|
||||
enable = true;
|
||||
wireplumber.enable = true;
|
||||
};
|
||||
security.rtkit.enable = true;
|
||||
|
||||
networking.firewall.allowedTCPPorts = [ 3389 ];
|
||||
|
||||
systemd.user.services.krdp = {
|
||||
description = "RDP into this Plasma session";
|
||||
wantedBy = [ "plasma-workspace.target" ];
|
||||
after = [ "plasma-core.target" ];
|
||||
# with no password the unit is skipped, not failed: `systemctl --user start krdp` once the
|
||||
# file is there
|
||||
unitConfig.ConditionPathExists =
|
||||
if cfg.passwordFile == null then
|
||||
"%h/.config/komorebi-vm/rdp-password"
|
||||
else
|
||||
[
|
||||
"|%h/.config/komorebi-vm/rdp-password"
|
||||
"|${cfg.passwordFile}"
|
||||
];
|
||||
serviceConfig = {
|
||||
ExecStart = startKrdp;
|
||||
Restart = "on-failure";
|
||||
RestartSec = 3;
|
||||
};
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
mesa: let go of the fence a surface is flushed or processed again over
|
||||
|
||||
vlVaSurfaceFlush() (the upload of an image, the clear of a new surface) and the end of a
|
||||
video-processing pass (vl_compositor_proc: the scale_vaapi of FFmpeg, the blit of
|
||||
vaPutImage) flush into surf->pipe_fence, which gets the new fence of the flush and loses
|
||||
the old one. The only places that let go of it are vaSyncSurface() and the destruction of
|
||||
the surface, so a surface that is flushed again before a sync, which one of a pool is,
|
||||
leaves the fence it had behind.
|
||||
|
||||
With virgl a fence owns a file descriptor: the sync_file that the kernel returns for the
|
||||
out-fence of the execbuffer (VIRTGPU_EXECBUF_FENCE_FD_OUT), closed when the fence is freed.
|
||||
The guest's KRDP kept one open for every frame it captured until it had 1024 of them,
|
||||
after which every ioctl failed with EMFILE ("got error from kernel - expect bad rendering
|
||||
24") and the picture froze.
|
||||
|
||||
Release the fence a flush is about to replace. The newer one covers it: both are fences of
|
||||
the same context.
|
||||
|
||||
--- a/src/gallium/frontends/va/surface.c 2026-10-28 17:58:18.769410786 -0700
|
||||
+++ b/src/gallium/frontends/va/surface.c 2026-10-28 17:58:30.469583700 -0700
|
||||
@@ -812,6 +812,14 @@
|
||||
void
|
||||
vlVaSurfaceFlush(vlVaDriver *drv, vlVaSurface *surf)
|
||||
{
|
||||
+ /* A flush makes a new fence, which replaces the one in the surface: the one of the last flush
|
||||
+ * is what vaSyncSurface waits for, and it is only let go of there and when the surface is
|
||||
+ * destroyed. Replaced without a release, its fence is never freed, and with a driver whose
|
||||
+ * fences hold a file descriptor (virgl: a sync_file) a surface that is flushed again and
|
||||
+ * again, as the ones of a pool are, leaves one open a time until there are no more. */
|
||||
+ if (surf->pipe_fence)
|
||||
+ drv->pipe->screen->fence_reference(drv->pipe->screen, &surf->pipe_fence, NULL);
|
||||
+
|
||||
drv->pipe->flush(drv->pipe, &surf->pipe_fence,
|
||||
drv->has_external_handles ? 0 : PIPE_FLUSH_ASYNC);
|
||||
}
|
||||
--- a/src/gallium/auxiliary/vl/vl_compositor_proc.c 2026-10-28 17:58:18.771011962 -0700
|
||||
+++ b/src/gallium/auxiliary/vl/vl_compositor_proc.c 2026-10-28 17:58:30.814280800 -0700
|
||||
@@ -185,8 +185,17 @@
|
||||
struct pipe_picture_desc *picture)
|
||||
{
|
||||
struct vl_compositor_proc *proc = (struct vl_compositor_proc *)codec;
|
||||
+ struct pipe_context *context = proc->b.context;
|
||||
|
||||
- proc->b.context->flush(proc->b.context, picture->out_pipe_fence, picture->flush_flags);
|
||||
+ /* out_pipe_fence is the pipe_fence of the target surface (vlVaEndPicture, vlVaPutImage), and
|
||||
+ * the flush makes a new fence for it. The last one is what a sync waits for, so the one it
|
||||
+ * replaces is let go of here: left, it is never freed, and with virgl its fence is a
|
||||
+ * sync_file, one more of them open for every frame of a pooled surface that is processed
|
||||
+ * again before it is synced. */
|
||||
+ if (picture->out_pipe_fence && *picture->out_pipe_fence)
|
||||
+ context->screen->fence_reference(context->screen, picture->out_pipe_fence, NULL);
|
||||
+
|
||||
+ context->flush(context, picture->out_pipe_fence, picture->flush_flags);
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
vl/compositor: give the graphics RGB to YUV conversion its matrix
|
||||
|
||||
compositor_proc_process_frame() fills a matrix for each conversion: for RGB to RGB and
|
||||
YUV to RGB it fills both yuv2rgb and csc_matrix, for RGB to YUV only rgb2yuv. The compute
|
||||
compositor reads rgb2yuv, but the graphics compositor uploads csc_matrix (set_csc_matrix()
|
||||
in vl_compositor_gfx.c) to the constants of its fragment shaders, and for RGB to YUV
|
||||
csc_matrix still held what vl_compositor_init_state() put in it, the YUV to RGB matrix of
|
||||
BT.709 for NV12. Only radeonsi sets prefer_compute_for_multimedia, so every other driver
|
||||
takes the graphics path: on virgl scale_vaapi=format=nv12 of an RGB surface (what
|
||||
KPipeWire and KRDP do with every frame of a screen) gave Y = 1.164 R + 1.793 B - 0.973,
|
||||
that is 0 for a gray of 0 to 118 and a wrong picture above.
|
||||
|
||||
Fill csc_matrix with the RGB to YUV matrix too, as the other conversions do.
|
||||
|
||||
diff --git a/src/gallium/auxiliary/vl/vl_compositor_proc.c b/src/gallium/auxiliary/vl/vl_compositor_proc.c
|
||||
index 7de461e..d794038 100644
|
||||
--- a/src/gallium/auxiliary/vl/vl_compositor_proc.c
|
||||
+++ b/src/gallium/auxiliary/vl/vl_compositor_proc.c
|
||||
@@ -93,6 +93,11 @@ compositor_proc_process_frame(struct pipe_video_codec *codec,
|
||||
/* RGB to YUV */
|
||||
vl_csc_get_rgbyuv_matrix(param->out_matrix_coefficients, src->buffer_format, dst->buffer_format,
|
||||
param->in_color_range, param->out_color_range, &proc->cstate.rgb2yuv);
|
||||
+ /* The compute compositor reads rgb2yuv, but the graphics one (the only one that drivers
|
||||
+ * without prefer_compute_for_multimedia, like virgl, ever use) uploads csc_matrix to its
|
||||
+ * shader constants, and it still held the YUV to RGB default of vl_compositor_init_state():
|
||||
+ * the RGB to YUV fragment shaders then made nonsense of the picture. */
|
||||
+ memcpy(&proc->cstate.csc_matrix, &proc->cstate.rgb2yuv, sizeof(vl_csc_matrix));
|
||||
}
|
||||
|
||||
vl_csc_get_primaries_matrix(param->in_color_primaries, param->out_color_primaries,
|
||||
@@ -0,0 +1,57 @@
|
||||
{ lib, pkgs, ... }:
|
||||
|
||||
# The Plasma session guest as a plain disk image, for a hypervisor with a GPU: UTM on Apple Silicon
|
||||
# runs QEMU with virtio-gpu-gl (virgl over ANGLE/CoreGL), which the QEMU in nixpkgs, and so the
|
||||
# 9p-booted `plasma-vm-session`, cannot: that one composites with llvmpipe on the CPU.
|
||||
#
|
||||
# This is the same session as plasma-vm.nix (komorebi from the module, KRDP), booted from its own
|
||||
# disk by UEFI instead of from a kernel and the host's /nix/store. docs/dev/utm.md says how to
|
||||
# install it onto a disk image and point UTM at it.
|
||||
{
|
||||
imports = [ ./plasma-vm.nix ];
|
||||
|
||||
komorebi.plasmaVm.session = true;
|
||||
|
||||
networking.hostName = lib.mkOverride 40 "plasma-utm";
|
||||
|
||||
boot.loader = {
|
||||
grub = {
|
||||
enable = true;
|
||||
efiSupport = true;
|
||||
efiInstallAsRemovable = true;
|
||||
device = "nodev";
|
||||
};
|
||||
efi.canTouchEfiVariables = false;
|
||||
timeout = 1;
|
||||
};
|
||||
|
||||
boot.initrd.availableKernelModules = [
|
||||
"virtio_pci"
|
||||
"virtio_blk"
|
||||
"virtio_net"
|
||||
"virtio_scsi"
|
||||
"xhci_pci"
|
||||
"usbhid"
|
||||
];
|
||||
# kms from the start, so that sddm has a screen to start on
|
||||
boot.initrd.kernelModules = [ "virtio_gpu" ];
|
||||
boot.kernelParams = [ "console=tty0" ];
|
||||
boot.growPartition = true;
|
||||
|
||||
fileSystems."/" = {
|
||||
device = "/dev/disk/by-label/nixos";
|
||||
fsType = "ext4";
|
||||
autoResize = true;
|
||||
};
|
||||
fileSystems."/boot" = {
|
||||
device = "/dev/disk/by-label/ESP";
|
||||
fsType = "vfat";
|
||||
};
|
||||
|
||||
# the window follows the guest's resolution, and the clipboard is shared
|
||||
services.spice-vdagentd.enable = true;
|
||||
services.qemuGuest.enable = true;
|
||||
|
||||
# to check that the session really is on the GPU: `eglinfo | grep -i renderer` says virgl
|
||||
environment.systemPackages = [ pkgs.mesa-demos ];
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
{
|
||||
config,
|
||||
lib,
|
||||
pkgs,
|
||||
hostPkgs,
|
||||
...
|
||||
}:
|
||||
|
||||
# A NixOS Plasma 6 guest to develop and test against a real KWin, with komorebi installed by the
|
||||
# flake's module, `services.komorebi`, from the flake's packages. The flake builds it for an Apple
|
||||
# silicon Mac, which runs it under QEMU with HVF, and for a Linux machine, which runs it under QEMU
|
||||
# with KVM; docs/dev/utm.md says how to build and run it. The system of the guest and the packages
|
||||
# of the machine that runs QEMU (`hostPkgs`) come from the flake, so that one file serves them all.
|
||||
#
|
||||
# The guest mounts the repository at /repo, and keeps its disk in the directory it is started
|
||||
# from, which is best .vm (gitignored):
|
||||
#
|
||||
# nix build .#nixosConfigurations.plasma-vm.config.system.build.vm -o .vm/result-plasma-vm
|
||||
# cd .vm && KOMOREBI_REPO=$PWD/.. ./result-plasma-vm/bin/run-plasma-vm-vm
|
||||
#
|
||||
# The console, in the terminal that runs the guest, is logged in as the user `komorebi`. ssh is
|
||||
# forwarded to localhost:2222 (2223 for the session), for the keys in ~/.ssh/authorized_keys of
|
||||
# that user, which the guest's disk keeps.
|
||||
#
|
||||
# The session variant is the one to live in: Plasma logs in by itself, the module's unit runs
|
||||
# komorebi in it, and it can be reached over RDP (krdp.nix).
|
||||
let
|
||||
cfg = config.komorebi.plasmaVm;
|
||||
|
||||
# The guest's one display, a virtio-gpu, so that KWin has a DRM device to draw on. The machine of
|
||||
# an aarch64 guest has no display of its own. The machine of an x86_64 guest has a VGA, which QEMU
|
||||
# adds unless it is told not to, and KWin would draw on it as well as on the virtio-gpu: a second
|
||||
# head. An x86_64 guest gets `virtio-vga`, a virtio-gpu that is also the VGA, in its place.
|
||||
gpu =
|
||||
args:
|
||||
if pkgs.stdenv.hostPlatform.isx86_64 then
|
||||
[
|
||||
"-vga none"
|
||||
"-device virtio-vga${args}"
|
||||
]
|
||||
else
|
||||
[ "-device virtio-gpu-pci${args}" ];
|
||||
in
|
||||
{
|
||||
imports = [ ./krdp.nix ];
|
||||
|
||||
options.komorebi.plasmaVm = {
|
||||
session = lib.mkEnableOption ''
|
||||
a full autologin Plasma Wayland session (sddm + plasmashell), in addition to the headless
|
||||
`kwin_wayland --virtual` workflow that is always available from the console and over ssh
|
||||
'';
|
||||
|
||||
display = lib.mkOption {
|
||||
type = lib.types.bool;
|
||||
default = true;
|
||||
description = ''
|
||||
Whether the runner gives the guest its display device, a virtio-gpu. A guest that sets this
|
||||
to false is started with a display device of its own choosing, which can then differ from
|
||||
one start to the next: `run-kde` starts the demo guest (run-kde.nix) with a software
|
||||
`virtio-vga` or with a `virtio-vga-gl` that renders on the host's GPU, from one closure and
|
||||
one disk.
|
||||
'';
|
||||
};
|
||||
};
|
||||
|
||||
config = lib.mkMerge [
|
||||
{
|
||||
system.stateVersion = "26.05";
|
||||
networking.hostName = "plasma-vm";
|
||||
|
||||
services.desktopManager.plasma6.enable = true;
|
||||
programs.dconf.enable = true;
|
||||
# mesa (llvmpipe over the virtio-gpu render node) so kwin can composite with GL
|
||||
hardware.graphics.enable = true;
|
||||
fonts.enableDefaultPackages = true;
|
||||
|
||||
# komorebi and komorebic, from the flake's packages; the unit starts with a Plasma session
|
||||
services.komorebi.enable = true;
|
||||
|
||||
services.openssh = {
|
||||
enable = true;
|
||||
settings = {
|
||||
PasswordAuthentication = false;
|
||||
PermitRootLogin = "no";
|
||||
};
|
||||
};
|
||||
|
||||
# the way in before any key is in ~/.ssh/authorized_keys: there is no password anywhere
|
||||
services.getty.autologinUser = "komorebi";
|
||||
|
||||
users.users.komorebi = {
|
||||
isNormalUser = true;
|
||||
uid = 1000;
|
||||
extraGroups = [
|
||||
"wheel"
|
||||
"video"
|
||||
"render"
|
||||
];
|
||||
# keep a user manager (and XDG_RUNTIME_DIR) alive across ssh sessions
|
||||
linger = true;
|
||||
};
|
||||
security.sudo.wheelNeedsPassword = false;
|
||||
|
||||
nix.settings.experimental-features = [
|
||||
"nix-command"
|
||||
"flakes"
|
||||
];
|
||||
|
||||
environment.systemPackages = with pkgs; [
|
||||
# clients to tile: Qt/KDE, GTK3/4 (CSD), Electron-ish via firefox, plain wayland, XWayland
|
||||
kdePackages.konsole
|
||||
kdePackages.dolphin
|
||||
kdePackages.kate
|
||||
kdePackages.spectacle
|
||||
firefox
|
||||
gnome-text-editor
|
||||
gnome-calculator
|
||||
foot
|
||||
xterm
|
||||
|
||||
# poking at KWin
|
||||
kdePackages.qttools # qdbus6
|
||||
dbus
|
||||
jq
|
||||
kdotool
|
||||
strace
|
||||
|
||||
# installing plasma-utm onto a disk image (docs/dev/utm.md)
|
||||
nixos-install-tools
|
||||
dosfstools
|
||||
parted
|
||||
e2fsprogs
|
||||
|
||||
# building komorebi from /repo in the guest
|
||||
rustc
|
||||
cargo
|
||||
gcc
|
||||
pkg-config
|
||||
git
|
||||
rsync
|
||||
htop
|
||||
];
|
||||
|
||||
environment.sessionVariables = {
|
||||
# kwin refuses to load animating effects (including the stock scripted ones) under software
|
||||
# rendering; llvmpipe is all this vm has
|
||||
KWIN_EFFECTS_FORCE_ANIMATIONS = "1";
|
||||
# always build in guest-local storage; /repo is a 9p mount and is slow for target dirs
|
||||
CARGO_TARGET_DIR = "/home/komorebi/target";
|
||||
};
|
||||
|
||||
virtualisation.vmVariant = {
|
||||
virtualisation = {
|
||||
host.pkgs = hostPkgs;
|
||||
qemu.forceAccel = true;
|
||||
cores = 6;
|
||||
memorySize = 8192;
|
||||
diskSize = 20 * 1024;
|
||||
graphics = false;
|
||||
# no display, but a gpu so there is a drm render node
|
||||
qemu.options = lib.mkIf (cfg.display && !cfg.session) (gpu "");
|
||||
forwardPorts = [
|
||||
{
|
||||
from = "host";
|
||||
host.address = "127.0.0.1";
|
||||
host.port = if cfg.session then 2223 else 2222;
|
||||
guest.port = 22;
|
||||
}
|
||||
];
|
||||
sharedDirectories.repo = {
|
||||
# the runner says so when it is not set
|
||||
source = "\${KOMOREBI_REPO:?set KOMOREBI_REPO to the root of the repository}";
|
||||
target = "/repo";
|
||||
writable = true;
|
||||
};
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
(lib.mkIf cfg.session {
|
||||
# a separate disk image (named after the host) and ssh port so both vms can run at once
|
||||
networking.hostName = lib.mkForce "plasma-vm-session";
|
||||
services.displayManager = {
|
||||
sddm = {
|
||||
enable = true;
|
||||
wayland.enable = true;
|
||||
};
|
||||
autoLogin = {
|
||||
enable = true;
|
||||
user = "komorebi";
|
||||
};
|
||||
defaultSession = "plasma";
|
||||
};
|
||||
# kwin drives virtio-gpu through drm on the primary node; that is the only place mesa's software
|
||||
# rasterizer can allocate buffers (see docs/dev/PLATFORM.md: the headless --virtual backend
|
||||
# cannot)
|
||||
virtualisation.vmVariant.virtualisation.qemu.options = lib.mkIf cfg.display (
|
||||
gpu ",xres=1920,yres=1080"
|
||||
);
|
||||
# an idle lock screen or dimmed display changes how kwin animates and what screenshots show
|
||||
environment.etc."xdg/kscreenlockerrc".text = ''
|
||||
[Daemon]
|
||||
Autolock=false
|
||||
LockOnResume=false
|
||||
'';
|
||||
# and so does a display that has gone to sleep: with the output off, KWin sends no frame
|
||||
# callbacks, so clients stop answering resizes and every window stays where it was while komorebi
|
||||
# asks for another place (found on the UTM guest after it sat idle: black screenshots, nothing tiled)
|
||||
environment.etc."xdg/powerdevilrc".text = ''
|
||||
[AC][Display]
|
||||
DimDisplayWhenIdle=false
|
||||
TurnOffDisplayWhenIdle=false
|
||||
|
||||
[AC][SuspendAndShutdown]
|
||||
AutoSuspendAction=0
|
||||
'';
|
||||
|
||||
komorebi.krdp.enable = true;
|
||||
|
||||
# only the host's loopback reaches it
|
||||
virtualisation.vmVariant.virtualisation.forwardPorts = [
|
||||
{
|
||||
from = "host";
|
||||
host.address = "127.0.0.1";
|
||||
host.port = 3389;
|
||||
guest.port = 3389;
|
||||
}
|
||||
];
|
||||
})
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
virtio-gpu: let virglrenderer use video encode and decode
|
||||
|
||||
virglrenderer can pass a guest's VA-API video encode and decode to the host's
|
||||
(virtio_gpu_drv_video in Mesa), but only when asked: with
|
||||
VIRGL_RENDERER_USE_VIDEO, and with a get_drm_fd callback to say which DRM node to
|
||||
open the host's video device on. QEMU passes neither, so a guest's vainfo lists
|
||||
VideoProc and no encoder. VIRGL_RENDERER_USE_VIDEO is only defined with
|
||||
VIRGL_RENDERER_UNSTABLE_APIS, which the build has to set.
|
||||
|
||||
--- a/hw/display/virtio-gpu-virgl.c 2026-10-28 15:30:25.853615969 -0700
|
||||
+++ b/hw/display/virtio-gpu-virgl.c 2026-10-28 15:30:25.853715164 -0700
|
||||
@@ -14,6 +14,7 @@
|
||||
#include "qemu/osdep.h"
|
||||
#include "qemu/error-report.h"
|
||||
#include "qemu/iov.h"
|
||||
+#include "qemu/drm.h"
|
||||
#include "trace.h"
|
||||
#include "hw/virtio/virtio.h"
|
||||
#include "hw/virtio/virtio-gpu.h"
|
||||
@@ -1345,6 +1346,18 @@
|
||||
return qemu_console_gl_ctx_make_current(g->parent_obj.scanout[scanout_idx].con, qctx);
|
||||
}
|
||||
|
||||
+#ifdef VIRGL_RENDERER_USE_VIDEO
|
||||
+/*
|
||||
+ * virglrenderer opens the host's video encoder and decoder (VA-API) on a DRM
|
||||
+ * node of its caller's choosing, and disables video when it has none to ask
|
||||
+ * for. It owns the fd it gets and closes it.
|
||||
+ */
|
||||
+static int virgl_get_drm_fd(void *opaque)
|
||||
+{
|
||||
+ return qemu_drm_rendernode_open(NULL);
|
||||
+}
|
||||
+#endif
|
||||
+
|
||||
static struct virgl_renderer_callbacks virtio_gpu_3d_cbs = {
|
||||
#if VIRGL_VERSION_MAJOR >= 1
|
||||
.version = 3,
|
||||
@@ -1453,6 +1466,10 @@
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
+#ifdef VIRGL_RENDERER_USE_VIDEO
|
||||
+ virtio_gpu_3d_cbs.get_drm_fd = virgl_get_drm_fd;
|
||||
+ flags |= VIRGL_RENDERER_USE_VIDEO;
|
||||
+#endif
|
||||
#ifdef VIRGL_RENDERER_D3D11_SHARE_TEXTURE
|
||||
if (qemu_egl_angle_d3d) {
|
||||
flags |= VIRGL_RENDERER_D3D11_SHARE_TEXTURE;
|
||||
@@ -0,0 +1,441 @@
|
||||
# The demo guest of `run-kde`: a Plasma session in which komorebi tiles a few windows that open by
|
||||
# themselves, with a cheat sheet to start from. It is a module to put on the session guest
|
||||
# (plasma-vm.nix with `session` and not `display`: the flake's `run-kde-x86_64` and
|
||||
# `run-kde-aarch64`), and the VM suite `run-kde` puts it on the session node, so that what the
|
||||
# command starts is what CI boots.
|
||||
#
|
||||
# The closure is the same for everyone: no password, no key and no configuration of a person is in
|
||||
# it. The host shares a directory, which the guest mounts at /run/run-kde, with
|
||||
#
|
||||
# rdp-password the password a client logs in to RDP with
|
||||
# ssh_key.pub the public key that may log in over ssh
|
||||
#
|
||||
# and the guest takes them at boot (`run-kde-credentials`). What a person's own run needs at start
|
||||
# up, the memory, the ports, the display device and the repository, comes from the environment of
|
||||
# the runner, which `run-kde` sets (docs/dev/utm.md, docs/trying-it.md). The guest shows a window
|
||||
# through QEMU or is reached over RDP, and the terminal of whoever starts it is its console.
|
||||
{
|
||||
config,
|
||||
lib,
|
||||
pkgs,
|
||||
...
|
||||
}:
|
||||
let
|
||||
# where the host's directory is mounted, and where the guest keeps what it takes from it
|
||||
shared = "/run/run-kde";
|
||||
taken = "/run/run-kde-guest";
|
||||
|
||||
user = "komorebi";
|
||||
|
||||
cheatSheet = pkgs.writeText "run-kde-cheat-sheet.txt" ''
|
||||
komorebi for KDE tiles the windows of this Plasma session.
|
||||
|
||||
The windows that opened by themselves (two terminals, Kate and Dolphin) share
|
||||
the screen. Open another one and it takes a tile of its own; close one and the
|
||||
others grow. This window is not tiled: komorebi leaves it alone. Press q to
|
||||
close it, and run `run-kde-cheat-sheet` in a terminal to open it again.
|
||||
|
||||
Start with these. Alt is either Alt key.
|
||||
|
||||
alt + h, j, k, l focus the window to the left, below, above, right
|
||||
alt + shift + h, j, k, l move the window that way
|
||||
alt + shift + return promote the window to the biggest tile
|
||||
alt + t take the window out of the tiles and back in
|
||||
alt + shift + f toggle monocle: the window fills the screen
|
||||
alt + 1 ... 9 show workspace 1 ... 9, each with its own layout
|
||||
alt + shift + 1 ... 9 move the window to that workspace
|
||||
alt + x, alt + y flip the layout horizontally, vertically
|
||||
|
||||
Or type the same in a terminal: `komorebic` is the program that every key
|
||||
runs.
|
||||
|
||||
komorebic state everything komorebi knows, as JSON
|
||||
komorebic change-layout columns bsp, rows, grid, scrolling, ...
|
||||
komorebic toggle-monocle
|
||||
komorebic retile put every window back in its tile
|
||||
komorebic border off borders are drawn by a KWin effect
|
||||
komorebic --help
|
||||
|
||||
komorebic reads its configuration from ~/.config/komorebi unless it is told
|
||||
where, and this machine starts komorebi with a file of its own, so tell it:
|
||||
|
||||
KOMOREBI_CONFIG_HOME=/etc/run-kde/config-home komorebic check
|
||||
|
||||
The key bindings komorebi reads are the whole of the file below, written in
|
||||
skhd's format. The repository is mounted at /repo: edit komorebi there and
|
||||
build it in this machine with `cargo`.
|
||||
|
||||
${builtins.readFile ../../docs/skhdrc.sample}
|
||||
'';
|
||||
|
||||
# the file the module starts the daemon with, which is the `--config` of its command line, and
|
||||
# the directory `komorebic check` reads to see what the daemon runs: it looks in the config
|
||||
# home, not at the daemon's command line
|
||||
configHome =
|
||||
let
|
||||
words = lib.splitString " " config.services.komorebi.execStart;
|
||||
at = lib.lists.findFirstIndex (word: word == "--config") null words;
|
||||
in
|
||||
pkgs.linkFarm "run-kde-config-home" [
|
||||
{
|
||||
name = "komorebi.json";
|
||||
path = builtins.elemAt words (at + 1);
|
||||
}
|
||||
{
|
||||
name = "skhdrc";
|
||||
path = ../../docs/skhdrc.sample;
|
||||
}
|
||||
];
|
||||
|
||||
# What the window shows: the graphics line, which the guest looks up when it has started, the
|
||||
# text above, and what `komorebic check` finds now.
|
||||
cheatSheetCommand = pkgs.writeShellApplication {
|
||||
name = "run-kde-cheat-sheet";
|
||||
runtimeInputs = [
|
||||
pkgs.coreutils
|
||||
pkgs.less
|
||||
config.services.komorebi.package
|
||||
];
|
||||
text = ''
|
||||
text=$(mktemp)
|
||||
{
|
||||
printf 'Graphics: %s\n\n' "$(cat "''${XDG_RUNTIME_DIR:-/tmp}/run-kde-renderer" 2>/dev/null || echo "not known yet")"
|
||||
cat ${cheatSheet}
|
||||
printf '\nkomorebic check\n\n'
|
||||
NO_COLOR=1 KOMOREBI_CONFIG_HOME=${configHome} komorebic check 2>&1 || true
|
||||
} > "$text"
|
||||
exec less -R "$text"
|
||||
'';
|
||||
};
|
||||
|
||||
# The windows of the demo, opened once the shell has its panel: a window that is tiled before
|
||||
# komorebi knows what room the panel takes is tiled under it, and nothing tiles it again.
|
||||
demo = pkgs.writeShellApplication {
|
||||
name = "run-kde-demo";
|
||||
runtimeInputs = [
|
||||
pkgs.coreutils
|
||||
pkgs.jq
|
||||
config.services.komorebi.package
|
||||
];
|
||||
text = ''
|
||||
panel=0
|
||||
for _ in $(seq 1 120); do
|
||||
if komorebic state 2>/dev/null |
|
||||
jq -e '.monitors.elements[0] | .work_area_size != .size' > /dev/null 2>&1; then
|
||||
panel=1
|
||||
break
|
||||
fi
|
||||
sleep 1
|
||||
done
|
||||
[ "$panel" = 1 ] || echo "komorebi does not know the panel's room: the windows may be tiled under it"
|
||||
|
||||
tiled() {
|
||||
local n
|
||||
n=$(komorebic state 2>/dev/null |
|
||||
jq '[.monitors.elements[].workspaces.elements[] | .containers.elements[].windows.elements[]] | length' 2> /dev/null || true)
|
||||
echo "''${n:-0}"
|
||||
}
|
||||
|
||||
# starts a program in a scope of its own, which outlives this script, and waits until komorebi
|
||||
# has a tile for it
|
||||
open() {
|
||||
local before
|
||||
before=$(tiled)
|
||||
systemd-run --user --scope --quiet -- "$@" &
|
||||
for _ in $(seq 1 60); do
|
||||
[ "$(tiled)" -gt "$before" ] && return 0
|
||||
sleep 1
|
||||
done
|
||||
echo "no tile for $1 after a minute"
|
||||
}
|
||||
|
||||
dir=$HOME
|
||||
[ -d /repo ] && dir=/repo
|
||||
|
||||
open konsole --workdir "$dir"
|
||||
open konsole
|
||||
open kate
|
||||
open dolphin "$dir"
|
||||
|
||||
# the cheat sheet says what KWin draws with, which the guest looks up once KWin has started
|
||||
for _ in $(seq 1 60); do
|
||||
[ -s "$XDG_RUNTIME_DIR/run-kde-renderer" ] && break
|
||||
sleep 1
|
||||
done
|
||||
|
||||
systemd-run --user --scope --quiet -- foot --app-id komorebi-cheat-sheet \
|
||||
--title "komorebi cheat sheet" --window-size-chars 100x34 -o main.font=monospace:size=10 \
|
||||
run-kde-cheat-sheet &
|
||||
sleep 1
|
||||
'';
|
||||
};
|
||||
|
||||
# What KWin draws with, which is what the cheat sheet and the console say: "GPU" when the host's
|
||||
# GPU renders for it (virgl) and "software" when the guest's CPUs do (llvmpipe).
|
||||
report = pkgs.writeShellApplication {
|
||||
name = "run-kde-report";
|
||||
runtimeInputs = [
|
||||
pkgs.coreutils
|
||||
pkgs.gnused
|
||||
pkgs.kdePackages.qttools
|
||||
];
|
||||
text = ''
|
||||
export XDG_RUNTIME_DIR=/run/user/${toString config.users.users.${user}.uid}
|
||||
export DBUS_SESSION_BUS_ADDRESS=unix:path=$XDG_RUNTIME_DIR/bus
|
||||
renderer=
|
||||
for _ in $(seq 1 300); do
|
||||
renderer=$(qdbus org.kde.KWin /KWin supportInformation 2> /dev/null |
|
||||
sed -n 's/^OpenGL renderer string: //p' | head -n 1 || true)
|
||||
[ -n "$renderer" ] && break
|
||||
sleep 1
|
||||
done
|
||||
[ -n "$renderer" ] || exit 0
|
||||
case $renderer in
|
||||
*llvmpipe* | *softpipe* | *swrast*) kind=software ;;
|
||||
*) kind=GPU ;;
|
||||
esac
|
||||
line="$kind (''${renderer%% *}): $renderer"
|
||||
printf '%s\n' "$line" > "$XDG_RUNTIME_DIR/run-kde-renderer"
|
||||
echo "run-kde: KWin draws with $line"
|
||||
'';
|
||||
};
|
||||
in
|
||||
{
|
||||
imports = [ ./krdp.nix ];
|
||||
|
||||
komorebi.krdp = {
|
||||
enable = true;
|
||||
passwordFile = "${taken}/rdp-password";
|
||||
};
|
||||
|
||||
services.komorebi = {
|
||||
config = {
|
||||
border = true;
|
||||
border_width = 6;
|
||||
border_offset = 5;
|
||||
default_workspace_padding = 15;
|
||||
default_container_padding = 15;
|
||||
animation = {
|
||||
enabled = true;
|
||||
style = "EaseOutExpo";
|
||||
duration = 250;
|
||||
};
|
||||
# this window is the guide to the others, and is not one of them
|
||||
ignore_rules = [
|
||||
{
|
||||
kind = "Class";
|
||||
id = "komorebi-cheat-sheet";
|
||||
matching_strategy = "Equals";
|
||||
}
|
||||
];
|
||||
monitors = [
|
||||
{
|
||||
workspaces = [
|
||||
{
|
||||
name = "I";
|
||||
layout = "BSP";
|
||||
}
|
||||
{
|
||||
name = "II";
|
||||
layout = "VerticalStack";
|
||||
}
|
||||
{
|
||||
name = "III";
|
||||
layout = "HorizontalStack";
|
||||
}
|
||||
{
|
||||
name = "IV";
|
||||
layout = "Columns";
|
||||
}
|
||||
{
|
||||
name = "V";
|
||||
layout = "Rows";
|
||||
}
|
||||
{
|
||||
name = "VI";
|
||||
layout = "Grid";
|
||||
}
|
||||
{
|
||||
name = "VII";
|
||||
layout = "RightMainVerticalStack";
|
||||
}
|
||||
{
|
||||
name = "VIII";
|
||||
layout = "Scrolling";
|
||||
}
|
||||
];
|
||||
}
|
||||
];
|
||||
};
|
||||
|
||||
# the module's default mode, with the sample bindings of docs/skhdrc.sample
|
||||
keybindings = {
|
||||
format = "skhd";
|
||||
file = ../../docs/skhdrc.sample;
|
||||
};
|
||||
};
|
||||
|
||||
environment.systemPackages = [
|
||||
cheatSheetCommand
|
||||
pkgs.foot
|
||||
pkgs.jq
|
||||
pkgs.kdePackages.dolphin
|
||||
pkgs.kdePackages.kate
|
||||
pkgs.kdePackages.konsole
|
||||
pkgs.kdePackages.qttools
|
||||
pkgs.less
|
||||
];
|
||||
environment.etc."run-kde/cheat-sheet.txt".source = cheatSheet;
|
||||
environment.etc."run-kde/config-home".source = configHome;
|
||||
|
||||
# The host's password and key, taken from the directory it shares. The files may belong to a user
|
||||
# of the host who is not the guest's user, so the guest copies them, as root, and gives them the
|
||||
# owner and the mode that RDP's unit and ssh want. Before the login, so that the unit that reads
|
||||
# the password finds it, and before ssh. A guest that is started with no directory has neither,
|
||||
# and RDP does not start.
|
||||
systemd.services.run-kde-credentials = {
|
||||
description = "Take the RDP password and the ssh key that the host shares";
|
||||
wantedBy = [ "multi-user.target" ];
|
||||
before = [
|
||||
"display-manager.service"
|
||||
"sshd.service"
|
||||
];
|
||||
unitConfig = {
|
||||
ConditionPathExists = shared;
|
||||
RequiresMountsFor = shared;
|
||||
};
|
||||
serviceConfig = {
|
||||
Type = "oneshot";
|
||||
RemainAfterExit = true;
|
||||
};
|
||||
path = [ pkgs.coreutils ];
|
||||
script = ''
|
||||
install -d -m 0755 ${taken} ${taken}/authorized_keys.d
|
||||
if [ -r ${shared}/rdp-password ]; then
|
||||
install -m 0400 -o ${user} -g ${config.users.users.${user}.group} \
|
||||
${shared}/rdp-password ${taken}/rdp-password
|
||||
fi
|
||||
if [ -r ${shared}/ssh_key.pub ]; then
|
||||
install -m 0644 ${shared}/ssh_key.pub ${taken}/authorized_keys.d/${user}
|
||||
fi
|
||||
'';
|
||||
};
|
||||
services.openssh.authorizedKeysFiles = [ "${taken}/authorized_keys.d/%u" ];
|
||||
|
||||
systemd.services.run-kde-report = {
|
||||
description = "Say what KWin draws with";
|
||||
wantedBy = [ "multi-user.target" ];
|
||||
after = [ "user@${toString config.users.users.${user}.uid}.service" ];
|
||||
serviceConfig = {
|
||||
# simple, so that waiting for KWin does not hold up the machine's start
|
||||
Type = "simple";
|
||||
User = user;
|
||||
ExecStart = lib.getExe report;
|
||||
# the line goes to the console, which is the terminal of whoever started the guest
|
||||
StandardOutput = "journal+console";
|
||||
};
|
||||
};
|
||||
|
||||
# The windows of the demo, once the session is up. The unit does not wait for the panel, the
|
||||
# script does, since only komorebi can say that it knows the panel's room.
|
||||
systemd.user.services.run-kde-demo = {
|
||||
description = "Open the windows of the demo";
|
||||
wantedBy = [ "plasma-workspace.target" ];
|
||||
after = [
|
||||
"plasma-core.target"
|
||||
"komorebi.service"
|
||||
];
|
||||
# the PATH a terminal in the session has, as the module's unit has it
|
||||
enableDefaultPath = false;
|
||||
environment.PATH = lib.concatStringsSep ":" [
|
||||
"/run/wrappers/bin"
|
||||
"/etc/profiles/per-user/%u/bin"
|
||||
"/run/current-system/sw/bin"
|
||||
];
|
||||
serviceConfig = {
|
||||
Type = "simple";
|
||||
ExecStart = lib.getExe demo;
|
||||
# the windows are in scopes of their own, and stay when the script is done
|
||||
KillMode = "process";
|
||||
};
|
||||
};
|
||||
|
||||
# Mesa's video compositor (vl_compositor) never loads an RGB to YUV matrix on a driver that takes
|
||||
# its graphics path, which virgl does: the draw multiplies by the YUV to RGB one of its initial
|
||||
# state, and the NV12 that scale_vaapi makes of the screen, which KRDP encodes, is the wrong
|
||||
# picture (nix/dev/mesa-virgl-rgb-yuv-csc.patch). `builtins.path` makes the patch a store path of
|
||||
# its own, so that Mesa is built once for any way of reading this file. There is no binary cache:
|
||||
# this is a build of Mesa from source.
|
||||
#
|
||||
# The same driver leaks a sync_file, an out-fence of the kernel, for every picture it converts or
|
||||
# uploads: the surface keeps the fence of its last flush in `pipe_fence`, and the next flush of
|
||||
# it stores a new one over it, so the first is never released, and its file descriptor is never
|
||||
# closed. A KRDP session ran out of descriptors (1024) after about 950 frames, and the stream
|
||||
# froze (nix/dev/mesa-virgl-fence-leak.patch).
|
||||
hardware.graphics.package = pkgs.mesa.overrideAttrs (old: {
|
||||
patches = (old.patches or [ ]) ++ [
|
||||
(builtins.path {
|
||||
path = ./mesa-virgl-rgb-yuv-csc.patch;
|
||||
name = "mesa-virgl-rgb-yuv-csc.patch";
|
||||
})
|
||||
(builtins.path {
|
||||
path = ./mesa-virgl-fence-leak.patch;
|
||||
name = "mesa-virgl-fence-leak.patch";
|
||||
})
|
||||
];
|
||||
});
|
||||
|
||||
# What only the runner, which is the machine of the person who starts the guest, can say. The
|
||||
# ports are forwarded and the display device is added on its command line, and the memory is
|
||||
# sized to what that machine has: the shared memory that virtiofs needs is a backend of the
|
||||
# size of the guest's memory, which nixpkgs would fix at the size of `memorySize`.
|
||||
virtualisation.vmVariant.virtualisation = {
|
||||
forwardPorts = lib.mkForce [ ];
|
||||
# `run-kde` says whether KVM is there, and `--tcg` lets it start without
|
||||
qemu.forceAccel = lib.mkForce false;
|
||||
qemu.enableSharedMemory = false;
|
||||
# QEMU never asks virglrenderer for the host's video encoder, so the guest's VA-API lists none
|
||||
# and KRDP encodes H.264 on the guest's CPUs. The patch does (nix/dev/qemu-virgl-video.patch);
|
||||
# VIRGL_RENDERER_USE_VIDEO is only defined with VIRGL_RENDERER_UNSTABLE_APIS. Only the runner
|
||||
# has it: there is no binary cache, so it is a QEMU built from source. The virglrenderer under
|
||||
# it has four patches, in this order, for a host whose encoder is the d3d12 one of WSL 2:
|
||||
# chroma-format the guest's Mesa and virglrenderer number the chroma format of a codec
|
||||
# differently: 4:2:0 was read as 4:2:2, and the encoder refused every codec
|
||||
# video-memory-upload
|
||||
# the d3d12 driver has no dma-bufs, so the picture to encode goes to the
|
||||
# surface through memory
|
||||
# h264-packed-sps Mesa's VA-API takes the level of the stream from a packed SPS, which
|
||||
# virglrenderer never sent: level 0 crashed the d3d12 encoder
|
||||
# ubo0-constants a constant buffer 0 bound as a buffer was never read by the shader, so the
|
||||
# colour matrix of an RGB to YUV conversion was zero
|
||||
qemu.package =
|
||||
(pkgs.qemu_kvm.override {
|
||||
virglrenderer = pkgs.virglrenderer.overrideAttrs (old: {
|
||||
patches = (old.patches or [ ]) ++ [
|
||||
./virglrenderer-chroma-format.patch
|
||||
./virglrenderer-video-memory-upload.patch
|
||||
./virglrenderer-h264-packed-sps.patch
|
||||
./virglrenderer-ubo0-constants.patch
|
||||
];
|
||||
});
|
||||
}).overrideAttrs
|
||||
(old: {
|
||||
patches = (old.patches or [ ]) ++ [ ./qemu-virgl-video.patch ];
|
||||
configureFlags = (old.configureFlags or [ ]) ++ [
|
||||
"--extra-cflags=-DVIRGL_RENDERER_UNSTABLE_APIS"
|
||||
];
|
||||
doCheck = false;
|
||||
});
|
||||
qemu.options = [
|
||||
"-object memory-backend-memfd,id=mem0,size=\${RUN_KDE_MEMORY:-8192}M,share=on"
|
||||
"-machine memory-backend=mem0"
|
||||
];
|
||||
sharedDirectories.run-kde = {
|
||||
source = "\${RUN_KDE_STATE:?set RUN_KDE_STATE to the directory with the password and the key}";
|
||||
target = shared;
|
||||
};
|
||||
# a mount under /run is hidden when the root file system's /run is replaced by a tmpfs, which
|
||||
# happens before the units run
|
||||
fileSystems.${shared}.neededForBoot = lib.mkForce false;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
virglrenderer: read the chroma format of a video codec in the guest's numbering
|
||||
|
||||
The guest's Mesa (26.2.5) sends a video codec's chroma format as the number of its own
|
||||
pipe_video_chroma_format, which since the enum moved to u_format.h is NONE, 400,
|
||||
420, 422, 440, 444 (0 to 5). The enum of virglrenderer, generated by
|
||||
u_format_table.py, is 400, 420, 422, 444, 440, NONE, so 4:2:0, which is 2, is read as
|
||||
4:2:2 and VA-API's encoder, which has no 4:2:2, refuses the codec: "format 0x2 not
|
||||
supported, supported formats: 0x1". The guest's encode then returns no data at all.
|
||||
|
||||
This reads the number as Mesa's. It is for a guest whose Mesa numbers it that way: a
|
||||
guest whose Mesa still numbers it as virglrenderer does would be read wrongly.
|
||||
|
||||
|
||||
diff --git a/src/vrend/vrend_decode.c b/src/vrend/vrend_decode.c
|
||||
index 7774a25..c6eb8f2 100644
|
||||
--- a/src/vrend/vrend_decode.c
|
||||
+++ b/src/vrend/vrend_decode.c
|
||||
@@ -1766,6 +1766,26 @@ static int vrend_decode_get_pipe_resource_layout(struct vrend_context *ctx, cons
|
||||
#ifdef ENABLE_VIDEO
|
||||
/* video codec related functions */
|
||||
|
||||
+/*
|
||||
+ * The chroma format of a codec comes from the guest as the number of its own enum, and the enum
|
||||
+ * of Mesa since its pipe_video_chroma_format moved to u_format.h is numbered NONE, 400, 420, 422,
|
||||
+ * 440, 444 (0 to 5), where this one, which u_format_table.py generates, is 400, 420, 422, 444, 440,
|
||||
+ * NONE. Taken as is, 4:2:0, which is 2, is 4:2:2 here, and the host's encoder, which has no 4:2:2,
|
||||
+ * refuses the codec ("format 0x2 not supported, supported formats: 0x1"), after which the guest
|
||||
+ * encodes nothing.
|
||||
+ */
|
||||
+static uint32_t vrend_decode_chroma_format(uint32_t guest_format)
|
||||
+{
|
||||
+ switch (guest_format) {
|
||||
+ case 1: return PIPE_VIDEO_CHROMA_FORMAT_400;
|
||||
+ case 2: return PIPE_VIDEO_CHROMA_FORMAT_420;
|
||||
+ case 3: return PIPE_VIDEO_CHROMA_FORMAT_422;
|
||||
+ case 4: return PIPE_VIDEO_CHROMA_FORMAT_440;
|
||||
+ case 5: return PIPE_VIDEO_CHROMA_FORMAT_444;
|
||||
+ default: return PIPE_VIDEO_CHROMA_FORMAT_NONE;
|
||||
+ }
|
||||
+}
|
||||
+
|
||||
static int vrend_decode_create_video_codec(struct vrend_context *ctx,
|
||||
const uint32_t *buf,
|
||||
uint32_t length)
|
||||
@@ -1778,7 +1798,8 @@ static int vrend_decode_create_video_codec(struct vrend_context *ctx,
|
||||
uint32_t handle = get_buf_entry(buf, VIRGL_CREATE_VIDEO_CODEC_HANDLE);
|
||||
uint32_t profile = get_buf_entry(buf, VIRGL_CREATE_VIDEO_CODEC_PROFILE);
|
||||
uint32_t entrypoint = get_buf_entry(buf, VIRGL_CREATE_VIDEO_CODEC_ENTRYPOINT);
|
||||
- uint32_t chroma_fmt = get_buf_entry(buf, VIRGL_CREATE_VIDEO_CODEC_CHROMA_FMT);
|
||||
+ uint32_t chroma_fmt = vrend_decode_chroma_format(
|
||||
+ get_buf_entry(buf, VIRGL_CREATE_VIDEO_CODEC_CHROMA_FMT));
|
||||
uint32_t level = get_buf_entry(buf, VIRGL_CREATE_VIDEO_CODEC_LEVEL);
|
||||
uint32_t width = get_buf_entry(buf, VIRGL_CREATE_VIDEO_CODEC_WIDTH);
|
||||
uint32_t height = get_buf_entry(buf, VIRGL_CREATE_VIDEO_CODEC_HEIGHT);
|
||||
@@ -0,0 +1,192 @@
|
||||
virglrenderer: send the SPS of an H.264 stream to encode to the host's VA-API
|
||||
|
||||
Mesa's VA-API takes the level (and the profile) of an H.264 stream to encode only from
|
||||
the packed sequence header: vlVaHandleVAEncSequenceParameterBufferTypeH264() does not
|
||||
set seq.level_idc, and vlVaHandleVAEncPackedHeaderDataBufferTypeH264() parses it from
|
||||
the application's SPS. The video protocol carries no SPS and no level, and virglrenderer
|
||||
sends no packed header, so on a host whose encoder needs the level, the d3d12 driver of
|
||||
WSL 2, seq.level_idc is 0 and d3d12_video_encoder_convert_level_h264() reaches
|
||||
UNREACHABLE("Unsupported H264 level"), which segfaults QEMU in vaEndPicture().
|
||||
|
||||
On an IDR frame, build a minimal SPS (profile, level, order count type, reference
|
||||
frames, size, cropping) and give it to VA-API as a packed sequence header. The level is
|
||||
the smallest of Table A-1 that holds the frame size and the macroblock rate. The d3d12
|
||||
encoder writes the SPS and PPS it encodes itself: the packed header only has to say what
|
||||
it needs to know.
|
||||
|
||||
|
||||
diff --git a/src/vrend/virgl_video.c b/src/vrend/virgl_video.c
|
||||
index 8b47837..8b71ebe 100644
|
||||
--- a/src/vrend/virgl_video.c
|
||||
+++ b/src/vrend/virgl_video.c
|
||||
@@ -1550,6 +1550,161 @@ err:
|
||||
return err;
|
||||
}
|
||||
|
||||
+/*
|
||||
+ * Mesa's VA-API takes the profile and the level of an H.264 stream to encode only from the
|
||||
+ * packed sequence header (vlVaHandleVAEncPackedHeaderDataBufferTypeH264 parses the SPS of the
|
||||
+ * application), and not from the sequence parameter. Nothing in the video protocol carries the
|
||||
+ * SPS or the level of the guest's, and the level of the codec is not one: with no packed header
|
||||
+ * seq.level_idc is 0, which the d3d12 encoder (WSL 2) does not take, and it crashes in
|
||||
+ * d3d12_video_encoder_convert_level_h264(). The d3d12 encoder writes the SPS and the PPS it
|
||||
+ * encodes itself, and the headers of the application only tell it to, so the SPS here only has to
|
||||
+ * say what the encoder needs: the profile, the level, the order count type, the number of
|
||||
+ * reference frames, the size and the cropping.
|
||||
+ */
|
||||
+struct h264_bits {
|
||||
+ uint8_t *buf;
|
||||
+ unsigned size; /* bytes in buf */
|
||||
+ unsigned pos; /* bits written */
|
||||
+};
|
||||
+
|
||||
+static void h264_put_bits(struct h264_bits *w, uint32_t value, unsigned nbits)
|
||||
+{
|
||||
+ while (nbits--) {
|
||||
+ if (w->pos / 8 < w->size) {
|
||||
+ if (value >> nbits & 1)
|
||||
+ w->buf[w->pos / 8] |= 0x80 >> (w->pos % 8);
|
||||
+ else
|
||||
+ w->buf[w->pos / 8] &= ~(0x80 >> (w->pos % 8));
|
||||
+ }
|
||||
+ w->pos++;
|
||||
+ }
|
||||
+}
|
||||
+
|
||||
+/* Exp-Golomb ue(v) */
|
||||
+static void h264_put_ue(struct h264_bits *w, uint32_t value)
|
||||
+{
|
||||
+ uint32_t v = value + 1;
|
||||
+ unsigned nbits = 0;
|
||||
+
|
||||
+ while (v >> nbits)
|
||||
+ nbits++;
|
||||
+ h264_put_bits(w, 0, nbits - 1);
|
||||
+ h264_put_bits(w, v, nbits);
|
||||
+}
|
||||
+
|
||||
+/* the smallest level that holds the frame size and the macroblock rate (Table A-1) */
|
||||
+static uint32_t h264_level_idc(uint32_t width_mbs, uint32_t height_mbs,
|
||||
+ uint32_t fps)
|
||||
+{
|
||||
+ static const struct { uint8_t idc; uint32_t max_mbps; uint32_t max_fs; } levels[] = {
|
||||
+ { 10, 1485, 99 }, { 11, 3000, 396 }, { 12, 6000, 396 },
|
||||
+ { 13, 11880, 396 }, { 20, 11880, 396 }, { 21, 19800, 792 },
|
||||
+ { 22, 20250, 1620 }, { 30, 40500, 1620 }, { 31, 108000, 3600 },
|
||||
+ { 32, 216000, 5120 }, { 40, 245760, 8192 }, { 41, 245760, 8192 },
|
||||
+ { 42, 522240, 8704 }, { 50, 589824, 22080 }, { 51, 983040, 36864 },
|
||||
+ { 52, 2073600, 36864 }, { 60, 4177920, 139264 },
|
||||
+ };
|
||||
+ uint32_t mbs = width_mbs * height_mbs;
|
||||
+ unsigned i;
|
||||
+
|
||||
+ if (!fps)
|
||||
+ fps = 30;
|
||||
+
|
||||
+ for (i = 0; i < ARRAY_SIZE(levels); i++) {
|
||||
+ if (mbs <= levels[i].max_fs && (uint64_t)mbs * fps <= levels[i].max_mbps)
|
||||
+ return levels[i].idc;
|
||||
+ }
|
||||
+
|
||||
+ return levels[ARRAY_SIZE(levels) - 1].idc;
|
||||
+}
|
||||
+
|
||||
+static void h264_encode_render_packed_sps(
|
||||
+ struct virgl_video_codec *codec,
|
||||
+ const struct virgl_h264_enc_picture_desc *desc)
|
||||
+{
|
||||
+ uint8_t data[64] = { 0 };
|
||||
+ struct h264_bits w = { data, sizeof(data), 0 };
|
||||
+ uint32_t profile_idc, fps, level_idc, width_mbs, height_mbs, poc_type;
|
||||
+ const struct virgl_h264_enc_rate_control *rc = &desc->rate_ctrl[0];
|
||||
+ VAEncPackedHeaderParameterBuffer hdr;
|
||||
+ VABufferID bufs[2];
|
||||
+ VAStatus va_stat;
|
||||
+ unsigned nbytes;
|
||||
+
|
||||
+ switch (codec->profile) {
|
||||
+ case PIPE_VIDEO_PROFILE_MPEG4_AVC_BASELINE:
|
||||
+ profile_idc = 66;
|
||||
+ break;
|
||||
+ case PIPE_VIDEO_PROFILE_MPEG4_AVC_MAIN:
|
||||
+ profile_idc = 77;
|
||||
+ break;
|
||||
+ default:
|
||||
+ profile_idc = 100;
|
||||
+ break;
|
||||
+ }
|
||||
+
|
||||
+ width_mbs = (codec->width + 15) / 16;
|
||||
+ height_mbs = (codec->height + 15) / 16;
|
||||
+ fps = rc->frame_rate_den ? rc->frame_rate_num / rc->frame_rate_den : 0;
|
||||
+ level_idc = h264_level_idc(width_mbs, height_mbs, fps);
|
||||
+ /* the order count types that the SPS below can say, 0 and 2 */
|
||||
+ poc_type = desc->seq.pic_order_cnt_type == 2 ? 2 : 0;
|
||||
+
|
||||
+ h264_put_bits(&w, 0x00000001, 32); /* start code */
|
||||
+ h264_put_bits(&w, 0x67, 8); /* nal_ref_idc 3, SPS */
|
||||
+ h264_put_bits(&w, profile_idc, 8);
|
||||
+ h264_put_bits(&w, desc->seq.enc_constraint_set_flags & 0x3f, 6);
|
||||
+ h264_put_bits(&w, 0, 2); /* reserved_zero_2bits */
|
||||
+ h264_put_bits(&w, level_idc, 8);
|
||||
+ h264_put_ue(&w, 0); /* seq_parameter_set_id */
|
||||
+ if (profile_idc == 100) {
|
||||
+ h264_put_ue(&w, 1); /* chroma_format_idc: 4:2:0 */
|
||||
+ h264_put_ue(&w, 0); /* bit_depth_luma_minus8 */
|
||||
+ h264_put_ue(&w, 0); /* bit_depth_chroma_minus8 */
|
||||
+ h264_put_bits(&w, 0, 1); /* qpprime_y_zero_transform_bypass */
|
||||
+ h264_put_bits(&w, 0, 1); /* seq_scaling_matrix_present */
|
||||
+ }
|
||||
+ h264_put_ue(&w, 0); /* log2_max_frame_num_minus4 */
|
||||
+ h264_put_ue(&w, poc_type);
|
||||
+ if (poc_type == 0)
|
||||
+ h264_put_ue(&w, 0); /* log2_max_pic_order_cnt_lsb_minus4 */
|
||||
+ h264_put_ue(&w, codec->max_references);
|
||||
+ h264_put_bits(&w, 0, 1); /* gaps_in_frame_num_value_allowed */
|
||||
+ h264_put_ue(&w, width_mbs - 1);
|
||||
+ h264_put_ue(&w, height_mbs - 1);
|
||||
+ h264_put_bits(&w, 1, 1); /* frame_mbs_only_flag */
|
||||
+ h264_put_bits(&w, 1, 1); /* direct_8x8_inference_flag */
|
||||
+ h264_put_bits(&w, desc->seq.enc_frame_cropping_flag ? 1 : 0, 1);
|
||||
+ if (desc->seq.enc_frame_cropping_flag) {
|
||||
+ h264_put_ue(&w, desc->seq.enc_frame_crop_left_offset);
|
||||
+ h264_put_ue(&w, desc->seq.enc_frame_crop_right_offset);
|
||||
+ h264_put_ue(&w, desc->seq.enc_frame_crop_top_offset);
|
||||
+ h264_put_ue(&w, desc->seq.enc_frame_crop_bottom_offset);
|
||||
+ }
|
||||
+ h264_put_bits(&w, 0, 1); /* vui_parameters_present_flag */
|
||||
+ h264_put_bits(&w, 1, 1); /* rbsp_stop_one_bit */
|
||||
+ nbytes = (w.pos + 7) / 8;
|
||||
+ if (nbytes > sizeof(data))
|
||||
+ return;
|
||||
+
|
||||
+ memset(&hdr, 0, sizeof(hdr));
|
||||
+ hdr.type = VAEncPackedHeaderSequence;
|
||||
+ hdr.bit_length = nbytes * 8;
|
||||
+ hdr.has_emulation_bytes = 0;
|
||||
+
|
||||
+ vaCreateBuffer(va_dpy, codec->va_ctx, VAEncPackedHeaderParameterBufferType,
|
||||
+ sizeof(hdr), 1, &hdr, &bufs[0]);
|
||||
+ vaCreateBuffer(va_dpy, codec->va_ctx, VAEncPackedHeaderDataBufferType,
|
||||
+ nbytes, 1, data, &bufs[1]);
|
||||
+
|
||||
+ va_stat = vaRenderPicture(va_dpy, codec->va_ctx, bufs, 2);
|
||||
+ if (VA_STATUS_SUCCESS != va_stat)
|
||||
+ virgl_error("render h264 packed sps failed, err = 0x%x\n", va_stat);
|
||||
+
|
||||
+ vaDestroyBuffer(va_dpy, bufs[0]);
|
||||
+ vaDestroyBuffer(va_dpy, bufs[1]);
|
||||
+}
|
||||
+
|
||||
static int h264_encode_render_sequence(
|
||||
struct virgl_video_codec *codec,
|
||||
struct virgl_video_buffer *source,
|
||||
@@ -1591,6 +1746,8 @@ static int h264_encode_render_sequence(
|
||||
goto error;
|
||||
}
|
||||
|
||||
+ h264_encode_render_packed_sps(codec, desc);
|
||||
+
|
||||
va_stat = vaRenderPicture(va_dpy, codec->va_ctx, &rc_param_buf, 1);
|
||||
if (VA_STATUS_SUCCESS != va_stat) {
|
||||
virgl_error("render h264 rate control param failed, err = 0x%x\n", va_stat);
|
||||
@@ -0,0 +1,105 @@
|
||||
vrend: read constant buffer 0 bound as a buffer into the default uniforms
|
||||
|
||||
A guest binds the constant buffer 0 of a shader either as inline constants
|
||||
(SET_CONSTANT_BUFFER) or as a buffer resource (SET_UNIFORM_BUFFER). A shader reads its
|
||||
constant buffer 0 from the default uniform block (fsconst0[] and the like), which vrend
|
||||
fills only from the inline constants, and vrend binds UBOs only for the buffers from 1:
|
||||
a buffer bound at index 0 was never seen by the shader, and its constants stayed zero.
|
||||
|
||||
Mesa's vl_compositor binds the colour matrix of an RGB to YUV conversion that way, so
|
||||
with the virgl driver the conversion (scale_vaapi from RGB to NV12 in FFmpeg, which
|
||||
KRDP uses) multiplied by a zero matrix and wrote zeros: a solid green picture.
|
||||
|
||||
Remember when the constant buffer 0 is set whether it is a buffer, and at the draw read
|
||||
it (glGetBufferSubData) into the uniforms with glUniform4uiv. It is read at every draw,
|
||||
since the guest can write to the buffer without binding it again. The conversion then
|
||||
writes what Mesa's matrix gives: the luma of a ramp goes from 0 0 0 to 0 124 255. What
|
||||
is left is Mesa's: the graphics path of vl_compositor_convert_rgb_to_yuv() never loads
|
||||
an RGB to YUV matrix, and the one that is sent is the YUV to RGB matrix of the
|
||||
compositor's initial state.
|
||||
|
||||
diff --git a/src/vrend/vrend_renderer.c b/src/vrend/vrend_renderer.c
|
||||
index 4bf88e0..a5166c4 100644
|
||||
--- a/src/vrend/vrend_renderer.c
|
||||
+++ b/src/vrend/vrend_renderer.c
|
||||
@@ -735,6 +735,8 @@ struct vrend_sub_context {
|
||||
|
||||
struct vrend_constants consts[PIPE_SHADER_TYPES];
|
||||
bool const_dirty[PIPE_SHADER_TYPES];
|
||||
+ /* constant buffer 0 was last bound as a buffer resource, not as inline constants */
|
||||
+ bool const0_from_buffer[PIPE_SHADER_TYPES];
|
||||
|
||||
struct pipe_constant_buffer cbs[PIPE_SHADER_TYPES][PIPE_MAX_CONSTANT_BUFFERS];
|
||||
uint32_t const_bufs_used_mask[PIPE_SHADER_TYPES];
|
||||
@@ -3486,6 +3488,7 @@ void vrend_set_constants(struct vrend_context *ctx,
|
||||
|
||||
consts = &ctx->sub->consts[shader];
|
||||
ctx->sub->const_dirty[shader] = true;
|
||||
+ ctx->sub->const0_from_buffer[shader] = false;
|
||||
|
||||
/* avoid reallocations by only growing the buffer */
|
||||
if (consts->num_allocated_consts < num_constant) {
|
||||
@@ -3517,6 +3520,9 @@ void vrend_set_uniform_buffer(struct vrend_context *ctx,
|
||||
struct pipe_constant_buffer *cbs = &ctx->sub->cbs[shader][index];
|
||||
const uint32_t mask = 1u << index;
|
||||
|
||||
+ if (index == 0)
|
||||
+ ctx->sub->const0_from_buffer[shader] = res_handle != 0;
|
||||
+
|
||||
if (res_handle) {
|
||||
res = vrend_renderer_ctx_res_lookup(ctx, res_handle);
|
||||
|
||||
@@ -5352,9 +5358,53 @@ static GLuint vrend_draw_bind_ubo_shader(struct vrend_sub_context *sub_ctx,
|
||||
return next_ubo_id;
|
||||
}
|
||||
|
||||
+/*
|
||||
+ * A guest can bind constant buffer 0 as a buffer resource (SET_UNIFORM_BUFFER) instead of as
|
||||
+ * inline constants (SET_CONSTANT_BUFFER): Mesa's vl_compositor does for the colour matrix of an
|
||||
+ * RGB to YUV conversion. A shader reads its constant buffer 0 as the default uniform block
|
||||
+ * (fsconst0[]), which only the inline constants fill, and the UBOs are for the buffers from 1:
|
||||
+ * the matrix stayed zero, and the conversion wrote zeros. Read the buffer into the uniforms. It
|
||||
+ * is read at every draw, as the guest can write to the buffer without binding it again. Returns
|
||||
+ * whether the constants came from the buffer.
|
||||
+ */
|
||||
+static bool vrend_draw_bind_const0_buffer(struct vrend_sub_context *sub_ctx,
|
||||
+ int shader_type)
|
||||
+{
|
||||
+ const struct vrend_shader_selector *sel = sub_ctx->shaders[shader_type];
|
||||
+ const struct pipe_constant_buffer *cb = &sub_ctx->cbs[shader_type][0];
|
||||
+ const struct vrend_resource *res = (const struct vrend_resource *)cb->buffer;
|
||||
+ unsigned num_consts, bytes;
|
||||
+ uint32_t *data;
|
||||
+
|
||||
+ if (!sub_ctx->const0_from_buffer[shader_type] || !sel || !sel->sinfo.num_consts ||
|
||||
+ sub_ctx->prog->const_location[shader_type] == -1 ||
|
||||
+ !(sub_ctx->const_bufs_used_mask[shader_type] & 1) ||
|
||||
+ !res || !has_bit(res->storage_bits, VREND_STORAGE_GL_BUFFER))
|
||||
+ return false;
|
||||
+
|
||||
+ num_consts = sel->sinfo.num_consts;
|
||||
+ bytes = num_consts * 4 * sizeof(uint32_t);
|
||||
+ data = calloc(1, bytes);
|
||||
+ if (!data)
|
||||
+ return true;
|
||||
+
|
||||
+ glBindBuffer(GL_COPY_READ_BUFFER, res->gl_id);
|
||||
+ glGetBufferSubData(GL_COPY_READ_BUFFER, cb->buffer_offset,
|
||||
+ MIN2(bytes, cb->buffer_size), data);
|
||||
+ glBindBuffer(GL_COPY_READ_BUFFER, 0);
|
||||
+
|
||||
+ glUniform4uiv(sub_ctx->prog->const_location[shader_type], num_consts, data);
|
||||
+ free(data);
|
||||
+
|
||||
+ return true;
|
||||
+}
|
||||
+
|
||||
static void vrend_draw_bind_const_shader(struct vrend_sub_context *sub_ctx,
|
||||
int shader_type, bool new_program)
|
||||
{
|
||||
+ if (vrend_draw_bind_const0_buffer(sub_ctx, shader_type))
|
||||
+ return;
|
||||
+
|
||||
if (sub_ctx->consts[shader_type].consts &&
|
||||
sub_ctx->shaders[shader_type] &&
|
||||
(sub_ctx->prog->const_location[shader_type] != -1) &&
|
||||
@@ -0,0 +1,237 @@
|
||||
virglrenderer: upload the picture to encode through memory
|
||||
|
||||
virglrenderer shares a video buffer with the host's VA-API driver as a dma-buf: it
|
||||
exports the VA surface (vaExportSurfaceHandle) and imports it into EGL to copy the
|
||||
guest's picture in. The d3d12 driver on WSL 2 has no dma-bufs, so the export fails
|
||||
("export surface failed, err = 0x6"), nothing is uploaded and the encoder returns an
|
||||
empty bitstream.
|
||||
|
||||
When the first export fails, read the planes of the guest's picture back from their
|
||||
textures (glReadPixels, into the planes of a VAImage) and write them to the surface
|
||||
through vaDeriveImage(), as FFmpeg's hwupload does; where the driver cannot derive an
|
||||
image, a vaCreateImage() image is copied with vaPutImage(). On the d3d12 driver the
|
||||
vaPutImage() copy came out with an all-zero luma plane (the chroma was right), where
|
||||
the derived image encodes exactly: a luma ramp through the encoder comes back as
|
||||
43 125 207 for 43 125 207. Where the export works nothing changes: it is tried first,
|
||||
and given up on only after it has failed.
|
||||
|
||||
diff --git a/src/vrend/virgl_video.c b/src/vrend/virgl_video.c
|
||||
index dc1e8cd..8b47837 100644
|
||||
--- a/src/vrend/virgl_video.c
|
||||
+++ b/src/vrend/virgl_video.c
|
||||
@@ -438,12 +438,100 @@ static void destroy_video_dma_buf(struct virgl_video_dma_buf *dmabuf)
|
||||
}
|
||||
}
|
||||
|
||||
+/*
|
||||
+ * Upload the picture to encode through memory, for a host that cannot export
|
||||
+ * a video buffer as a dma-buf: the d3d12 driver on WSL 2 has no dma-bufs, and
|
||||
+ * vaExportSurfaceHandle() fails on it. The callback reads the planes of the
|
||||
+ * guest's picture into a VAImage, which vaPutImage() copies to the surface,
|
||||
+ * as FFmpeg's hwupload does.
|
||||
+ */
|
||||
+static void encode_upload_picture_cpu(struct virgl_video_codec *codec,
|
||||
+ struct virgl_video_buffer *buffer)
|
||||
+{
|
||||
+ VAStatus va_stat;
|
||||
+ VAImageFormat fmt;
|
||||
+ VAImage image;
|
||||
+ void *data = NULL;
|
||||
+ uint8_t *dst[3] = { NULL, NULL, NULL };
|
||||
+ unsigned pitches[3] = { 0, 0, 0 };
|
||||
+ unsigned i;
|
||||
+ int ret;
|
||||
+ bool derived = false;
|
||||
+
|
||||
+ if (!callbacks || !callbacks->encode_read_picture)
|
||||
+ return;
|
||||
+
|
||||
+ memset(&fmt, 0, sizeof(fmt));
|
||||
+ fmt.byte_order = VA_LSB_FIRST;
|
||||
+ fmt.bits_per_pixel = 12;
|
||||
+ switch (buffer->format) {
|
||||
+ case PIPE_FORMAT_NV12:
|
||||
+ fmt.fourcc = VA_FOURCC_NV12;
|
||||
+ break;
|
||||
+ case PIPE_FORMAT_NV21:
|
||||
+ fmt.fourcc = VA_FOURCC_NV21;
|
||||
+ break;
|
||||
+ default:
|
||||
+ virgl_error("upload through memory: pipe format %d not supported\n",
|
||||
+ buffer->format);
|
||||
+ return;
|
||||
+ }
|
||||
+
|
||||
+ /*
|
||||
+ * Write to the surface itself when the driver can show it as an image, as FFmpeg's
|
||||
+ * hwupload does. On the d3d12 driver the picture of an image made with vaCreateImage() and
|
||||
+ * copied by vaPutImage() came out with an all-zero luma plane (the chroma was right),
|
||||
+ * where the same planes written through vaDeriveImage() encode exactly.
|
||||
+ */
|
||||
+ va_stat = vaDeriveImage(va_dpy, buffer->va_sfc, &image);
|
||||
+ if (VA_STATUS_SUCCESS == va_stat) {
|
||||
+ derived = true;
|
||||
+ } else {
|
||||
+ va_stat = vaCreateImage(va_dpy, &fmt, buffer->width, buffer->height, &image);
|
||||
+ if (VA_STATUS_SUCCESS != va_stat) {
|
||||
+ virgl_error("create image failed, err = 0x%x\n", va_stat);
|
||||
+ return;
|
||||
+ }
|
||||
+ }
|
||||
+
|
||||
+ va_stat = vaMapBuffer(va_dpy, image.buf, &data);
|
||||
+ if (VA_STATUS_SUCCESS != va_stat || !data) {
|
||||
+ virgl_error("map image failed, err = 0x%x\n", va_stat);
|
||||
+ goto destroy_image;
|
||||
+ }
|
||||
+
|
||||
+ for (i = 0; i < image.num_planes && i < ARRAY_SIZE(dst); i++) {
|
||||
+ dst[i] = (uint8_t *)data + image.offsets[i];
|
||||
+ pitches[i] = image.pitches[i];
|
||||
+ }
|
||||
+
|
||||
+ ret = callbacks->encode_read_picture(codec, buffer, image.num_planes,
|
||||
+ dst, pitches);
|
||||
+ vaUnmapBuffer(va_dpy, image.buf);
|
||||
+ if (ret) {
|
||||
+ virgl_error("read picture failed, err = %d\n", ret);
|
||||
+ goto destroy_image;
|
||||
+ }
|
||||
+
|
||||
+ if (!derived) {
|
||||
+ va_stat = vaPutImage(va_dpy, buffer->va_sfc, image.image_id,
|
||||
+ 0, 0, buffer->width, buffer->height,
|
||||
+ 0, 0, buffer->width, buffer->height);
|
||||
+ if (VA_STATUS_SUCCESS != va_stat)
|
||||
+ virgl_error("put image failed, err = 0x%x\n", va_stat);
|
||||
+ }
|
||||
+
|
||||
+destroy_image:
|
||||
+ vaDestroyImage(va_dpy, image.image_id);
|
||||
+}
|
||||
+
|
||||
static void encode_upload_picture(struct virgl_video_codec *codec,
|
||||
struct virgl_video_buffer *buffer)
|
||||
{
|
||||
VAStatus va_stat;
|
||||
+ static bool dmabuf_unsupported;
|
||||
|
||||
- if (!callbacks || !callbacks->encode_upload_picture)
|
||||
+ if (!callbacks)
|
||||
return;
|
||||
|
||||
va_stat = vaSyncSurface(va_dpy, buffer->va_sfc);
|
||||
@@ -452,11 +540,20 @@ static void encode_upload_picture(struct virgl_video_codec *codec,
|
||||
return;
|
||||
}
|
||||
|
||||
- if (!buffer->dmabuf)
|
||||
+ /* once a surface cannot be exported none can: go through memory */
|
||||
+ if (!buffer->dmabuf && !dmabuf_unsupported && callbacks->encode_upload_picture) {
|
||||
buffer->dmabuf = export_video_dma_buf(buffer, VIRGL_VIDEO_DMABUF_WRITE_ONLY);
|
||||
+ if (!buffer->dmabuf) {
|
||||
+ dmabuf_unsupported = true;
|
||||
+ virgl_warn("cannot export a video buffer as a dma-buf, "
|
||||
+ "uploading the pictures to encode through memory\n");
|
||||
+ }
|
||||
+ }
|
||||
|
||||
if (buffer->dmabuf)
|
||||
callbacks->encode_upload_picture(codec, buffer->dmabuf);
|
||||
+ else
|
||||
+ encode_upload_picture_cpu(codec, buffer);
|
||||
}
|
||||
|
||||
static void encode_completed(struct virgl_video_codec *codec,
|
||||
diff --git a/src/vrend/virgl_video.h b/src/vrend/virgl_video.h
|
||||
index e954559..c39d33d 100644
|
||||
--- a/src/vrend/virgl_video.h
|
||||
+++ b/src/vrend/virgl_video.h
|
||||
@@ -115,6 +115,16 @@ struct virgl_video_callbacks {
|
||||
void (*encode_upload_picture)(struct virgl_video_codec *codec,
|
||||
const struct virgl_video_dma_buf *dmabuf);
|
||||
|
||||
+ /* Read the picture data to be encoded into memory, plane by plane, for
|
||||
+ * a host whose video buffers cannot be exported as dma-bufs (the d3d12
|
||||
+ * driver of WSL 2): plane i is written to dst[i], pitches[i] bytes a row.
|
||||
+ * Returns 0 when the planes are filled. */
|
||||
+ int (*encode_read_picture)(struct virgl_video_codec *codec,
|
||||
+ struct virgl_video_buffer *buffer,
|
||||
+ unsigned num_planes,
|
||||
+ uint8_t * const *dst,
|
||||
+ const unsigned *pitches);
|
||||
+
|
||||
/* Callback when encoding is complete, used to download the encoded data
|
||||
* and reference picture */
|
||||
void (*encode_completed)(struct virgl_video_codec *codec,
|
||||
diff --git a/src/vrend/vrend_video.c b/src/vrend/vrend_video.c
|
||||
index 57341d8..dc30c55 100644
|
||||
--- a/src/vrend/vrend_video.c
|
||||
+++ b/src/vrend/vrend_video.c
|
||||
@@ -293,6 +293,58 @@ static void vrend_video_enocde_upload_picture(
|
||||
sync_video_buffer_to_dmabuf(buf, dmabuf);
|
||||
}
|
||||
|
||||
+/*
|
||||
+ * The picture to encode is the planes of a video buffer the guest rendered to, which are
|
||||
+ * textures here (R8 for the luma, RG8 for the chroma of NV12). Read them into the planes of a
|
||||
+ * VAImage, for a host that cannot share its video buffer as a dma-buf.
|
||||
+ */
|
||||
+static int vrend_video_encode_read_picture(
|
||||
+ struct virgl_video_codec *codec,
|
||||
+ struct virgl_video_buffer *vbuf,
|
||||
+ unsigned num_planes,
|
||||
+ uint8_t * const *dst,
|
||||
+ const unsigned *pitches)
|
||||
+{
|
||||
+ struct vrend_video_buffer *buf = vrend_video_buffer(vbuf);
|
||||
+ int ret = 0;
|
||||
+
|
||||
+ (void)codec;
|
||||
+
|
||||
+ if (!buf)
|
||||
+ return -1;
|
||||
+
|
||||
+ glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
|
||||
+ glPixelStorei(GL_PACK_ALIGNMENT, 1);
|
||||
+
|
||||
+ for (unsigned i = 0; i < num_planes && i < buf->num_planes; i++) {
|
||||
+ struct vrend_video_plane *plane = &buf->planes[i];
|
||||
+ struct vrend_resource *res;
|
||||
+ /* NV12 and NV21 have a plane of one byte a pixel, and one of two */
|
||||
+ const unsigned bytes_per_pixel = i ? 2 : 1;
|
||||
+
|
||||
+ res = vrend_renderer_ctx_res_lookup(buf->ctx->ctx, plane->res_handle);
|
||||
+ if (!res) {
|
||||
+ virgl_error("%s: res %d not found\n", __func__, plane->res_handle);
|
||||
+ ret = -1;
|
||||
+ continue;
|
||||
+ }
|
||||
+
|
||||
+ glBindFramebuffer(GL_READ_FRAMEBUFFER, plane->framebuffer);
|
||||
+ glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
|
||||
+ GL_TEXTURE_2D, res->gl_id, 0);
|
||||
+
|
||||
+ glPixelStorei(GL_PACK_ROW_LENGTH, pitches[i] / bytes_per_pixel);
|
||||
+ glReadPixels(0, 0, res->base.width0, res->base.height0,
|
||||
+ i ? GL_RG : GL_RED, GL_UNSIGNED_BYTE, dst[i]);
|
||||
+ }
|
||||
+
|
||||
+ glPixelStorei(GL_PACK_ROW_LENGTH, 0);
|
||||
+ glPixelStorei(GL_PACK_ALIGNMENT, 4);
|
||||
+ glBindFramebuffer(GL_FRAMEBUFFER, 0);
|
||||
+
|
||||
+ return ret;
|
||||
+}
|
||||
+
|
||||
static void vrend_video_encode_completed(
|
||||
struct virgl_video_codec *codec,
|
||||
const struct virgl_video_dma_buf *src_buf,
|
||||
@@ -349,6 +401,7 @@ static void vrend_video_encode_completed(
|
||||
static struct virgl_video_callbacks video_callbacks = {
|
||||
.decode_completed = vrend_video_decode_completed,
|
||||
.encode_upload_picture = vrend_video_enocde_upload_picture,
|
||||
+ .encode_read_picture = vrend_video_encode_read_picture,
|
||||
.encode_completed = vrend_video_encode_completed,
|
||||
};
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
# The init of the guest that scripts/wsl2-probe.sh boots (nix/dev/wsl2-probe.nix puts the
|
||||
# interpreter, PATH and `probe_loop` in front of this text). The kernel command line chooses what
|
||||
# it does:
|
||||
#
|
||||
# probe.mode=bench runs the CPU loop, prints the CPU, and powers off (the default)
|
||||
# probe.mode=hold prints a line every second for probe.hold seconds, then powers off: it
|
||||
# keeps a window open long enough to be seen
|
||||
# probe.mode=virtiofs loads the kernel's virtio and virtiofs modules, mounts the share that
|
||||
# the host serves with virtiofsd (tag probe.fstag, default probe), reads
|
||||
# probe.token's file and writes one, then powers off
|
||||
# probe.loops=N the number of iterations of the loop (default 600000)
|
||||
# probe.hold=N the number of seconds of the hold mode (default 8)
|
||||
# probe.serial=DEV a serial device the lines are copied to, for a run whose console is the
|
||||
# screen (default none: the console is the serial port)
|
||||
#
|
||||
# Every line that matters starts with `PROBE:` so that the host can find it in the console.
|
||||
|
||||
mount -t proc proc /proc
|
||||
mount -t sysfs sysfs /sys
|
||||
mount -t devtmpfs devtmpfs /dev
|
||||
exec </dev/console >/dev/console 2>&1
|
||||
|
||||
# param NAME DEFAULT: the value NAME has on the kernel command line
|
||||
param() {
|
||||
value=$(tr ' ' '\n' </proc/cmdline | sed -n "s/^$1=//p" | tail -n 1)
|
||||
echo "${value:-$2}"
|
||||
}
|
||||
|
||||
mode=$(param probe.mode bench)
|
||||
hold=$(param probe.hold 8)
|
||||
loops=$(param probe.loops 600000)
|
||||
serial=$(param probe.serial none)
|
||||
fstag=$(param probe.fstag probe)
|
||||
token=$(param probe.token none)
|
||||
|
||||
# to the console, and to the serial port that the host reads when the console is the screen
|
||||
say() {
|
||||
echo "PROBE:$*"
|
||||
[ -c "/dev/$serial" ] && echo "PROBE:$*" >"/dev/$serial"
|
||||
}
|
||||
|
||||
say "START kernel=$(uname -r) machine=$(uname -m) mode=$mode"
|
||||
say "CPU_MODEL=$(grep -m1 -E '^(model name|Processor|CPU part)' /proc/cpuinfo | cut -d: -f2- | sed 's/^ *//')"
|
||||
say "CPU_FLAGS=$(grep -m1 -E '^(flags|Features)' /proc/cpuinfo | cut -d: -f2- | sed 's/^ *//')"
|
||||
say "CPU_COUNT=$(grep -c '^processor' /proc/cpuinfo)"
|
||||
say "MEM_KB=$(grep -m1 '^MemTotal' /proc/meminfo | tr -s ' ' | cut -d' ' -f2)"
|
||||
|
||||
if [ "$mode" = bench ]; then
|
||||
say "LOOP_ITERATIONS=$loops"
|
||||
say "LOOP_MS=$(probe_loop "$loops")"
|
||||
fi
|
||||
|
||||
if [ "$mode" = virtiofs ]; then
|
||||
# virtio's PCI transport, FUSE and virtiofs are modules in this kernel, as they are in the real
|
||||
# guest's, whose initrd loads them before it mounts /nix/store
|
||||
for module in virtio_pci virtiofs; do
|
||||
if text=$(modprobe "$module" 2>&1); then
|
||||
say "MODULE_$module=loaded"
|
||||
elif [ "$module" = virtio_pci ] && [ -d /sys/bus/pci/drivers/virtio-pci ]; then
|
||||
# a kernel that has the transport built in (the aarch64 one) has no module of it
|
||||
say "MODULE_$module=built in"
|
||||
else
|
||||
say "MODULE_$module=failed: $text"
|
||||
fi
|
||||
done
|
||||
say "FILESYSTEMS=$(grep -E 'virtiofs|fuse' /proc/filesystems | tr -s '\t\n' ' ')"
|
||||
mkdir -p /store /share
|
||||
|
||||
# the host's /nix/store, read-only: the guest's busybox is read through it and checksummed
|
||||
if text=$(mount -t virtiofs -o ro probestore /store 2>&1); then
|
||||
say "STORE_MOUNT=ok"
|
||||
say "STORE_SHA256=$(sha256sum "/store/$(param probe.storefile none)" 2>&1 | cut -d' ' -f1)"
|
||||
if echo x >/store/probe-write 2>/dev/null; then
|
||||
say "STORE_WRITE=allowed"
|
||||
else
|
||||
say "STORE_WRITE=refused"
|
||||
fi
|
||||
else
|
||||
say "STORE_MOUNT=failed: $text"
|
||||
say "DEVICES=$(cd /sys/bus/virtio/devices 2>&1 && echo *)"
|
||||
fi
|
||||
|
||||
# a writable directory: the guest reads the file the host made and writes one of its own
|
||||
if text=$(mount -t virtiofs "$fstag" /share 2>&1); then
|
||||
say "SHARE_MOUNT=ok"
|
||||
say "SHARE_LISTING=$(cd /share && echo *)"
|
||||
say "SHARE_READ=$(cat /share/token 2>&1)"
|
||||
say "SHARE_READ_OWNER=$(stat -c '%u:%g %a' /share/token 2>&1)"
|
||||
if text=$({ echo "$token" >/share/from-guest; } 2>&1); then
|
||||
say "SHARE_WRITE=ok"
|
||||
else
|
||||
say "SHARE_WRITE=failed: $text"
|
||||
fi
|
||||
say "SHARE_WRITE_OWNER=$(stat -c '%u:%g %a' /share/from-guest 2>&1)"
|
||||
else
|
||||
say "SHARE_MOUNT=failed: $text"
|
||||
fi
|
||||
sync
|
||||
fi
|
||||
|
||||
if [ "$mode" = hold ]; then
|
||||
n=0
|
||||
while [ "$n" -lt "$hold" ]; do
|
||||
say "ALIVE $n of $hold seconds: this window is the guest of wsl2-probe, it closes by itself"
|
||||
sleep 1
|
||||
n=$((n + 1))
|
||||
done
|
||||
fi
|
||||
|
||||
say "DONE"
|
||||
sync
|
||||
poweroff -f
|
||||
# a kernel that does not power off on request is stopped by the host's timeout
|
||||
sleep 600
|
||||
@@ -0,0 +1,22 @@
|
||||
# A CPU loop that scripts/wsl2-probe.sh times in three places: on the host, in a guest under
|
||||
# KVM and in a guest under TCG. busybox's ash runs it, so the same interpreter runs the same
|
||||
# instructions everywhere and only the way the CPU is provided differs.
|
||||
#
|
||||
# `probe_loop N` counts to N and prints the milliseconds it took, read from /proc/uptime, whose
|
||||
# resolution is 10 ms: a loop shorter than about a second says little.
|
||||
|
||||
# the uptime in centiseconds; the 1 in front of the fraction keeps ash from reading 08 as octal
|
||||
probe_centis() {
|
||||
read -r up _ </proc/uptime
|
||||
echo $((${up%.*} * 100 + 1${up#*.} - 100))
|
||||
}
|
||||
|
||||
probe_loop() {
|
||||
start=$(probe_centis)
|
||||
i=0
|
||||
while [ "$i" -lt "$1" ]; do
|
||||
i=$((i + 1))
|
||||
done
|
||||
end=$(probe_centis)
|
||||
echo $(((end - start) * 10))
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
{
|
||||
pkgs,
|
||||
# the revision the probe says it came from; the checks pass a constant, so that they are the
|
||||
# same derivations for every commit
|
||||
rev,
|
||||
}:
|
||||
|
||||
# scripts/wsl2-probe.sh, with the tools it uses from nixpkgs, and the tiny guest it boots.
|
||||
#
|
||||
# The guest is a kernel from the binary cache and an initrd made here of a static busybox, the
|
||||
# kernel modules that virtiofs needs, and the init in wsl2-probe-init.sh: nothing in it is built
|
||||
# from source, so the first run is a download. docs/dev/wsl2-probe.md says what the probe does.
|
||||
let
|
||||
inherit (pkgs) lib;
|
||||
|
||||
busybox = pkgs.pkgsStatic.busybox;
|
||||
|
||||
# the kernel is the one the real guest boots (the default of NixOS), so that what the probe's
|
||||
# guest can do with virtiofs is what the real guest's kernel can do
|
||||
kernel = pkgs.linuxPackages.kernel;
|
||||
|
||||
# the file of the kernel package that QEMU boots
|
||||
kernelImage = if pkgs.stdenv.hostPlatform.isAarch64 then "Image" else "bzImage";
|
||||
|
||||
# virtio's PCI transport, FUSE and virtiofs are modules of that kernel, not built in; this is
|
||||
# the closure of them in the shape the NixOS initrd uses (modules.dep included, for modprobe)
|
||||
modules = pkgs.makeModulesClosure {
|
||||
kernel = pkgs.aggregateModules [ (lib.getOutput "modules" kernel) ];
|
||||
firmware = pkgs.runCommand "wsl2-probe-no-firmware" { } "mkdir -p $out";
|
||||
rootModules = [
|
||||
"virtio_pci"
|
||||
"virtiofs"
|
||||
];
|
||||
};
|
||||
|
||||
# the loop that the host and the guest both time, which busybox's ash runs in both
|
||||
loop = pkgs.writeTextFile {
|
||||
name = "wsl2-probe-loop.sh";
|
||||
text = builtins.readFile ./wsl2-probe-loop.sh;
|
||||
checkPhase = ''
|
||||
${lib.getExe pkgs.shellcheck} --shell=sh "$target"
|
||||
'';
|
||||
};
|
||||
|
||||
init = pkgs.writeTextFile {
|
||||
name = "wsl2-probe-init";
|
||||
executable = true;
|
||||
text = ''
|
||||
#!${busybox}/bin/sh
|
||||
PATH=${busybox}/bin
|
||||
# shellcheck source=/dev/null
|
||||
. ${loop}
|
||||
${builtins.readFile ./wsl2-probe-init.sh}
|
||||
'';
|
||||
checkPhase = ''
|
||||
${lib.getExe pkgs.shellcheck} --shell=sh "$target"
|
||||
'';
|
||||
};
|
||||
|
||||
initrd = pkgs.makeInitrd {
|
||||
contents = [
|
||||
{
|
||||
object = init;
|
||||
symlink = "/init";
|
||||
}
|
||||
{
|
||||
object = "${modules}/lib/modules";
|
||||
symlink = "/lib/modules";
|
||||
}
|
||||
];
|
||||
};
|
||||
|
||||
guest = pkgs.runCommand "wsl2-probe-guest" { } ''
|
||||
mkdir -p $out
|
||||
ln -s ${kernel}/${kernelImage} $out/kernel
|
||||
ln -s ${initrd}/initrd $out/initrd
|
||||
ln -s ${busybox}/bin/busybox $out/busybox
|
||||
ln -s ${loop} $out/loop.sh
|
||||
'';
|
||||
|
||||
probe = pkgs.writeShellApplication {
|
||||
name = "wsl2-probe";
|
||||
runtimeInputs = with pkgs; [
|
||||
# QEMU with GTK and VirGL, which the real guest uses, and the daemon that serves the guest's
|
||||
# /nix/store and shared directories
|
||||
qemu_kvm
|
||||
virtiofsd
|
||||
# eglinfo and glxinfo
|
||||
mesa-demos
|
||||
socat
|
||||
# what the script needs of a system, the same on every distribution
|
||||
coreutils
|
||||
findutils
|
||||
gawk
|
||||
gnugrep
|
||||
gnused
|
||||
iproute2
|
||||
jq
|
||||
procps
|
||||
util-linux
|
||||
];
|
||||
# the script sets its own options: a probe that stops at the first failure answers nothing
|
||||
bashOptions = [ ];
|
||||
text = ''
|
||||
export WSL2_PROBE_GUEST=${guest}
|
||||
export WSL2_PROBE_REV=${rev}
|
||||
${builtins.readFile ../../scripts/wsl2-probe.sh}
|
||||
'';
|
||||
meta = {
|
||||
description = "Probes a NixOS-WSL2 machine for KVM, WSLg, a GPU and RDP, for a Plasma guest";
|
||||
mainProgram = "wsl2-probe";
|
||||
};
|
||||
};
|
||||
in
|
||||
{
|
||||
inherit guest probe;
|
||||
}
|
||||
Reference in new issue
Block a user