diff --git a/client/include/interface/renderer.h b/client/include/interface/renderer.h index 33d7d04c..082a29bb 100644 --- a/client/include/interface/renderer.h +++ b/client/include/interface/renderer.h @@ -96,6 +96,22 @@ typedef struct LG_RendererFormat uint32_t hdrMaxContentLightLevel; uint32_t hdrMaxFrameAverageLightLevel; uint32_t sdrWhiteLevel; + + /* Multi-display layout. + * + * When displayCount is zero the frame is a single conventional display and + * a renderer should ignore everything below, behaving exactly as before. + * + * Otherwise the frame is a packed atlas of displayCount guest displays and + * the renderer must compose it: each display is copied from its atlas + * rectangle to its position on the guest's virtual desktop. The view + * rectangle selects the region of that virtual desktop to present, which is + * either the whole desktop or a single display the user has chosen. */ + unsigned int displayCount; + KVMFRDisplay displays[KVMFR_MAX_DISPLAYS]; + int viewX, viewY; // top left of the presented region + unsigned int viewWidth; // width of the presented region + unsigned int viewHeight; // height of the presented region } LG_RendererFormat; diff --git a/client/renderers/EGL/CMakeLists.txt b/client/renderers/EGL/CMakeLists.txt index 8b88346f..c406c88c 100644 --- a/client/renderers/EGL/CMakeLists.txt +++ b/client/renderers/EGL/CMakeLists.txt @@ -50,6 +50,8 @@ build_shaders( shader shader/desktop.vert shader/desktop_rgb.frag + shader/compose.vert + shader/compose.frag shader/cursor.vert shader/cursor_rgb.frag shader/cursor_mono.frag @@ -88,6 +90,7 @@ add_library(renderer_EGL STATIC model.c desktop.c desktop_rects.c + compose.c cursor.c damage.c hdr_overlay.c diff --git a/client/renderers/EGL/compose.c b/client/renderers/EGL/compose.c new file mode 100644 index 00000000..e8143494 --- /dev/null +++ b/client/renderers/EGL/compose.c @@ -0,0 +1,285 @@ +/** + * Looking Glass + * Copyright © 2017-2026 The Looking Glass Authors + * https://looking-glass.io + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., 59 + * Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#include "compose.h" + +#include "framebuffer.h" +#include "shader.h" +#include "state.h" +#include "texture.h" + +#include "common/debug.h" + +#include +#include + +#include + +#include "compose.vert.h" +#include "compose.frag.h" + +/* Two triangles per display, as an indexed quad. */ +#define VERTS_PER_DISPLAY 4 +#define INDICES_PER_DISPLAY 6 +/* each vertex is x, y, u, v */ +#define FLOATS_PER_VERTEX 4 + +struct EGL_Compose +{ + EGL_Framebuffer * framebuffer; + EGL_Shader * shader; + EGL_Uniform * uViewSize; + EGL_Uniform * uAtlasSize; + + GLuint vao; + GLuint buffers[2]; + + bool configured; + unsigned int viewWidth, viewHeight; + unsigned int atlasWidth, atlasHeight; + int quadCount; +}; + +bool egl_composeInit(EGL_Compose ** compose) +{ + *compose = calloc(1, sizeof(**compose)); + if (!*compose) + { + DEBUG_ERROR("Failed to allocate the display composition"); + return false; + } + + EGL_Compose * this = *compose; + + if (!egl_framebufferInit(&this->framebuffer) || + !egl_shaderInit(&this->shader) || + !egl_shaderCompile(this->shader, + b_shader_compose_vert, b_shader_compose_vert_size, + b_shader_compose_frag, b_shader_compose_frag_size, + false, NULL)) + { + DEBUG_ERROR("Failed to initialize the display composition"); + egl_composeFree(compose); + return false; + } + + this->uViewSize = egl_shaderGetUniform(this->shader, "viewSize" ); + this->uAtlasSize = egl_shaderGetUniform(this->shader, "atlasSize"); + + glGenVertexArrays(1, &this->vao); + egl_stateBindVertexArray(this->vao); + + glGenBuffers(2, this->buffers); + egl_stateBindBuffer(GL_ARRAY_BUFFER, this->buffers[0]); + glBufferData(GL_ARRAY_BUFFER, + KVMFR_MAX_DISPLAYS * VERTS_PER_DISPLAY * FLOATS_PER_VERTEX * + sizeof(GLfloat), + NULL, GL_STREAM_DRAW); + + // location 0 is the view position, location 1 the atlas position + glEnableVertexAttribArray(0); + glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, + FLOATS_PER_VERTEX * sizeof(GLfloat), (void *)0); + glEnableVertexAttribArray(1); + glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, + FLOATS_PER_VERTEX * sizeof(GLfloat), + (void *)(2 * sizeof(GLfloat))); + + GLushort indices[KVMFR_MAX_DISPLAYS * INDICES_PER_DISPLAY]; + for(int i = 0; i < KVMFR_MAX_DISPLAYS; ++i) + { + indices[INDICES_PER_DISPLAY * i + 0] = VERTS_PER_DISPLAY * i + 0; + indices[INDICES_PER_DISPLAY * i + 1] = VERTS_PER_DISPLAY * i + 1; + indices[INDICES_PER_DISPLAY * i + 2] = VERTS_PER_DISPLAY * i + 2; + indices[INDICES_PER_DISPLAY * i + 3] = VERTS_PER_DISPLAY * i + 0; + indices[INDICES_PER_DISPLAY * i + 4] = VERTS_PER_DISPLAY * i + 2; + indices[INDICES_PER_DISPLAY * i + 5] = VERTS_PER_DISPLAY * i + 3; + } + + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, this->buffers[1]); + glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof indices, indices, + GL_STATIC_DRAW); + + return true; +} + +void egl_composeFree(EGL_Compose ** compose) +{ + if (!*compose) + return; + + EGL_Compose * this = *compose; + + if (this->vao) + { + glDeleteVertexArrays(1, &this->vao); + glDeleteBuffers(2, this->buffers); + egl_stateInvalidateShared(); + } + + egl_shaderFree(&this->shader); + egl_framebufferFree(&this->framebuffer); + free(this); + *compose = NULL; +} + +bool egl_composeSetup(EGL_Compose * this, const LG_RendererFormat * format) +{ + this->configured = false; + this->quadCount = 0; + + if (!format->displayCount) + return false; + + if (format->displayCount > KVMFR_MAX_DISPLAYS) + { + DEBUG_ERROR("Frame reports %u displays, the maximum is %d", + format->displayCount, KVMFR_MAX_DISPLAYS); + return false; + } + + if (!format->viewWidth || !format->viewHeight) + { + DEBUG_ERROR("Frame reports an empty view region"); + return false; + } + + /* The composed image is the same pixel format as the atlas, so a display is + * copied without conversion and HDR handling downstream is unaffected. */ + enum EGL_PixelFormat pixFmt; + switch(format->type) + { + case FRAME_TYPE_BGRA : pixFmt = EGL_PF_BGRA ; break; + case FRAME_TYPE_RGBA : pixFmt = EGL_PF_RGBA ; break; + case FRAME_TYPE_RGBA10 : pixFmt = EGL_PF_RGBA10 ; break; + case FRAME_TYPE_RGBA16F: pixFmt = EGL_PF_RGBA16F; break; + + default: + DEBUG_ERROR("Frame type %d cannot be composed", format->type); + return false; + } + + if (!egl_framebufferSetup(this->framebuffer, pixFmt, + format->viewWidth, format->viewHeight)) + { + DEBUG_ERROR("Failed to create the %ux%u composition target", + format->viewWidth, format->viewHeight); + return false; + } + + this->viewWidth = format->viewWidth; + this->viewHeight = format->viewHeight; + this->atlasWidth = format->frameWidth; + this->atlasHeight = format->frameHeight; + + /* Build one quad per display that intersects the view, mapping its atlas + * rectangle onto its place in the view. Displays fully outside the view are + * skipped, which is what makes selecting a single display cost nothing + * extra to draw. */ + GLfloat verts[KVMFR_MAX_DISPLAYS * VERTS_PER_DISPLAY * FLOATS_PER_VERTEX]; + int quads = 0; + + for(unsigned i = 0; i < format->displayCount; ++i) + { + const KVMFRDisplay * d = &format->displays[i]; + + // position within the view, which may be a single display's region + const int vx = d->desktopX - format->viewX; + const int vy = d->desktopY - format->viewY; + + if (vx + (int)d->desktopWidth <= 0 || + vy + (int)d->desktopHeight <= 0 || + vx >= (int)format->viewWidth || + vy >= (int)format->viewHeight) + continue; + + if (d->atlasX + d->atlasWidth > format->frameWidth || + d->atlasY + d->atlasHeight > format->frameHeight) + { + DEBUG_ERROR("Display %u (%s) lies outside the %ux%u frame", + i, d->name, format->frameWidth, format->frameHeight); + return false; + } + + const GLfloat x0 = vx, y0 = vy; + const GLfloat x1 = vx + (GLfloat)d->desktopWidth; + const GLfloat y1 = vy + (GLfloat)d->desktopHeight; + + const GLfloat u0 = d->atlasX, v0 = d->atlasY; + const GLfloat u1 = d->atlasX + (GLfloat)d->atlasWidth; + const GLfloat v1 = d->atlasY + (GLfloat)d->atlasHeight; + + GLfloat * v = verts + quads * VERTS_PER_DISPLAY * FLOATS_PER_VERTEX; + v[ 0] = x0; v[ 1] = y0; v[ 2] = u0; v[ 3] = v0; + v[ 4] = x1; v[ 5] = y0; v[ 6] = u1; v[ 7] = v0; + v[ 8] = x1; v[ 9] = y1; v[10] = u1; v[11] = v1; + v[12] = x0; v[13] = y1; v[14] = u0; v[15] = v1; + ++quads; + } + + if (!quads) + { + DEBUG_ERROR("No display intersects the requested view region"); + return false; + } + + egl_stateBindVertexArray(this->vao); + egl_stateBindBuffer(GL_ARRAY_BUFFER, this->buffers[0]); + glBufferSubData(GL_ARRAY_BUFFER, 0, + quads * VERTS_PER_DISPLAY * FLOATS_PER_VERTEX * sizeof(GLfloat), verts); + + this->quadCount = quads; + this->configured = true; + return true; +} + +EGL_Texture * egl_composeRun(EGL_Compose * this, EGL_Texture * atlas) +{ + if (!this->configured) + return NULL; + + egl_framebufferBind(this->framebuffer); + + /* Displays never overlap and the view is not guaranteed to be fully + * covered, so clear first to keep any gap between monitors black rather + * than showing the previous frame there. */ + egl_stateBlend(false); + egl_stateScissor(false); + glClearColor(0.0f, 0.0f, 0.0f, 1.0f); + glClear(GL_COLOR_BUFFER_BIT); + + egl_textureBind(atlas); + egl_shaderUse(this->shader); + egl_uniform2f(this->uViewSize , this->viewWidth , this->viewHeight ); + egl_uniform2f(this->uAtlasSize, this->atlasWidth, this->atlasHeight); + + egl_stateBindVertexArray(this->vao); + glDrawElements(GL_TRIANGLES, this->quadCount * INDICES_PER_DISPLAY, + GL_UNSIGNED_SHORT, NULL); + + return egl_framebufferGetTexture(this->framebuffer); +} + +void egl_composeGetSize(EGL_Compose * this, + unsigned int * width, unsigned int * height) +{ + *width = this->viewWidth; + *height = this->viewHeight; +} diff --git a/client/renderers/EGL/compose.h b/client/renderers/EGL/compose.h new file mode 100644 index 00000000..d02c611a --- /dev/null +++ b/client/renderers/EGL/compose.h @@ -0,0 +1,62 @@ +/** + * Looking Glass + * Copyright © 2017-2026 The Looking Glass Authors + * https://looking-glass.io + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., 59 + * Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#pragma once + +#include + +#include "texture.h" +#include "interface/renderer.h" + +/* Composes a packed multi-display atlas frame into a single image of the + * guest's virtual desktop, or of one display within it. + * + * Running this as its own pass, rather than folding it into the desktop + * shader, keeps every stage downstream (post processing, HDR handling, the + * cursor, damage tracking and input mapping) working on one conventional + * frame. Those stages then need no knowledge of multi-display at all. */ + +typedef struct EGL_Compose EGL_Compose; + +bool egl_composeInit(EGL_Compose ** compose); +void egl_composeFree(EGL_Compose ** compose); + +/** + * Configure the composition for a frame format. + * + * Returns false if the format cannot be composed, in which case the caller + * should fall back to presenting the raw atlas rather than showing nothing. + */ +bool egl_composeSetup(EGL_Compose * compose, const LG_RendererFormat * format); + +/** + * Compose `atlas` into the configured view. + * + * Returns the composed texture, or NULL if composition is not configured or + * failed, in which case the caller should present the atlas unchanged. + */ +EGL_Texture * egl_composeRun(EGL_Compose * compose, EGL_Texture * atlas); + +/** + * The dimensions of the composed output. Only valid after a successful + * egl_composeSetup. + */ +void egl_composeGetSize(EGL_Compose * compose, + unsigned int * width, unsigned int * height); diff --git a/client/renderers/EGL/desktop.c b/client/renderers/EGL/desktop.c index 1538f15a..9847939b 100644 --- a/client/renderers/EGL/desktop.c +++ b/client/renderers/EGL/desktop.c @@ -39,6 +39,7 @@ #include "desktop_rgb.frag.h" #include "desktop_rgb.def.h" +#include "compose.h" #include "postprocess.h" #include "filters.h" @@ -107,6 +108,12 @@ struct EGL_Desktop EGL_PostProcess * pp; _Atomic(bool) processFrame; + + /* Multi-display composition. When active the frame is a packed atlas and + * `compose` turns it into the presented view before anything else runs, so + * width/height below describe the composed view rather than the atlas. */ + EGL_Compose * compose; + bool composeActive; }; // forwards @@ -217,6 +224,12 @@ bool egl_desktopInit(EGL * egl, EGL_Desktop ** desktop_, EGLDisplay * display, desktop->peakLuminance = option_get_int ("egl", "peakLuminance"); desktop->maxCLL = option_get_int ("egl", "maxCLL" ); + if (!egl_composeInit(&desktop->compose)) + { + DEBUG_ERROR("Failed to initialize the display composition"); + return false; + } + if (!egl_postProcessInit(&desktop->pp)) { DEBUG_ERROR("Failed to initialize the post process manager"); @@ -265,6 +278,7 @@ void egl_desktopFree(EGL_Desktop ** desktop) egl_shaderFree (&(*desktop)->shader .shader); egl_shaderFree (&(*desktop)->dmaShader.shader); egl_desktopRectsFree(&(*desktop)->mesh ); + egl_composeFree (&(*desktop)->compose ); egl_postProcessFree(&(*desktop)->pp); free(*desktop); @@ -387,6 +401,26 @@ bool egl_desktopSetup(EGL_Desktop * desktop, const LG_RendererFormat format) return false; } + /* A multi-display frame is an atlas that has to be composed before it means + * anything on screen. If composition cannot be set up we still present the + * raw atlas, which looks wrong but keeps the session usable and makes the + * cause visible in the log. */ + desktop->composeActive = false; + if (format.displayCount) + { + if (egl_composeSetup(desktop->compose, &desktop->format)) + { + egl_composeGetSize(desktop->compose, &desktop->width, &desktop->height); + desktop->composeActive = true; + + DEBUG_INFO("Composing %u displays from a %ux%u atlas into a %ux%u view", + format.displayCount, format.frameWidth, format.frameHeight, + desktop->width, desktop->height); + } + else + DEBUG_WARN("Display composition unavailable, showing the packed frame"); + } + return true; } @@ -481,13 +515,40 @@ bool egl_desktopRender(EGL_Desktop * desktop, unsigned int outputWidth, DEBUG_ERROR("Failed to process the desktop texture"); } + /* Compose the packed atlas into the presented view before anything else + * runs, so post processing, HDR, the cursor and damage all operate on one + * ordinary frame and need no multi-display handling of their own. */ + const bool composing = desktop->composeActive && !desktop->useSpice; + if (composing) + { + EGL_Texture * composed = egl_composeRun(desktop->compose, tex); + if (likely(composed != NULL)) + { + /* the composed view is a plain texture, never an imported DMA buffer, + * so the DMA sampling path must not be used for it */ + tex = composed; + dma = false; + } + else + { + // present the atlas rather than nothing at all + width = desktop->format.frameWidth; + height = desktop->format.frameHeight; + } + } + int scaleAlgo = EGL_SCALE_NEAREST; egl_desktopRectsMatrix(desktop->matrix, width, height, x, y, scaleX, scaleY, rotate); - egl_desktopRectsUpdate(desktop->mesh, rects, width, height); - *fullFrame = false; + /* Damage arrives in packed atlas coordinates, which say nothing about where + * the pixels landed once composed. Redraw the whole view instead; the + * expensive part, uploading the frame, still honours the damage rectangles. */ + egl_desktopRectsUpdate(desktop->mesh, composing ? NULL : rects, + width, height); + + *fullFrame = composing; const bool hdr = desktop->hdr && !desktop->useSpice; uint32_t hdrPeak = 0; if (hdr) diff --git a/client/renderers/EGL/shader/compose.frag b/client/renderers/EGL/shader/compose.frag new file mode 100644 index 00000000..4e0e35a8 --- /dev/null +++ b/client/renderers/EGL/shader/compose.frag @@ -0,0 +1,20 @@ +#version 300 es +#extension GL_OES_EGL_image_external_essl3 : enable + +precision highp float; + +/* Straight copy of the atlas into the composed desktop. Sampling is a plain + * texel fetch: composition never scales a display, so introducing filtering + * here would only soften the image before the real scaling pass runs. */ + +in vec2 uv; +out vec4 color; + +uniform sampler2D sampler1; + +void main() +{ + ivec2 size = textureSize(sampler1, 0); + ivec2 pos = ivec2(uv * vec2(size)); + color = texelFetch(sampler1, clamp(pos, ivec2(0), size - ivec2(1)), 0); +} diff --git a/client/renderers/EGL/shader/compose.vert b/client/renderers/EGL/shader/compose.vert new file mode 100644 index 00000000..e92deec0 --- /dev/null +++ b/client/renderers/EGL/shader/compose.vert @@ -0,0 +1,26 @@ +#version 300 es +precision highp float; + +/* Composes a packed multi-display atlas into the guest's virtual desktop. + * + * Unlike the desktop shader, the texture coordinate is supplied per vertex + * rather than derived from the position: a display's place in the atlas has + * nothing to do with its place on the desktop, so the two cannot be tied + * together. */ + +layout(location = 0) in vec2 vertex; // position in view pixels +layout(location = 1) in vec2 texture; // source position in atlas pixels + +out vec2 uv; + +uniform vec2 viewSize; +uniform vec2 atlasSize; + +void main() +{ + // view pixels -> clip space, with the origin at the top left + vec2 pos = vertex / viewSize * 2.0 - 1.0; + gl_Position = vec4(pos.x, -pos.y, 0.0, 1.0); + + uv = texture / atlasSize; +} diff --git a/client/src/main.h b/client/src/main.h index 1beebde3..d8789615 100644 --- a/client/src/main.h +++ b/client/src/main.h @@ -101,6 +101,20 @@ struct AppState atomic_bool keyDown[KEY_MAX]; bool haveSrcSize; + + /* Multi-display state, taken from the last frame format. + * + * displayCount is zero for a conventional single-display guest, in which + * case the view fields are unused and the client behaves as it always has. + * + * When non-zero the frame is a packed atlas, and viewX/viewY give the offset + * of the presented region within the guest's virtual desktop. Input has to + * be shifted by that offset because the guest addresses its cursor in + * virtual desktop coordinates, not in coordinates of the region on show. */ + unsigned int displayCount; + KVMFRDisplay displays[KVMFR_MAX_DISPLAYS]; + int viewX, viewY; + struct Point windowPos; int windowW, windowH; int windowCX, windowCY; diff --git a/common/CMakeLists.txt b/common/CMakeLists.txt index a2795a17..93fdee9b 100644 --- a/common/CMakeLists.txt +++ b/common/CMakeLists.txt @@ -25,6 +25,7 @@ set(COMMON_SOURCES src/framebuffer.c src/KVMFR.c src/countedbuffer.c + src/displays.c src/rects.c src/runningavg.c src/ringbuffer.c diff --git a/common/include/common/KVMFR.h b/common/include/common/KVMFR.h index 26354e34..38e55071 100644 --- a/common/include/common/KVMFR.h +++ b/common/include/common/KVMFR.h @@ -28,7 +28,7 @@ #include "types.h" #define KVMFR_MAGIC "KVMFR---" -#define KVMFR_VERSION 23 +#define KVMFR_VERSION 24 // Fallback used by producers that cannot report the source display's SDR // white level. IDD frames override this with IDDCX_METADATA2::SdrWhiteLevel. @@ -36,6 +36,9 @@ #define KVMFR_MAX_DAMAGE_RECTS 64 +// The maximum number of guest displays that may be packed into a single frame. +#define KVMFR_MAX_DISPLAYS 8 + #define LGMP_Q_POINTER 1 #define LGMP_Q_FRAME 2 @@ -176,6 +179,48 @@ enum typedef uint32_t KVMFRFrameFlags; +enum +{ + KVMFR_DISPLAY_FLAG_PRIMARY = 0x1 // the guest's primary display +}; + +typedef uint32_t KVMFRDisplayFlags; + +/* Describes one guest display packed into a multi-display (atlas) frame. + * + * A display occupies the axis-aligned rectangle (atlasX, atlasY, atlasWidth, + * atlasHeight) inside the frame data, and belongs at (desktopX, desktopY) on + * the guest's virtual desktop. The two rectangles always have the same size: + * packing relocates a display but never scales it. + * + * The producer normalises the virtual desktop so that the top-left of the + * bounding box of all displays is (0, 0), making desktopX/desktopY + * non-negative. They remain signed so a consumer can safely offset them. + * + * `rotation` is the orientation the guest has applied to this display. The + * packed pixels are already in their final, rotated orientation, so it is + * informational only; consumers do not need to rotate to compose the desktop. + */ +typedef struct KVMFRDisplay +{ + uint32_t id; // producer-assigned stable identifier + KVMFRDisplayFlags flags; // bit field combination of KVMFR_DISPLAY_FLAG_* + + uint32_t atlasX; // x offset of this display within the frame + uint32_t atlasY; // y offset of this display within the frame + uint32_t atlasWidth; // width of this display within the frame + uint32_t atlasHeight; // height of this display within the frame + + int32_t desktopX; // x position on the guest's virtual desktop + int32_t desktopY; // y position on the guest's virtual desktop + uint32_t desktopWidth; // width on the guest's virtual desktop + uint32_t desktopHeight; // height on the guest's virtual desktop + + FrameRotation rotation; // the guest's rotation for this display + char name[32]; // friendly output name, NUL terminated +} +KVMFRDisplay; + typedef struct KVMFRFrame { uint32_t formatVer; // the frame format version number @@ -211,6 +256,22 @@ typedef struct KVMFRFrame // White level in nits for SDR content composited into an HDR frame, such as // the hardware cursor. Valid for all frames; SDR modes normally report 80. uint32_t sdrWhiteLevel; + + /* Multi-display layout. + * + * A displayCount of zero means this is a conventional single-display frame + * and `displays` carries no meaning: the frame is the whole guest screen, + * exactly as in KVMFR versions before 24. + * + * Otherwise the frame is an atlas holding `displayCount` displays, and + * screenWidth/screenHeight describe the guest's virtual desktop rather than + * the packed frame. frameWidth/frameHeight remain the dimensions of the + * packed frame itself, so a consumer with no multi-display support still + * renders something coherent (the raw atlas) rather than reading out of + * bounds. Damage rectangles are always expressed in packed frame space. + */ + uint32_t displayCount; + KVMFRDisplay displays[KVMFR_MAX_DISPLAYS]; } KVMFRFrame; diff --git a/common/include/common/displays.h b/common/include/common/displays.h new file mode 100644 index 00000000..311c9646 --- /dev/null +++ b/common/include/common/displays.h @@ -0,0 +1,102 @@ +/** + * Looking Glass + * Copyright © 2017-2026 The Looking Glass Authors + * https://looking-glass.io + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., 59 + * Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#ifndef _H_LG_COMMON_DISPLAYS_ +#define _H_LG_COMMON_DISPLAYS_ + +#pragma once + +#include +#include + +#include "KVMFR.h" +#include "types.h" + +/* The largest atlas edge the packer will produce. Chosen to stay within the + * GL_MAX_TEXTURE_SIZE of every GPU the client supports; 16384 is the common + * limit on current hardware and 8192 on older parts, so we stay at 16384 and + * let the client reject anything its driver cannot honour. */ +#define LG_DISPLAY_MAX_ATLAS_EDGE 16384 + +/* One guest display as reported by a capture backend, before packing. */ +typedef struct LGDisplayInfo +{ + uint32_t id; // backend-assigned stable identifier + bool primary; // true if this is the guest's primary display + int32_t x, y; // position on the guest virtual desktop + uint32_t width, height; // size on the guest virtual desktop + FrameRotation rotation; // the guest's rotation for this display + char name[32]; // friendly output name +} +LGDisplayInfo; + +/** + * Pack a set of guest displays into a single atlas frame. + * + * Displays are placed without scaling or rotation, so each keeps its exact + * pixel dimensions. The packer chooses a layout that minimises the atlas area + * (and therefore the shared memory and copy cost per frame), falling back to a + * simple vertical stack if no better arrangement fits. + * + * Virtual desktop coordinates are normalised so the bounding box of all + * displays starts at (0, 0), and returned via desktopWidth/desktopHeight. + * + * `out` must have room for `count` entries and `count` must not exceed + * KVMFR_MAX_DISPLAYS. Entries in `out` are written in the same order as `in`, + * so a backend can keep its own indexing. + * + * `alignment` rounds the atlas width up to a multiple of that many pixels, so + * a backend can satisfy a row-pitch requirement. Pass 1 for no alignment. + * + * Returns false if the inputs are invalid or no layout fits within + * LG_DISPLAY_MAX_ATLAS_EDGE. + */ +bool lgDisplaysPack( + const LGDisplayInfo * in, + unsigned count, + unsigned alignment, + KVMFRDisplay * out, + unsigned * atlasWidth, + unsigned * atlasHeight, + unsigned * desktopWidth, + unsigned * desktopHeight); + +/** + * Returns the index of the display in `displays` containing the virtual + * desktop point (x, y), or -1 if the point falls in a gap between displays. + */ +int lgDisplaysFindAtPoint(const KVMFRDisplay * displays, unsigned count, + int32_t x, int32_t y); + +/** + * Translate a point from guest virtual desktop space into packed atlas space. + * Returns false if the point does not fall inside any display. + */ +bool lgDisplaysDesktopToAtlas(const KVMFRDisplay * displays, unsigned count, + int32_t dx, int32_t dy, int32_t * ax, int32_t * ay); + +/** + * Translate a point from packed atlas space into guest virtual desktop space. + * Returns false if the point falls in atlas padding owned by no display. + */ +bool lgDisplaysAtlasToDesktop(const KVMFRDisplay * displays, unsigned count, + int32_t ax, int32_t ay, int32_t * dx, int32_t * dy); + +#endif diff --git a/common/src/displays.c b/common/src/displays.c new file mode 100644 index 00000000..aaa23968 --- /dev/null +++ b/common/src/displays.c @@ -0,0 +1,288 @@ +/** + * Looking Glass + * Copyright © 2017-2026 The Looking Glass Authors + * https://looking-glass.io + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., 59 + * Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +#include "common/displays.h" +#include "common/debug.h" + +#include + +/* Place displays onto shelves of the given width, in the supplied order. + * + * This is first-fit decreasing-height shelf packing: with `order` sorted by + * descending height, the first display on a shelf is its tallest, so the shelf + * height is known as soon as it is opened and no display is ever placed above + * a taller neighbour. It is not optimal in general, but monitor sets are tiny + * and usually uniform, where it is exact. + * + * Returns false if any display is wider than the shelf width. */ +static bool packWithWidth( + const LGDisplayInfo * in, + const unsigned * order, + unsigned count, + unsigned width, + unsigned * outX, + unsigned * outY, + unsigned * outHeight, + unsigned * outUsedWidth) +{ + unsigned shelfX = 0, shelfY = 0, shelfHeight = 0, usedWidth = 0; + + for(unsigned i = 0; i < count; ++i) + { + const unsigned idx = order[i]; + const unsigned w = in[idx].width; + const unsigned h = in[idx].height; + + if (w > width) + return false; + + if (shelfX + w > width) + { + // no room left on this shelf, open a new one above it + shelfY += shelfHeight; + shelfX = 0; + shelfHeight = 0; + } + + outX[idx] = shelfX; + outY[idx] = shelfY; + + shelfX += w; + if (h > shelfHeight) + shelfHeight = h; + if (shelfX > usedWidth) + usedWidth = shelfX; + } + + *outHeight = shelfY + shelfHeight; + *outUsedWidth = usedWidth; + return true; +} + +bool lgDisplaysPack( + const LGDisplayInfo * in, + unsigned count, + unsigned alignment, + KVMFRDisplay * out, + unsigned * atlasWidth, + unsigned * atlasHeight, + unsigned * desktopWidth, + unsigned * desktopHeight) +{ + if (!in || !out || count == 0 || count > KVMFR_MAX_DISPLAYS) + return false; + + if (alignment == 0) + alignment = 1; + + for(unsigned i = 0; i < count; ++i) + if (in[i].width == 0 || in[i].height == 0) + { + DEBUG_ERROR("Display %u (%s) has a zero dimension (%ux%u)", + i, in[i].name, in[i].width, in[i].height); + return false; + } + + /* sort indices by descending height, breaking ties on descending width and + * then ascending id so the layout is stable across frames */ + unsigned order[KVMFR_MAX_DISPLAYS]; + for(unsigned i = 0; i < count; ++i) + order[i] = i; + + for(unsigned i = 1; i < count; ++i) + { + const unsigned v = order[i]; + unsigned j = i; + while(j > 0) + { + const LGDisplayInfo * a = &in[order[j - 1]]; + const LGDisplayInfo * b = &in[v]; + const bool swap = + (b->height > a->height) || + (b->height == a->height && b->width > a->width) || + (b->height == a->height && b->width == a->width && b->id < a->id); + if (!swap) + break; + order[j] = order[j - 1]; + --j; + } + order[j] = v; + } + + unsigned maxWidth = 0, totalWidth = 0; + for(unsigned i = 0; i < count; ++i) + { + if (in[i].width > maxWidth) + maxWidth = in[i].width; + totalWidth += in[i].width; + } + + /* Candidate shelf widths: the widest single display (a pure vertical stack), + * every running total in packing order (which produces the natural "N per + * row" arrangements), and the sum of all widths (a single row). Every + * candidate is at least maxWidth so no display is ever too wide to place. */ + unsigned candidates[KVMFR_MAX_DISPLAYS + 2]; + unsigned candidateCount = 0; + + candidates[candidateCount++] = maxWidth; + unsigned running = 0; + for(unsigned i = 0; i < count; ++i) + { + running += in[order[i]].width; + candidates[candidateCount++] = running < maxWidth ? maxWidth : running; + } + candidates[candidateCount++] = totalWidth < maxWidth ? maxWidth : totalWidth; + + unsigned bestX[KVMFR_MAX_DISPLAYS], bestY[KVMFR_MAX_DISPLAYS]; + unsigned bestWidth = 0, bestHeight = 0; + uint64_t bestArea = 0; + bool haveBest = false; + + for(unsigned c = 0; c < candidateCount; ++c) + { + const unsigned width = candidates[c]; + if (width > LG_DISPLAY_MAX_ATLAS_EDGE) + continue; + + unsigned x[KVMFR_MAX_DISPLAYS], y[KVMFR_MAX_DISPLAYS]; + unsigned height, usedWidth; + if (!packWithWidth(in, order, count, width, x, y, &height, &usedWidth)) + continue; + + // align the width only after tightening, so alignment is applied once + unsigned alignedWidth = + ((usedWidth + alignment - 1) / alignment) * alignment; + + if (alignedWidth > LG_DISPLAY_MAX_ATLAS_EDGE || + height > LG_DISPLAY_MAX_ATLAS_EDGE) + continue; + + const uint64_t area = (uint64_t)alignedWidth * height; + const unsigned edge = alignedWidth > height ? alignedWidth : height; + const unsigned bestEdge = bestWidth > bestHeight ? bestWidth : bestHeight; + + /* prefer the smallest atlas; on a tie prefer the squarer one, which is + * kinder to texture size limits and to the GPU's cache */ + if (!haveBest || area < bestArea || (area == bestArea && edge < bestEdge)) + { + memcpy(bestX, x, sizeof(*x) * count); + memcpy(bestY, y, sizeof(*y) * count); + bestWidth = alignedWidth; + bestHeight = height; + bestArea = area; + haveBest = true; + } + } + + if (!haveBest) + { + DEBUG_ERROR("No atlas layout for %u displays fits within %ux%u", + count, LG_DISPLAY_MAX_ATLAS_EDGE, LG_DISPLAY_MAX_ATLAS_EDGE); + return false; + } + + /* normalise the virtual desktop so its bounding box starts at (0, 0) */ + int32_t minX = in[0].x, minY = in[0].y; + int64_t maxX = (int64_t)in[0].x + in[0].width; + int64_t maxY = (int64_t)in[0].y + in[0].height; + for(unsigned i = 1; i < count; ++i) + { + if (in[i].x < minX) + minX = in[i].x; + if (in[i].y < minY) + minY = in[i].y; + if ((int64_t)in[i].x + in[i].width > maxX) + maxX = (int64_t)in[i].x + in[i].width; + if ((int64_t)in[i].y + in[i].height > maxY) + maxY = (int64_t)in[i].y + in[i].height; + } + + for(unsigned i = 0; i < count; ++i) + { + KVMFRDisplay * d = &out[i]; + memset(d, 0, sizeof(*d)); + + d->id = in[i].id; + d->flags = in[i].primary ? KVMFR_DISPLAY_FLAG_PRIMARY : 0; + d->atlasX = bestX[i]; + d->atlasY = bestY[i]; + d->atlasWidth = in[i].width; + d->atlasHeight = in[i].height; + d->desktopX = in[i].x - minX; + d->desktopY = in[i].y - minY; + d->desktopWidth = in[i].width; + d->desktopHeight = in[i].height; + d->rotation = in[i].rotation; + + memcpy(d->name, in[i].name, sizeof(d->name) - 1); + d->name[sizeof(d->name) - 1] = '\0'; + } + + *atlasWidth = bestWidth; + *atlasHeight = bestHeight; + *desktopWidth = (unsigned)(maxX - minX); + *desktopHeight = (unsigned)(maxY - minY); + return true; +} + +int lgDisplaysFindAtPoint(const KVMFRDisplay * displays, unsigned count, + int32_t x, int32_t y) +{ + for(unsigned i = 0; i < count; ++i) + { + const KVMFRDisplay * d = &displays[i]; + if (x >= d->desktopX && x < d->desktopX + (int32_t)d->desktopWidth && + y >= d->desktopY && y < d->desktopY + (int32_t)d->desktopHeight) + return (int)i; + } + return -1; +} + +bool lgDisplaysDesktopToAtlas(const KVMFRDisplay * displays, unsigned count, + int32_t dx, int32_t dy, int32_t * ax, int32_t * ay) +{ + const int index = lgDisplaysFindAtPoint(displays, count, dx, dy); + if (index < 0) + return false; + + const KVMFRDisplay * d = &displays[index]; + *ax = (int32_t)d->atlasX + (dx - d->desktopX); + *ay = (int32_t)d->atlasY + (dy - d->desktopY); + return true; +} + +bool lgDisplaysAtlasToDesktop(const KVMFRDisplay * displays, unsigned count, + int32_t ax, int32_t ay, int32_t * dx, int32_t * dy) +{ + for(unsigned i = 0; i < count; ++i) + { + const KVMFRDisplay * d = &displays[i]; + if (ax >= (int32_t)d->atlasX && + ax < (int32_t)d->atlasX + (int32_t)d->atlasWidth && + ay >= (int32_t)d->atlasY && + ay < (int32_t)d->atlasY + (int32_t)d->atlasHeight) + { + *dx = d->desktopX + (ax - (int32_t)d->atlasX); + *dy = d->desktopY + (ay - (int32_t)d->atlasY); + return true; + } + } + return false; +} diff --git a/common/tests/test_displays.c b/common/tests/test_displays.c new file mode 100644 index 00000000..0877e436 --- /dev/null +++ b/common/tests/test_displays.c @@ -0,0 +1,152 @@ +#include "common/displays.h" +#include "common/debug.h" +#include +#include +#include + +static int failures = 0; + +static void check(bool cond, const char * what) +{ + printf(" [%s] %s\n", cond ? "PASS" : "FAIL", what); + if (!cond) + ++failures; +} + +/* verify no two displays overlap in the atlas and all are in bounds */ +static bool validate(const KVMFRDisplay * d, unsigned count, + unsigned aw, unsigned ah) +{ + for(unsigned i = 0; i < count; ++i) + { + if (d[i].atlasX + d[i].atlasWidth > aw) return false; + if (d[i].atlasY + d[i].atlasHeight > ah) return false; + if (d[i].atlasWidth != d[i].desktopWidth) return false; + if (d[i].atlasHeight != d[i].desktopHeight) return false; + for(unsigned j = i + 1; j < count; ++j) + { + const bool disjoint = + d[i].atlasX + d[i].atlasWidth <= d[j].atlasX || + d[j].atlasX + d[j].atlasWidth <= d[i].atlasX || + d[i].atlasY + d[i].atlasHeight <= d[j].atlasY || + d[j].atlasY + d[j].atlasHeight <= d[i].atlasY; + if (!disjoint) + return false; + } + } + return true; +} + +static void run(const char * title, const LGDisplayInfo * in, unsigned count) +{ + KVMFRDisplay out[KVMFR_MAX_DISPLAYS]; + unsigned aw, ah, dw, dh; + + printf("\n== %s ==\n", title); + if (!lgDisplaysPack(in, count, 1, out, &aw, &ah, &dw, &dh)) + { + printf(" [FAIL] pack returned false\n"); + ++failures; + return; + } + + uint64_t used = 0; + for(unsigned i = 0; i < count; ++i) + used += (uint64_t)in[i].width * in[i].height; + + printf(" atlas %ux%u (%.1f MP), desktop %ux%u, waste %.1f%%\n", + aw, ah, (aw * (double)ah) / 1e6, dw, dh, + 100.0 * (1.0 - used / (aw * (double)ah))); + for(unsigned i = 0; i < count; ++i) + printf(" %-8s atlas +%u+%u %ux%u desktop +%d+%d\n", + out[i].name, out[i].atlasX, out[i].atlasY, + out[i].atlasWidth, out[i].atlasHeight, + out[i].desktopX, out[i].desktopY); + + check(validate(out, count, aw, ah), "layout is non-overlapping and in bounds"); + check((uint64_t)aw * ah >= used, "atlas is at least the sum of display areas"); +} + +int main(void) +{ + debug_init(); + + /* the real geometry of the development machine */ + const LGDisplayInfo real[3] = { + { .id = 0, .name = "DP-2", .x = 2160, .y = 2880, .width = 5120, .height = 2880 }, + { .id = 1, .name = "DP-1", .x = 0, .y = 896, .width = 2160, .height = 3840 }, + { .id = 2, .name = "DP-3", .x = 2160, .y = 0, .width = 5120, .height = 2880, + .primary = true }, + }; + run("3 mixed displays (this machine)", real, 3); + + const LGDisplayInfo triple[3] = { + { .id = 0, .name = "A", .x = 0, .y = 0, .width = 1920, .height = 1080 }, + { .id = 1, .name = "B", .x = 1920, .y = 0, .width = 1920, .height = 1080 }, + { .id = 2, .name = "C", .x = 3840, .y = 0, .width = 1920, .height = 1080 }, + }; + run("3 identical 1080p displays", triple, 3); + + const LGDisplayInfo single[1] = { + { .id = 0, .name = "only", .x = 0, .y = 0, .width = 2560, .height = 1440 }, + }; + run("single display", single, 1); + + const LGDisplayInfo negative[2] = { + { .id = 0, .name = "left", .x = -1920, .y = -100, .width = 1920, .height = 1080 }, + { .id = 1, .name = "right", .x = 0, .y = 0, .width = 2560, .height = 1440 }, + }; + run("negative desktop coordinates", negative, 2); + + printf("\n== edge cases ==\n"); + KVMFRDisplay out[KVMFR_MAX_DISPLAYS]; + unsigned aw, ah, dw, dh; + check(!lgDisplaysPack(real, 0, 1, out, &aw, &ah, &dw, &dh), + "zero displays rejected"); + check(!lgDisplaysPack(real, KVMFR_MAX_DISPLAYS + 1, 1, out, &aw, &ah, &dw, &dh), + "too many displays rejected"); + + const LGDisplayInfo zero[1] = { + { .id = 0, .name = "bad", .x = 0, .y = 0, .width = 0, .height = 1080 } }; + check(!lgDisplaysPack(zero, 1, 1, out, &aw, &ah, &dw, &dh), + "zero-width display rejected"); + + const LGDisplayInfo huge[2] = { + { .id = 0, .name = "h1", .x = 0, .y = 0, .width = 16384, .height = 16384 }, + { .id = 1, .name = "h2", .x = 0, .y = 0, .width = 16384, .height = 16384 } }; + check(!lgDisplaysPack(huge, 2, 1, out, &aw, &ah, &dw, &dh), + "oversized set rejected rather than silently truncated"); + + /* alignment */ + const LGDisplayInfo odd[1] = { + { .id = 0, .name = "odd", .x = 0, .y = 0, .width = 1234, .height = 1000 } }; + if (lgDisplaysPack(odd, 1, 64, out, &aw, &ah, &dw, &dh)) + check(aw % 64 == 0, "atlas width honours 64px alignment"); + else + check(false, "alignment case packed"); + + /* desktop normalisation */ + if (lgDisplaysPack(negative, 2, 1, out, &aw, &ah, &dw, &dh)) + { + check(out[0].desktopX == 0 && out[1].desktopX == 1920, + "negative coordinates normalised to origin"); + check(dw == 4480 && dh == 1540, "virtual desktop bounds computed"); + } + + /* atlas <-> desktop round trip */ + if (lgDisplaysPack(real, 3, 1, out, &aw, &ah, &dw, &dh)) + { + int32_t ax, ay, dx, dy; + bool ok = lgDisplaysDesktopToAtlas(out, 3, 2160 + 10, 2880 + 20, &ax, &ay) && + lgDisplaysAtlasToDesktop(out, 3, ax, ay, &dx, &dy); + check(ok && dx == 2170 && dy == 2900, "desktop->atlas->desktop round trips"); + check(lgDisplaysFindAtPoint(out, 3, 0, 0) == -1, + "point in a desktop gap reports no display"); + check(lgDisplaysFindAtPoint(out, 3, 2160, 0) == 2, + "point inside DP-3 finds DP-3"); + } + + printf("\n%s (%d failure%s)\n", failures ? "FAILED" : "ALL PASSED", + failures, failures == 1 ? "" : "s"); + return failures != 0; +} diff --git a/common/tests/test_stubs.c b/common/tests/test_stubs.c new file mode 100644 index 00000000..6f66a246 --- /dev/null +++ b/common/tests/test_stubs.c @@ -0,0 +1,5 @@ +/* minimal stand-ins for the platform layer so the packer can be unit tested */ +static const char * lookup[] = + { "", "[I]", "[W]", "[E]", "[T]", "[F]", "[!]" }; +const char ** debug_lookup = lookup; +void platform_debugInit(void) {} diff --git a/host/include/interface/capture.h b/host/include/interface/capture.h index 5040f133..a48bed84 100644 --- a/host/include/interface/capture.h +++ b/host/include/interface/capture.h @@ -97,6 +97,16 @@ typedef struct CaptureFrame uint32_t damageRectsCount; FrameDamageRect damageRects[KVMFR_MAX_DAMAGE_RECTS]; + + /* Multi-display layout for backends that pack several guest displays into + * one frame. Leave displayCount at zero for a conventional single-display + * capture; the host then reports the frame exactly as it always has. + * + * When non-zero, screenWidth/screenHeight describe the guest's virtual + * desktop while frameWidth/frameHeight describe the packed atlas, and + * damage rectangles remain in packed atlas space. */ + uint32_t displayCount; + KVMFRDisplay displays[KVMFR_MAX_DISPLAYS]; } CaptureFrame; diff --git a/host/platform/Linux/capture/XCB/CMakeLists.txt b/host/platform/Linux/capture/XCB/CMakeLists.txt index d8c045c4..5ded3c97 100644 --- a/host/platform/Linux/capture/XCB/CMakeLists.txt +++ b/host/platform/Linux/capture/XCB/CMakeLists.txt @@ -8,6 +8,7 @@ add_library(capture_XCB STATIC target_link_libraries(capture_XCB lg_common xcb + xcb-randr xcb-shm xcb-xfixes ) diff --git a/host/platform/Linux/capture/XCB/src/xcb.c b/host/platform/Linux/capture/XCB/src/xcb.c index 744d6eaf..f75bbf27 100644 --- a/host/platform/Linux/capture/XCB/src/xcb.c +++ b/host/platform/Linux/capture/XCB/src/xcb.c @@ -23,12 +23,15 @@ #include "common/util.h" #include "common/option.h" #include "common/debug.h" +#include "common/displays.h" #include "common/event.h" #include "common/thread.h" #include +#include #include #include #include +#include #include #include #include @@ -49,10 +52,23 @@ struct xcb CapturePostPointerBuffer postPointerBufferFn; LGThread * pointerThread; + // the X11 root window, which is the whole virtual desktop unsigned int width; unsigned int height, dataHeight; unsigned int pitch; + /* Multi-monitor state. displayCount is zero when capturing the root window + * as a single display, in which case the frame is sent exactly as it always + * has been and none of the atlas fields below are used. */ + bool multiMonitor; + unsigned int displayCount; + KVMFRDisplay displays[KVMFR_MAX_DISPLAYS]; + // where each display lives in the root window, which packing does not change + unsigned int srcX[KVMFR_MAX_DISPLAYS]; + unsigned int srcY[KVMFR_MAX_DISPLAYS]; + unsigned int atlasWidth, atlasHeight, atlasPitch; + unsigned int desktopWidth, desktopHeight; + int mouseX, mouseY, mouseHotX, mouseHotY; bool hasFrame; @@ -79,12 +95,134 @@ static void xcb_initOptions(void) { struct Option options[] = { + { + .module = "xcb", + .name = "multiMonitor", + .description = "Pack all monitors into a single frame", + .type = OPTION_TYPE_BOOL, + .value.x_bool = true + }, {0} }; option_register(options); } +/* Enumerate the active RandR monitors and build the packed atlas layout. + * + * On failure the caller falls back to capturing the root window as one + * display, which is always correct, just without per-monitor metadata. */ +static bool xcb_setupDisplays(void) +{ + this->displayCount = 0; + + const xcb_query_extension_reply_t * ext = + xcb_get_extension_data(this->xcb, &xcb_randr_id); + if (!ext || !ext->present) + { + DEBUG_WARN("RandR is unavailable, capturing the root window as one display"); + return false; + } + + xcb_randr_get_monitors_reply_t * reply = xcb_randr_get_monitors_reply( + this->xcb, + xcb_randr_get_monitors(this->xcb, this->xcbScreen->root, 1), + NULL); + if (!reply) + { + DEBUG_WARN("Failed to query RandR monitors, " + "capturing the root window as one display"); + return false; + } + + LGDisplayInfo info[KVMFR_MAX_DISPLAYS]; + unsigned count = 0; + + xcb_randr_monitor_info_iterator_t iter = + xcb_randr_get_monitors_monitors_iterator(reply); + for(; iter.rem; xcb_randr_monitor_info_next(&iter)) + { + const xcb_randr_monitor_info_t * mon = iter.data; + + if (mon->width == 0 || mon->height == 0) + continue; + + if (count == KVMFR_MAX_DISPLAYS) + { + DEBUG_WARN("More than %d monitors present, ignoring the rest", + KVMFR_MAX_DISPLAYS); + break; + } + + LGDisplayInfo * d = &info[count]; + memset(d, 0, sizeof(*d)); + d->id = count; + d->primary = mon->primary; + d->x = mon->x; + d->y = mon->y; + d->width = mon->width; + d->height = mon->height; + d->rotation = FRAME_ROT_0; + + xcb_get_atom_name_reply_t * name = xcb_get_atom_name_reply(this->xcb, + xcb_get_atom_name(this->xcb, mon->name), NULL); + if (name) + { + const int len = min(xcb_get_atom_name_name_length(name), + (int)sizeof(d->name) - 1); + memcpy(d->name, xcb_get_atom_name_name(name), len); + d->name[len] = '\0'; + free(name); + } + else + snprintf(d->name, sizeof(d->name), "monitor-%u", count); + + ++count; + } + free(reply); + + if (count < 2) + { + DEBUG_INFO("Only %u monitor present, using single display capture", count); + return false; + } + + /* The X11 root window is already the virtual desktop, so a monitor's + * position within it is exactly its RandR position. Record that before + * packing, which renumbers only the destination. */ + for(unsigned i = 0; i < count; ++i) + { + this->srcX[i] = info[i].x; + this->srcY[i] = info[i].y; + } + + if (!lgDisplaysPack(info, count, 1, this->displays, + &this->atlasWidth, &this->atlasHeight, + &this->desktopWidth, &this->desktopHeight)) + { + DEBUG_WARN("Failed to pack %u monitors into an atlas, " + "falling back to single display capture", count); + return false; + } + + this->displayCount = count; + this->atlasPitch = this->atlasWidth * 4; + + DEBUG_INFO("Multi-monitor : %u monitors, desktop %ux%u, atlas %ux%u", + count, this->desktopWidth, this->desktopHeight, + this->atlasWidth, this->atlasHeight); + for(unsigned i = 0; i < count; ++i) + { + const KVMFRDisplay * d = &this->displays[i]; + DEBUG_INFO(" %-16s %ux%u desktop +%d+%d -> atlas +%u+%u%s", + d->name, d->desktopWidth, d->desktopHeight, + d->desktopX, d->desktopY, d->atlasX, d->atlasY, + (d->flags & KVMFR_DISPLAY_FLAG_PRIMARY) ? " (primary)" : ""); + } + + return true; +} + static bool xcb_create( CaptureGetPointerBuffer getPointerBufferFn, CapturePostPointerBuffer postPointerBufferFn, @@ -139,6 +277,12 @@ static bool xcb_init(void * ivshmemBase, unsigned * alignSize) this->pitch = this->width * 4; DEBUG_INFO("Frame Size : %u x %u", this->width, this->height); + /* Falling back to single display capture is not an error: it is what this + * backend has always done, and it stays correct for one monitor. */ + this->multiMonitor = option_get_bool("xcb", "multiMonitor"); + if (this->multiMonitor) + xcb_setupDisplays(); + this->seg = xcb_generate_id(this->xcb); const size_t maxFrameSize = this->width * this->height * 4; this->shmID = shmget(IPC_PRIVATE, maxFrameSize, IPC_CREAT | 0777); @@ -279,6 +423,33 @@ static CaptureResult xcb_waitFrame( { lgWaitEvent(this->frameEvent, TIMEOUT_INFINITE); + if (this->displayCount) + { + /* Multi-monitor: the frame is the packed atlas, while the screen size + * describes the guest's virtual desktop so the client can lay the + * monitors out as the guest has them. */ + const unsigned int maxHeight = maxFrameSize / this->atlasPitch; + this->dataHeight = min(maxHeight, this->atlasHeight); + + frame->screenWidth = this->desktopWidth; + frame->screenHeight = this->desktopHeight; + frame->dataWidth = this->atlasWidth; + frame->dataHeight = this->dataHeight; + frame->frameWidth = this->atlasWidth; + frame->frameHeight = this->atlasHeight; + frame->truncated = maxHeight < this->atlasHeight; + frame->pitch = this->atlasPitch; + frame->stride = this->atlasWidth; + frame->format = CAPTURE_FMT_BGRA; + frame->rotation = CAPTURE_ROT_0; + + frame->displayCount = this->displayCount; + memcpy(frame->displays, this->displays, + this->displayCount * sizeof(*this->displays)); + + return CAPTURE_RESULT_OK; + } + const unsigned int maxHeight = maxFrameSize / this->pitch; this->dataHeight = min(maxHeight, this->height); @@ -294,10 +465,57 @@ static CaptureResult xcb_waitFrame( frame->stride = this->width; frame->format = CAPTURE_FMT_BGRA; frame->rotation = CAPTURE_ROT_0; + frame->displayCount = 0; return CAPTURE_RESULT_OK; } +/* Copy each monitor out of the captured root window into its slot in the + * packed atlas, writing directly into the shared memory frame so no + * intermediate buffer is needed. + * + * The write pointer is advanced once at the end rather than per row: the + * atlas is not filled in a contiguous top-to-bottom order, so a client + * waiting on the pointer must not be told a region is ready before it is. */ +static void xcb_packDisplays(FrameBuffer * frame) +{ + uint8_t * dst = framebuffer_get_data(frame); + const uint8_t * src = this->data; + + for(unsigned i = 0; i < this->displayCount; ++i) + { + const KVMFRDisplay * d = &this->displays[i]; + + // clamp to the captured root window, which a monitor should never exceed + unsigned width = d->atlasWidth; + unsigned rows = d->atlasHeight; + if (this->srcX[i] >= this->width || this->srcY[i] >= this->height) + continue; + if (this->srcX[i] + width > this->width) + width = this->width - this->srcX[i]; + if (this->srcY[i] + rows > this->height) + rows = this->height - this->srcY[i]; + + // clamp to what fits in the frame, so a small ivshmem truncates safely + if (d->atlasY >= this->dataHeight) + continue; + if (d->atlasY + rows > this->dataHeight) + rows = this->dataHeight - d->atlasY; + + const size_t bytes = (size_t)width * 4; + for(unsigned y = 0; y < rows; ++y) + memcpy( + dst + (size_t)(d->atlasY + y) * this->atlasPitch + + (size_t)d->atlasX * 4, + src + (size_t)(this->srcY[i] + y) * this->pitch + + (size_t)this->srcX[i] * 4, + bytes); + } + + framebuffer_set_write_ptr(frame, + (size_t)this->atlasPitch * this->dataHeight); +} + static CaptureResult xcb_getFrame( unsigned frameBufferIndex, FrameBuffer * frame, @@ -314,7 +532,11 @@ static CaptureResult xcb_getFrame( return CAPTURE_RESULT_ERROR; } - framebuffer_write(frame, this->data, this->pitch); + if (this->displayCount) + xcb_packDisplays(frame); + else + framebuffer_write(frame, this->data, + (size_t)this->pitch * this->dataHeight); free(img); this->hasFrame = false; diff --git a/host/src/app.c b/host/src/app.c index 2810b577..42534602 100644 --- a/host/src/app.c +++ b/host/src/app.c @@ -120,6 +120,11 @@ struct app uint32_t hdrMaxFrameAverageLightLevel; _Atomic(uint32_t) sdrWhiteLevel; + // the multi-display layout carried by the last frame, used to detect when + // the guest's display arrangement changes and clients must be told + uint32_t displayCount; + KVMFRDisplay displays[KVMFR_MAX_DISPLAYS]; + CaptureInterface * iface; bool captureStarted; @@ -305,11 +310,31 @@ static bool sendFrame(CaptureResult result, bool * restart) app.hdrMaxFrameAverageLightLevel != frame.hdrMaxFrameAverageLightLevel)); + if (frame.displayCount > KVMFR_MAX_DISPLAYS) + { + DEBUG_ERROR("Capture backend reported %u displays, the maximum is %d", + frame.displayCount, KVMFR_MAX_DISPLAYS); + return true; + } + + /* A change to the guest's display arrangement changes how the client must + * unpack the frame, so it has to invalidate the format like any other + * geometry change would. */ + const bool layoutChanged = + app.displayCount != frame.displayCount || + (frame.displayCount && memcmp(app.displays, frame.displays, + frame.displayCount * sizeof(*frame.displays)) != 0); + if (!app.frameValid || app.captureFormatVer != frame.formatVer || app.hdr != frame.hdr || app.hdrPQ != frame.hdrPQ || - metadataChanged || atomic_load(&app.sdrWhiteLevel) != sdrWhiteLevel) + metadataChanged || layoutChanged || + atomic_load(&app.sdrWhiteLevel) != sdrWhiteLevel) ++app.formatVer; + app.displayCount = frame.displayCount; + memcpy(app.displays, frame.displays, + frame.displayCount * sizeof(*frame.displays)); + app.captureFormatVer = frame.formatVer; app.hdr = frame.hdr; app.hdrPQ = frame.hdrPQ; @@ -420,6 +445,10 @@ static bool sendFrame(CaptureResult result, bool * restart) memcpy(fi->damageRects, frame.damageRects, frame.damageRectsCount * sizeof(FrameDamageRect)); + fi->displayCount = frame.displayCount; + memcpy(fi->displays, frame.displays, + frame.displayCount * sizeof(*frame.displays)); + app.frameValid = true; framebuffer_prepare(app.frameBuffer[app.captureIndex]);