This commit is contained in:
2025-12-28 13:55:10 -08:00
commit 9b4219aa67
131 changed files with 32853 additions and 0 deletions

504
kms/client/kms_client.c Normal file
View File

@ -0,0 +1,504 @@
#include "kms_client.h"
#include "../../include/utils.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <signal.h>
#include <stdbool.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/wait.h>
#include <poll.h>
#include <sys/stat.h>
#ifdef __linux__
#include <sys/capability.h>
#endif
#ifdef __FreeBSD__
#include <sys/sysctl.h>
#endif
#define GSR_SOCKET_PAIR_LOCAL 0
#define GSR_SOCKET_PAIR_REMOTE 1
static void cleanup_socket(gsr_kms_client *self, bool kill_server);
static int gsr_kms_client_replace_connection(gsr_kms_client *self);
static void close_fds(gsr_kms_response *response) {
for(int i = 0; i < response->num_items; ++i) {
for(int j = 0; j < response->items[i].num_dma_bufs; ++j) {
gsr_kms_response_dma_buf *dma_buf = &response->items[i].dma_buf[j];
if(dma_buf->fd > 0) {
close(dma_buf->fd);
dma_buf->fd = -1;
}
}
response->items[i].num_dma_bufs = 0;
}
response->num_items = 0;
}
static int send_msg_to_server(int server_fd, gsr_kms_request *request) {
struct iovec iov;
iov.iov_base = request;
iov.iov_len = sizeof(*request);
struct msghdr response_message = {0};
response_message.msg_iov = &iov;
response_message.msg_iovlen = 1;
char cmsgbuf[CMSG_SPACE(sizeof(int) * 1)];
memset(cmsgbuf, 0, sizeof(cmsgbuf));
if(request->new_connection_fd > 0) {
response_message.msg_control = cmsgbuf;
response_message.msg_controllen = sizeof(cmsgbuf);
struct cmsghdr *cmsg = CMSG_FIRSTHDR(&response_message);
cmsg->cmsg_level = SOL_SOCKET;
cmsg->cmsg_type = SCM_RIGHTS;
cmsg->cmsg_len = CMSG_LEN(sizeof(int) * 1);
int *fds = (int*)CMSG_DATA(cmsg);
fds[0] = request->new_connection_fd;
response_message.msg_controllen = cmsg->cmsg_len;
}
return sendmsg(server_fd, &response_message, 0);
}
static int recv_msg_from_server(int server_pid, int server_fd, gsr_kms_response *response) {
struct iovec iov;
iov.iov_base = response;
iov.iov_len = sizeof(*response);
struct msghdr response_message = {0};
response_message.msg_iov = &iov;
response_message.msg_iovlen = 1;
char cmsgbuf[CMSG_SPACE(sizeof(int) * GSR_KMS_MAX_ITEMS * GSR_KMS_MAX_DMA_BUFS)];
memset(cmsgbuf, 0, sizeof(cmsgbuf));
response_message.msg_control = cmsgbuf;
response_message.msg_controllen = sizeof(cmsgbuf);
int res = 0;
for(;;) {
res = recvmsg(server_fd, &response_message, MSG_DONTWAIT);
if(res <= 0 && (errno == EAGAIN || errno == EWOULDBLOCK)) {
// If we are replacing the connection and closing the application at the same time
// then recvmsg can get stuck (because the server died), so we prevent that by doing
// non-blocking recvmsg and checking if the server died
int status = 0;
int wait_result = waitpid(server_pid, &status, WNOHANG);
if(wait_result != 0) {
res = -1;
break;
}
usleep(1000);
} else {
break;
}
}
if(res > 0 && response->num_items > 0) {
struct cmsghdr *cmsg = CMSG_FIRSTHDR(&response_message);
if(cmsg) {
int *fds = (int*)CMSG_DATA(cmsg);
int fd_index = 0;
for(int i = 0; i < response->num_items; ++i) {
for(int j = 0; j < response->items[i].num_dma_bufs; ++j) {
gsr_kms_response_dma_buf *dma_buf = &response->items[i].dma_buf[j];
dma_buf->fd = fds[fd_index++];
}
}
} else {
close_fds(response);
}
}
return res;
}
/* We have to use $HOME because in flatpak there is no simple path that is accessible, read and write, that multiple flatpak instances can access */
static bool create_socket_path(char *output_path, size_t output_path_size) {
const bool inside_flatpak = getenv("FLATPAK_ID") != NULL;
const char *home = getenv("HOME");
// Portable home with AppImage can cause the socket path to be longer than 108 characters (unix domain socket path max length).
// Using gsr-kms-socket in $HOME is only needed in flatpak, so use /tmp everywhere else instead.
if(!home || !inside_flatpak)
home = "/tmp";
char random_characters[11];
random_characters[10] = '\0';
if(!generate_random_characters_standard_alphabet(random_characters, 10))
return false;
snprintf(output_path, output_path_size, "%s/.gsr-kms-socket-%s", home, random_characters);
return true;
}
#ifdef __linux__
static bool readlink_realpath(const char *filepath, char *buffer) {
char symlinked_path[PATH_MAX];
ssize_t bytes_written = readlink(filepath, symlinked_path, sizeof(symlinked_path) - 1);
if(bytes_written == -1 && errno == EINVAL) {
/* Not a symlink */
snprintf(symlinked_path, sizeof(symlinked_path), "%s", filepath);
} else if(bytes_written == -1) {
return false;
} else {
symlinked_path[bytes_written] = '\0';
}
if(!realpath(symlinked_path, buffer))
return false;
return true;
}
#endif
static bool strcat_safe(char *str, int size, const char *str_to_add) {
const int str_len = strlen(str);
const int str_to_add_len = strlen(str_to_add);
if(str_len + str_to_add_len + 1 >= size)
return false;
memcpy(str + str_len, str_to_add, str_to_add_len);
str[str_len + str_to_add_len] = '\0';
return true;
}
static void file_get_directory(char *filepath) {
char *end = strrchr(filepath, '/');
if(end == NULL)
filepath[0] = '\0';
else
*end = '\0';
}
static bool find_program_in_path(const char *program_name, char *filepath, int filepath_len) {
const char *path = getenv("PATH");
if(!path)
return false;
int program_name_len = strlen(program_name);
const char *end = path + strlen(path);
while(path != end) {
const char *part_end = strchr(path, ':');
const char *next = part_end;
if(part_end) {
next = part_end + 1;
} else {
part_end = end;
next = end;
}
int len = part_end - path;
if(len + 1 + program_name_len < filepath_len) {
memcpy(filepath, path, len);
filepath[len] = '/';
memcpy(filepath + len + 1, program_name, program_name_len);
filepath[len + 1 + program_name_len] = '\0';
if(access(filepath, F_OK) == 0)
return true;
}
path = next;
}
return false;
}
int gsr_kms_client_init(gsr_kms_client *self, const char *card_path) {
int result = -1;
self->kms_server_pid = -1;
self->initial_socket_fd = -1;
self->initial_client_fd = -1;
self->initial_socket_path[0] = '\0';
self->socket_pair[0] = -1;
self->socket_pair[1] = -1;
struct sockaddr_un local_addr = {0};
struct sockaddr_un remote_addr = {0};
if(!create_socket_path(self->initial_socket_path, sizeof(self->initial_socket_path))) {
fprintf(stderr, "gsr error: gsr_kms_client_init: failed to create path to kms socket\n");
return -1;
}
char server_filepath[PATH_MAX];
#ifdef __linux__
if(!readlink_realpath("/proc/self/exe", server_filepath)) {
fprintf(stderr, "gsr error: gsr_kms_client_init: failed to resolve /proc/self/exe\n");
return -1;
}
#elif defined(__FreeBSD__)
int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, getpid() };
size_t size = PATH_MAX;
if (sysctl(mib, 4, server_filepath, &size, NULL, 0) != 0) {
fprintf(stderr, "gsr error: gsr_kms_client_init: failed to resolve pathname using sysctl\n");
return -1;
}
#else
#error "Implement it by yourself"
#endif
file_get_directory(server_filepath);
if(!strcat_safe(server_filepath, sizeof(server_filepath), "/gsr-kms-server")) {
fprintf(stderr, "gsr error: gsr_kms_client_init: gsr-kms-server path too long\n");
return -1;
}
if(access(server_filepath, F_OK) != 0) {
fprintf(stderr, "gsr info: gsr_kms_client_init: gsr-kms-server is not installed in the same directory as gpu-screen-recorder (%s not found), looking for gsr-kms-server in PATH instead\n", server_filepath);
if(!find_program_in_path("gsr-kms-server", server_filepath, sizeof(server_filepath)) || access(server_filepath, F_OK) != 0) {
fprintf(stderr, "gsr error: gsr_kms_client_init: gsr-kms-server was not found in PATH. Please install gpu-screen-recorder properly\n");
return -1;
}
}
fprintf(stderr, "gsr info: gsr_kms_client_init: setting up connection to %s\n", server_filepath);
const bool inside_flatpak = getenv("FLATPAK_ID") != NULL;
const char *home = getenv("HOME");
if(!home)
home = "/tmp";
bool has_perm = 0;
if(geteuid() == 0) {
has_perm = true;
} else {
#ifdef __linux__
cap_t kms_server_cap = cap_get_file(server_filepath);
if(kms_server_cap) {
cap_flag_value_t res = CAP_CLEAR;
cap_get_flag(kms_server_cap, CAP_SYS_ADMIN, CAP_PERMITTED, &res);
if(res == CAP_SET) {
//fprintf(stderr, "has permission!\n");
has_perm = true;
} else {
//fprintf(stderr, "No permission:(\n");
}
cap_free(kms_server_cap);
} else if(!inside_flatpak) {
if(errno == ENODATA)
fprintf(stderr, "gsr info: gsr_kms_client_init: gsr-kms-server is missing sys_admin cap and will require root authentication. To bypass this automatically, run: sudo setcap cap_sys_admin+ep '%s'\n", server_filepath);
else
fprintf(stderr, "gsr info: gsr_kms_client_init: failed to get cap\n");
}
#else
fprintf(stderr, "gsr info: gsr_kms_client_init: platform doesn't support cap\n");
#endif
}
if(socketpair(AF_UNIX, SOCK_STREAM, 0, self->socket_pair) == -1) {
fprintf(stderr, "gsr error: gsr_kms_client_init: socketpair failed, error: %s\n", strerror(errno));
goto err;
}
self->initial_socket_fd = socket(AF_UNIX, SOCK_STREAM, 0);
if(self->initial_socket_fd == -1) {
fprintf(stderr, "gsr error: gsr_kms_client_init: socket failed, error: %s\n", strerror(errno));
goto err;
}
local_addr.sun_family = AF_UNIX;
snprintf(local_addr.sun_path, sizeof(local_addr.sun_path), "%s", (const char*)self->initial_socket_path);
const mode_t prev_mask = umask(0000);
const int bind_res = bind(self->initial_socket_fd, (struct sockaddr*)&local_addr, sizeof(local_addr.sun_family) + strlen(local_addr.sun_path));
umask(prev_mask);
if(bind_res == -1) {
fprintf(stderr, "gsr error: gsr_kms_client_init: failed to bind socket, error: %s\n", strerror(errno));
goto err;
}
if(listen(self->initial_socket_fd, 1) == -1) {
fprintf(stderr, "gsr error: gsr_kms_client_init: failed to listen on socket, error: %s\n", strerror(errno));
goto err;
}
pid_t pid = fork();
if(pid == -1) {
fprintf(stderr, "gsr error: gsr_kms_client_init: fork failed, error: %s\n", strerror(errno));
goto err;
} else if(pid == 0) { /* child */
if(inside_flatpak) {
const char *args[] = { "flatpak-spawn", "--host", "/var/lib/flatpak/app/com.dec05eba.gpu_screen_recorder/current/active/files/bin/kms-server-proxy", self->initial_socket_path, card_path, home, NULL };
execvp(args[0], (char *const*)args);
} else if(has_perm) {
const char *args[] = { server_filepath, self->initial_socket_path, card_path, NULL };
execvp(args[0], (char *const*)args);
} else {
const char *args[] = { "pkexec", server_filepath, self->initial_socket_path, card_path, NULL };
execvp(args[0], (char *const*)args);
}
fprintf(stderr, "gsr error: gsr_kms_client_init: failed to launch \"gsr-kms-server\", error: %s\n", strerror(errno));
_exit(127);
} else { /* parent */
self->kms_server_pid = pid;
}
// We need this dumb-shit retardation with unix domain socket and then replace it with socketpair because
// pkexec doesn't work with socketpair................
fprintf(stderr, "gsr info: gsr_kms_client_init: waiting for server to connect\n");
struct pollfd poll_fd = {
.fd = self->initial_socket_fd,
.events = POLLIN,
.revents = 0
};
for(;;) {
int poll_res = poll(&poll_fd, 1, 100);
if(poll_res > 0 && (poll_fd.revents & POLLIN)) {
socklen_t sock_len = 0;
self->initial_client_fd = accept(self->initial_socket_fd, (struct sockaddr*)&remote_addr, &sock_len);
if(self->initial_client_fd == -1) {
fprintf(stderr, "gsr error: gsr_kms_client_init: accept failed on socket, error: %s\n", strerror(errno));
goto err;
}
break;
} else {
int status = 0;
int wait_result = waitpid(self->kms_server_pid, &status, WNOHANG);
if(wait_result != 0) {
int exit_code = -1;
if(WIFEXITED(status))
exit_code = WEXITSTATUS(status);
fprintf(stderr, "gsr error: gsr_kms_client_init: kms server died or never started, exit code: %d\n", exit_code);
self->kms_server_pid = -1;
if(exit_code != 0)
result = exit_code;
goto err;
}
}
}
fprintf(stderr, "gsr info: gsr_kms_client_init: server connected\n");
fprintf(stderr, "gsr info: replacing file-backed unix domain socket with socketpair\n");
if(gsr_kms_client_replace_connection(self) != 0)
goto err;
cleanup_socket(self, false);
fprintf(stderr, "gsr info: using socketpair\n");
return 0;
err:
gsr_kms_client_deinit(self);
return result;
}
void cleanup_socket(gsr_kms_client *self, bool kill_server) {
if(self->initial_client_fd > 0) {
close(self->initial_client_fd);
self->initial_client_fd = -1;
}
if(self->initial_socket_fd > 0) {
close(self->initial_socket_fd);
self->initial_socket_fd = -1;
}
if(kill_server) {
for(int i = 0; i < 2; ++i) {
if(self->socket_pair[i] > 0) {
close(self->socket_pair[i]);
self->socket_pair[i] = -1;
}
}
}
if(kill_server && self->kms_server_pid > 0) {
kill(self->kms_server_pid, SIGKILL);
// TODO:
//int status;
//waitpid(self->kms_server_pid, &status, 0);
self->kms_server_pid = -1;
}
if(self->initial_socket_path[0] != '\0') {
remove(self->initial_socket_path);
self->initial_socket_path[0] = '\0';
}
}
void gsr_kms_client_deinit(gsr_kms_client *self) {
cleanup_socket(self, true);
}
int gsr_kms_client_replace_connection(gsr_kms_client *self) {
gsr_kms_response response;
response.version = 0;
response.result = KMS_RESULT_FAILED_TO_SEND;
response.err_msg[0] = '\0';
gsr_kms_request request;
request.version = GSR_KMS_PROTOCOL_VERSION;
request.type = KMS_REQUEST_TYPE_REPLACE_CONNECTION;
request.new_connection_fd = self->socket_pair[GSR_SOCKET_PAIR_REMOTE];
if(send_msg_to_server(self->initial_client_fd, &request) == -1) {
fprintf(stderr, "gsr error: gsr_kms_client_replace_connection: failed to send request message to server\n");
return -1;
}
const int recv_res = recv_msg_from_server(self->kms_server_pid, self->socket_pair[GSR_SOCKET_PAIR_LOCAL], &response);
if(recv_res == 0) {
fprintf(stderr, "gsr warning: gsr_kms_client_replace_connection: kms server shut down\n");
return -1;
} else if(recv_res == -1) {
fprintf(stderr, "gsr error: gsr_kms_client_replace_connection: failed to receive response\n");
return -1;
}
if(response.version != GSR_KMS_PROTOCOL_VERSION) {
fprintf(stderr, "gsr error: gsr_kms_client_replace_connection: expected gsr-kms-server protocol version to be %u, but it's %u. please reinstall gpu screen recorder\n", GSR_KMS_PROTOCOL_VERSION, response.version);
/*close_fds(response);*/
return -1;
}
return 0;
}
int gsr_kms_client_get_kms(gsr_kms_client *self, gsr_kms_response *response) {
response->version = 0;
response->result = KMS_RESULT_FAILED_TO_SEND;
response->err_msg[0] = '\0';
response->num_items = 0;
gsr_kms_request request;
request.version = GSR_KMS_PROTOCOL_VERSION;
request.type = KMS_REQUEST_TYPE_GET_KMS;
request.new_connection_fd = 0;
if(send_msg_to_server(self->socket_pair[GSR_SOCKET_PAIR_LOCAL], &request) == -1) {
fprintf(stderr, "gsr error: gsr_kms_client_get_kms: failed to send request message to server\n");
strcpy(response->err_msg, "failed to send");
return -1;
}
const int recv_res = recv_msg_from_server(self->kms_server_pid, self->socket_pair[GSR_SOCKET_PAIR_LOCAL], response);
if(recv_res == 0) {
fprintf(stderr, "gsr warning: gsr_kms_client_get_kms: kms server shut down\n");
strcpy(response->err_msg, "failed to receive");
return -1;
} else if(recv_res == -1) {
fprintf(stderr, "gsr error: gsr_kms_client_get_kms: failed to receive response\n");
strcpy(response->err_msg, "failed to receive");
return -1;
}
if(response->version != GSR_KMS_PROTOCOL_VERSION) {
fprintf(stderr, "gsr error: gsr_kms_client_get_kms: expected gsr-kms-server protocol version to be %u, but it's %u. please reinstall gpu screen recorder\n", GSR_KMS_PROTOCOL_VERSION, response->version);
/*close_fds(response);*/
strcpy(response->err_msg, "mismatching protocol version");
return -1;
}
return 0;
}

24
kms/client/kms_client.h Normal file
View File

@ -0,0 +1,24 @@
#ifndef GSR_KMS_CLIENT_H
#define GSR_KMS_CLIENT_H
#include "../kms_shared.h"
#include <sys/types.h>
#include <limits.h>
typedef struct gsr_kms_client gsr_kms_client;
struct gsr_kms_client {
pid_t kms_server_pid;
int initial_socket_fd;
int initial_client_fd;
char initial_socket_path[PATH_MAX];
int socket_pair[2];
};
/* |card_path| should be a path to card, for example /dev/dri/card0 */
int gsr_kms_client_init(gsr_kms_client *self, const char *card_path);
void gsr_kms_client_deinit(gsr_kms_client *self);
int gsr_kms_client_get_kms(gsr_kms_client *self, gsr_kms_response *response);
#endif /* #define GSR_KMS_CLIENT_H */

75
kms/kms_shared.h Normal file
View File

@ -0,0 +1,75 @@
#ifndef GSR_KMS_SHARED_H
#define GSR_KMS_SHARED_H
#include <stdint.h>
#include <stdbool.h>
#include <drm_mode.h>
#define GSR_KMS_PROTOCOL_VERSION 5
#define GSR_KMS_MAX_ITEMS 8
#define GSR_KMS_MAX_DMA_BUFS 4
typedef struct gsr_kms_response_dma_buf gsr_kms_response_dma_buf;
typedef struct gsr_kms_response_item gsr_kms_response_item;
typedef struct gsr_kms_response gsr_kms_response;
typedef enum {
KMS_REQUEST_TYPE_REPLACE_CONNECTION,
KMS_REQUEST_TYPE_GET_KMS
} gsr_kms_request_type;
typedef enum {
KMS_RESULT_OK,
KMS_RESULT_INVALID_REQUEST,
KMS_RESULT_FAILED_TO_GET_PLANE,
KMS_RESULT_FAILED_TO_GET_PLANES,
KMS_RESULT_FAILED_TO_SEND
} gsr_kms_result;
typedef struct {
uint32_t version; /* GSR_KMS_PROTOCOL_VERSION */
int type; /* gsr_kms_request_type */
int new_connection_fd;
} gsr_kms_request;
struct gsr_kms_response_dma_buf {
int fd;
uint32_t pitch;
uint32_t offset;
};
typedef enum {
KMS_ROT_0,
KMS_ROT_90,
KMS_ROT_180,
KMS_ROT_270
} gsr_kms_rotation;
struct gsr_kms_response_item {
gsr_kms_response_dma_buf dma_buf[GSR_KMS_MAX_DMA_BUFS];
int num_dma_bufs;
uint32_t width;
uint32_t height;
uint32_t pixel_format;
uint64_t modifier;
uint32_t connector_id; /* 0 if unknown */
bool is_cursor;
bool has_hdr_metadata;
gsr_kms_rotation rotation;
int x;
int y;
int src_w;
int src_h;
struct hdr_output_metadata hdr_metadata;
};
struct gsr_kms_response {
uint32_t version; /* GSR_KMS_PROTOCOL_VERSION */
int result; /* gsr_kms_result */
char err_msg[128];
gsr_kms_response_item items[GSR_KMS_MAX_ITEMS];
int num_items;
};
#endif /* #define GSR_KMS_SHARED_H */

1
kms/server/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
sibs-build/

626
kms/server/kms_server.c Normal file
View File

@ -0,0 +1,626 @@
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include "../kms_shared.h"
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <locale.h>
#include <unistd.h>
#include <limits.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <time.h>
#include <xf86drm.h>
#include <xf86drmMode.h>
#include <drm_mode.h>
#include <drm_fourcc.h>
#define MAX_CONNECTORS 32
typedef struct {
int drmfd;
} gsr_drm;
typedef struct {
uint32_t connector_id;
uint64_t crtc_id;
uint64_t hdr_metadata_blob_id;
} connector_crtc_pair;
typedef struct {
connector_crtc_pair maps[MAX_CONNECTORS];
int num_maps;
} connector_to_crtc_map;
static int max_int(int a, int b) {
return a > b ? a : b;
}
static int count_num_fds(const gsr_kms_response *response) {
int num_fds = 0;
for(int i = 0; i < response->num_items; ++i) {
num_fds += response->items[i].num_dma_bufs;
}
return num_fds;
}
static int send_msg_to_client(int client_fd, gsr_kms_response *response) {
struct iovec iov;
iov.iov_base = response;
iov.iov_len = sizeof(*response);
struct msghdr response_message = {0};
response_message.msg_iov = &iov;
response_message.msg_iovlen = 1;
const int num_fds = count_num_fds(response);
char cmsgbuf[CMSG_SPACE(sizeof(int) * max_int(1, num_fds))];
memset(cmsgbuf, 0, sizeof(cmsgbuf));
if(num_fds > 0) {
response_message.msg_control = cmsgbuf;
response_message.msg_controllen = sizeof(cmsgbuf);
struct cmsghdr *cmsg = CMSG_FIRSTHDR(&response_message);
cmsg->cmsg_level = SOL_SOCKET;
cmsg->cmsg_type = SCM_RIGHTS;
cmsg->cmsg_len = CMSG_LEN(sizeof(int) * num_fds);
int *fds = (int*)CMSG_DATA(cmsg);
int fd_index = 0;
for(int i = 0; i < response->num_items; ++i) {
for(int j = 0; j < response->items[i].num_dma_bufs; ++j) {
fds[fd_index++] = response->items[i].dma_buf[j].fd;
}
}
response_message.msg_controllen = cmsg->cmsg_len;
}
return sendmsg(client_fd, &response_message, 0);
}
static int recv_msg_from_client(int client_fd, gsr_kms_request *request) {
struct iovec iov;
iov.iov_base = request;
iov.iov_len = sizeof(*request);
struct msghdr response_message = {0};
response_message.msg_iov = &iov;
response_message.msg_iovlen = 1;
char cmsgbuf[CMSG_SPACE(sizeof(int) * 1)];
memset(cmsgbuf, 0, sizeof(cmsgbuf));
response_message.msg_control = cmsgbuf;
response_message.msg_controllen = sizeof(cmsgbuf);
int res = recvmsg(client_fd, &response_message, MSG_WAITALL);
if(res <= 0)
return res;
if(request->new_connection_fd > 0) {
struct cmsghdr *cmsg = CMSG_FIRSTHDR(&response_message);
if(cmsg) {
int *fds = (int*)CMSG_DATA(cmsg);
request->new_connection_fd = fds[0];
} else {
if(request->new_connection_fd > 0) {
close(request->new_connection_fd);
request->new_connection_fd = 0;
}
}
}
return res;
}
static bool connector_get_property_by_name(int drmfd, drmModeConnectorPtr props, const char *name, uint64_t *result) {
for(int i = 0; i < props->count_props; ++i) {
drmModePropertyPtr prop = drmModeGetProperty(drmfd, props->props[i]);
if(prop) {
if(strcmp(name, prop->name) == 0) {
*result = props->prop_values[i];
drmModeFreeProperty(prop);
return true;
}
drmModeFreeProperty(prop);
}
}
return false;
}
typedef enum {
PLANE_PROPERTY_X = 1 << 0,
PLANE_PROPERTY_Y = 1 << 1,
PLANE_PROPERTY_SRC_X = 1 << 2,
PLANE_PROPERTY_SRC_Y = 1 << 3,
PLANE_PROPERTY_SRC_W = 1 << 4,
PLANE_PROPERTY_SRC_H = 1 << 5,
PLANE_PROPERTY_IS_CURSOR = 1 << 6,
PLANE_PROPERTY_IS_PRIMARY = 1 << 7,
PLANE_PROPERTY_ROTATION = 1 << 8,
} plane_property_mask;
/* Returns plane_property_mask */
static uint32_t plane_get_properties(int drmfd, uint32_t plane_id, int *x, int *y, int *src_x, int *src_y, int *src_w, int *src_h, gsr_kms_rotation *rotation) {
*x = 0;
*y = 0;
*src_x = 0;
*src_y = 0;
*src_w = 0;
*src_h = 0;
*rotation = KMS_ROT_0;
plane_property_mask property_mask = 0;
drmModeObjectPropertiesPtr props = drmModeObjectGetProperties(drmfd, plane_id, DRM_MODE_OBJECT_PLANE);
if(!props)
return property_mask;
// TODO: Dont do this every frame
for(uint32_t i = 0; i < props->count_props; ++i) {
drmModePropertyPtr prop = drmModeGetProperty(drmfd, props->props[i]);
if(!prop)
continue;
// SRC_* values are fixed 16.16 points
const uint32_t type = prop->flags & (DRM_MODE_PROP_LEGACY_TYPE | DRM_MODE_PROP_EXTENDED_TYPE);
if((type & DRM_MODE_PROP_SIGNED_RANGE) && strcmp(prop->name, "CRTC_X") == 0) {
*x = (int)props->prop_values[i];
property_mask |= PLANE_PROPERTY_X;
} else if((type & DRM_MODE_PROP_SIGNED_RANGE) && strcmp(prop->name, "CRTC_Y") == 0) {
*y = (int)props->prop_values[i];
property_mask |= PLANE_PROPERTY_Y;
} else if((type & DRM_MODE_PROP_RANGE) && strcmp(prop->name, "SRC_X") == 0) {
*src_x = (int)(props->prop_values[i] >> 16);
property_mask |= PLANE_PROPERTY_SRC_X;
} else if((type & DRM_MODE_PROP_RANGE) && strcmp(prop->name, "SRC_Y") == 0) {
*src_y = (int)(props->prop_values[i] >> 16);
property_mask |= PLANE_PROPERTY_SRC_Y;
} else if((type & DRM_MODE_PROP_RANGE) && strcmp(prop->name, "SRC_W") == 0) {
*src_w = (int)(props->prop_values[i] >> 16);
property_mask |= PLANE_PROPERTY_SRC_W;
} else if((type & DRM_MODE_PROP_RANGE) && strcmp(prop->name, "SRC_H") == 0) {
*src_h = (int)(props->prop_values[i] >> 16);
property_mask |= PLANE_PROPERTY_SRC_H;
} else if((type & DRM_MODE_PROP_ENUM) && strcmp(prop->name, "type") == 0) {
const uint64_t current_enum_value = props->prop_values[i];
for(int j = 0; j < prop->count_enums; ++j) {
if(prop->enums[j].value == current_enum_value && strcmp(prop->enums[j].name, "Primary") == 0) {
property_mask |= PLANE_PROPERTY_IS_PRIMARY;
break;
} else if(prop->enums[j].value == current_enum_value && strcmp(prop->enums[j].name, "Cursor") == 0) {
property_mask |= PLANE_PROPERTY_IS_CURSOR;
break;
}
}
} else if((type & DRM_MODE_PROP_BITMASK) && strcmp(prop->name, "rotation") == 0) {
const uint64_t rotation_bitmask = props->prop_values[i];
*rotation = KMS_ROT_0;
if(rotation_bitmask & 2)
*rotation = (*rotation + KMS_ROT_90) % 4;
if(rotation_bitmask & 4)
*rotation = (*rotation + KMS_ROT_180) % 4;
if(rotation_bitmask & 8)
*rotation = (*rotation + KMS_ROT_270) % 4;
}
drmModeFreeProperty(prop);
}
drmModeFreeObjectProperties(props);
return property_mask;
}
/* Returns NULL if not found */
static const connector_crtc_pair* get_connector_pair_by_crtc_id(const connector_to_crtc_map *c2crtc_map, uint32_t crtc_id) {
for(int i = 0; i < c2crtc_map->num_maps; ++i) {
if(c2crtc_map->maps[i].crtc_id == crtc_id)
return &c2crtc_map->maps[i];
}
return NULL;
}
static void map_crtc_to_connector_ids(gsr_drm *drm, connector_to_crtc_map *c2crtc_map) {
c2crtc_map->num_maps = 0;
drmModeResPtr resources = drmModeGetResources(drm->drmfd);
if(!resources)
return;
for(int i = 0; i < resources->count_connectors && c2crtc_map->num_maps < MAX_CONNECTORS; ++i) {
drmModeConnectorPtr connector = drmModeGetConnectorCurrent(drm->drmfd, resources->connectors[i]);
if(!connector)
continue;
uint64_t crtc_id = 0;
connector_get_property_by_name(drm->drmfd, connector, "CRTC_ID", &crtc_id);
uint64_t hdr_output_metadata_blob_id = 0;
connector_get_property_by_name(drm->drmfd, connector, "HDR_OUTPUT_METADATA", &hdr_output_metadata_blob_id);
c2crtc_map->maps[c2crtc_map->num_maps].connector_id = connector->connector_id;
c2crtc_map->maps[c2crtc_map->num_maps].crtc_id = crtc_id;
c2crtc_map->maps[c2crtc_map->num_maps].hdr_metadata_blob_id = hdr_output_metadata_blob_id;
++c2crtc_map->num_maps;
drmModeFreeConnector(connector);
}
drmModeFreeResources(resources);
}
static void drm_mode_cleanup_handles(int drmfd, drmModeFB2Ptr drmfb) {
for(int i = 0; i < 4; ++i) {
if(!drmfb->handles[i])
continue;
bool already_closed = false;
for(int j = 0; j < i; ++j) {
if(drmfb->handles[i] == drmfb->handles[j]) {
already_closed = true;
break;
}
}
if(already_closed)
continue;
drmCloseBufferHandle(drmfd, drmfb->handles[i]);
}
}
static bool get_hdr_metadata(int drm_fd, uint64_t hdr_metadata_blob_id, struct hdr_output_metadata *hdr_metadata) {
drmModePropertyBlobPtr hdr_metadata_blob = drmModeGetPropertyBlob(drm_fd, hdr_metadata_blob_id);
if(!hdr_metadata_blob)
return false;
if(hdr_metadata_blob->length >= sizeof(struct hdr_output_metadata))
*hdr_metadata = *(struct hdr_output_metadata*)hdr_metadata_blob->data;
drmModeFreePropertyBlob(hdr_metadata_blob);
return true;
}
/* Returns the number of drm handles that we managed to get */
static int drm_prime_handles_to_fds(gsr_drm *drm, drmModeFB2Ptr drmfb, int *fb_fds) {
for(int i = 0; i < GSR_KMS_MAX_DMA_BUFS; ++i) {
if(!drmfb->handles[i])
return i;
const int ret = drmPrimeHandleToFD(drm->drmfd, drmfb->handles[i], O_RDONLY, &fb_fds[i]);
if(ret != 0 || fb_fds[i] == -1)
return i;
}
return GSR_KMS_MAX_DMA_BUFS;
}
static int kms_get_fb(gsr_drm *drm, gsr_kms_response *response) {
int result = -1;
response->result = KMS_RESULT_OK;
response->err_msg[0] = '\0';
response->num_items = 0;
connector_to_crtc_map c2crtc_map;
c2crtc_map.num_maps = 0;
map_crtc_to_connector_ids(drm, &c2crtc_map);
drmModePlaneResPtr planes = drmModeGetPlaneResources(drm->drmfd);
if(!planes) {
fprintf(stderr, "kms server error: failed to get plane resources, error: %s\n", strerror(errno));
goto done;
}
for(uint32_t i = 0; i < planes->count_planes && response->num_items < GSR_KMS_MAX_ITEMS; ++i) {
drmModePlanePtr plane = NULL;
drmModeFB2Ptr drmfb = NULL;
plane = drmModeGetPlane(drm->drmfd, planes->planes[i]);
if(!plane) {
response->result = KMS_RESULT_FAILED_TO_GET_PLANE;
snprintf(response->err_msg, sizeof(response->err_msg), "failed to get drm plane with id %u, error: %s\n", planes->planes[i], strerror(errno));
fprintf(stderr, "kms server error: %s\n", response->err_msg);
goto next;
}
if(!plane->fb_id)
goto next;
drmfb = drmModeGetFB2(drm->drmfd, plane->fb_id);
if(!drmfb) {
// Commented out for now because we get here if the cursor is moved to another monitor and we dont care about the cursor
//response->result = KMS_RESULT_FAILED_TO_GET_PLANE;
//snprintf(response->err_msg, sizeof(response->err_msg), "drmModeGetFB2 failed, error: %s", strerror(errno));
//fprintf(stderr, "kms server error: %s\n", response->err_msg);
goto next;
}
if(!drmfb->handles[0]) {
response->result = KMS_RESULT_FAILED_TO_GET_PLANE;
snprintf(response->err_msg, sizeof(response->err_msg), "drmfb handle is NULL");
fprintf(stderr, "kms server error: %s\n", response->err_msg);
goto cleanup_handles;
}
// TODO: Check if dimensions have changed by comparing width and height to previous time this was called.
// TODO: Support other plane formats than rgb (with multiple planes, such as direct YUV420 on wayland).
int x = 0, y = 0, src_x = 0, src_y = 0, src_w = 0, src_h = 0;
gsr_kms_rotation rotation = KMS_ROT_0;
const uint32_t property_mask = plane_get_properties(drm->drmfd, plane->plane_id, &x, &y, &src_x, &src_y, &src_w, &src_h, &rotation);
if(!(property_mask & PLANE_PROPERTY_IS_PRIMARY) && !(property_mask & PLANE_PROPERTY_IS_CURSOR))
continue;
int fb_fds[GSR_KMS_MAX_DMA_BUFS];
const int num_fb_fds = drm_prime_handles_to_fds(drm, drmfb, fb_fds);
if(num_fb_fds == 0) {
response->result = KMS_RESULT_FAILED_TO_GET_PLANE;
snprintf(response->err_msg, sizeof(response->err_msg), "failed to get fd from drm handle, error: %s", strerror(errno));
fprintf(stderr, "kms server error: %s\n", response->err_msg);
goto cleanup_handles;
}
const int item_index = response->num_items;
const connector_crtc_pair *crtc_pair = get_connector_pair_by_crtc_id(&c2crtc_map, plane->crtc_id);
if(crtc_pair && crtc_pair->hdr_metadata_blob_id) {
response->items[item_index].has_hdr_metadata = get_hdr_metadata(drm->drmfd, crtc_pair->hdr_metadata_blob_id, &response->items[item_index].hdr_metadata);
} else {
response->items[item_index].has_hdr_metadata = false;
}
for(int j = 0; j < num_fb_fds; ++j) {
response->items[item_index].dma_buf[j].fd = fb_fds[j];
response->items[item_index].dma_buf[j].pitch = drmfb->pitches[j];
response->items[item_index].dma_buf[j].offset = drmfb->offsets[j];
}
response->items[item_index].num_dma_bufs = num_fb_fds;
response->items[item_index].width = drmfb->width;
response->items[item_index].height = drmfb->height;
response->items[item_index].pixel_format = drmfb->pixel_format;
response->items[item_index].modifier = drmfb->flags & DRM_MODE_FB_MODIFIERS ? drmfb->modifier : DRM_FORMAT_MOD_INVALID;
response->items[item_index].connector_id = crtc_pair ? crtc_pair->connector_id : 0;
response->items[item_index].rotation = rotation;
response->items[item_index].is_cursor = property_mask & PLANE_PROPERTY_IS_CURSOR;
if(property_mask & PLANE_PROPERTY_IS_CURSOR) {
response->items[item_index].x = x;
response->items[item_index].y = y;
response->items[item_index].src_w = 0;
response->items[item_index].src_h = 0;
} else {
response->items[item_index].x = src_x;
response->items[item_index].y = src_y;
response->items[item_index].src_w = src_w;
response->items[item_index].src_h = src_h;
}
++response->num_items;
cleanup_handles:
drm_mode_cleanup_handles(drm->drmfd, drmfb);
next:
if(drmfb)
drmModeFreeFB2(drmfb);
if(plane)
drmModeFreePlane(plane);
}
done:
if(planes)
drmModeFreePlaneResources(planes);
if(response->num_items > 0)
response->result = KMS_RESULT_OK;
if(response->result == KMS_RESULT_OK) {
result = 0;
} else {
for(int i = 0; i < response->num_items; ++i) {
for(int j = 0; j < response->items[i].num_dma_bufs; ++j) {
gsr_kms_response_dma_buf *dma_buf = &response->items[i].dma_buf[j];
if(dma_buf->fd > 0) {
close(dma_buf->fd);
dma_buf->fd = -1;
}
}
response->items[i].num_dma_bufs = 0;
}
response->num_items = 0;
}
return result;
}
static double clock_get_monotonic_seconds(void) {
struct timespec ts;
ts.tv_sec = 0;
ts.tv_nsec = 0;
clock_gettime(CLOCK_MONOTONIC, &ts);
return (double)ts.tv_sec + (double)ts.tv_nsec * 0.000000001;
}
int main(int argc, char **argv) {
setlocale(LC_ALL, "C"); // Sigh... stupid C
int res = 0;
int socket_fd = 0;
gsr_drm drm;
drm.drmfd = 0;
if(argc != 3) {
fprintf(stderr, "usage: gsr-kms-server <domain_socket_path> <card_path>\n");
return 1;
}
const char *domain_socket_path = argv[1];
socket_fd = socket(AF_UNIX, SOCK_STREAM, 0);
if(socket_fd == -1) {
fprintf(stderr, "kms server error: failed to create socket, error: %s\n", strerror(errno));
return 2;
}
const char *card_path = argv[2];
drm.drmfd = open(card_path, O_RDONLY);
if(drm.drmfd < 0) {
fprintf(stderr, "kms server error: failed to open %s, error: %s", card_path, strerror(errno));
res = 2;
goto done;
}
if(drmSetClientCap(drm.drmfd, DRM_CLIENT_CAP_UNIVERSAL_PLANES, 1) != 0) {
fprintf(stderr, "kms server error: drmSetClientCap DRM_CLIENT_CAP_UNIVERSAL_PLANES failed, error: %s\n", strerror(errno));
res = 2;
goto done;
}
if(drmSetClientCap(drm.drmfd, DRM_CLIENT_CAP_ATOMIC, 1) != 0) {
fprintf(stderr, "kms server warning: drmSetClientCap DRM_CLIENT_CAP_ATOMIC failed, error: %s. The wrong monitor may be captured as a result\n", strerror(errno));
}
fprintf(stderr, "kms server info: connecting to the client\n");
bool connected = false;
const double connect_timeout_sec = 5.0;
const double start_time = clock_get_monotonic_seconds();
while(clock_get_monotonic_seconds() - start_time < connect_timeout_sec) {
struct sockaddr_un remote_addr = {0};
remote_addr.sun_family = AF_UNIX;
snprintf(remote_addr.sun_path, sizeof(remote_addr.sun_path), "%s", domain_socket_path);
// TODO: Check if parent disconnected
if(connect(socket_fd, (struct sockaddr*)&remote_addr, sizeof(remote_addr.sun_family) + strlen(remote_addr.sun_path)) == -1) {
if(errno == ECONNREFUSED || errno == ENOENT) {
goto next;
} else if(errno == EISCONN) {
connected = true;
break;
}
fprintf(stderr, "kms server error: connect failed, error: %s (%d)\n", strerror(errno), errno);
res = 2;
goto done;
}
next:
usleep(30 * 1000); // 30 milliseconds
}
if(connected) {
fprintf(stderr, "kms server info: connected to the client\n");
} else {
fprintf(stderr, "kms server error: failed to connect to the client in %f seconds\n", connect_timeout_sec);
res = 2;
goto done;
}
for(;;) {
gsr_kms_request request;
request.version = 0;
request.type = -1;
request.new_connection_fd = 0;
const int recv_res = recv_msg_from_client(socket_fd, &request);
if(recv_res == 0) {
fprintf(stderr, "kms server info: kms client shutdown, shutting down the server\n");
res = 3;
goto done;
} else if(recv_res == -1) {
const int err = errno;
fprintf(stderr, "kms server error: failed to read all data in client request (error: %s), ignoring\n", strerror(err));
if(err == EBADF) {
fprintf(stderr, "kms server error: invalid client fd, shutting down the server\n");
res = 3;
goto done;
}
continue;
}
if(request.version != GSR_KMS_PROTOCOL_VERSION) {
fprintf(stderr, "kms server error: expected gpu screen recorder protocol version to be %u, but it's %u. please reinstall gpu screen recorder\n", GSR_KMS_PROTOCOL_VERSION, request.version);
/*
if(request.new_connection_fd > 0)
close(request.new_connection_fd);
*/
continue;
}
switch(request.type) {
case KMS_REQUEST_TYPE_REPLACE_CONNECTION: {
gsr_kms_response response;
response.version = GSR_KMS_PROTOCOL_VERSION;
response.num_items = 0;
if(request.new_connection_fd > 0) {
if(socket_fd > 0)
close(socket_fd);
socket_fd = request.new_connection_fd;
response.result = KMS_RESULT_OK;
if(send_msg_to_client(socket_fd, &response) == -1)
fprintf(stderr, "kms server error: failed to respond to client KMS_REQUEST_TYPE_REPLACE_CONNECTION request\n");
} else {
response.result = KMS_RESULT_INVALID_REQUEST;
snprintf(response.err_msg, sizeof(response.err_msg), "received invalid connection fd");
fprintf(stderr, "kms server error: %s\n", response.err_msg);
if(send_msg_to_client(socket_fd, &response) == -1)
fprintf(stderr, "kms server error: failed to respond to client request\n");
}
break;
}
case KMS_REQUEST_TYPE_GET_KMS: {
gsr_kms_response response;
response.version = GSR_KMS_PROTOCOL_VERSION;
response.num_items = 0;
if(kms_get_fb(&drm, &response) == 0) {
if(send_msg_to_client(socket_fd, &response) == -1)
fprintf(stderr, "kms server error: failed to respond to client KMS_REQUEST_TYPE_GET_KMS request\n");
} else {
if(send_msg_to_client(socket_fd, &response) == -1)
fprintf(stderr, "kms server error: failed to respond to client KMS_REQUEST_TYPE_GET_KMS request\n");
}
for(int i = 0; i < response.num_items; ++i) {
for(int j = 0; j < response.items[i].num_dma_bufs; ++j) {
gsr_kms_response_dma_buf *dma_buf = &response.items[i].dma_buf[j];
if(dma_buf->fd > 0) {
close(dma_buf->fd);
dma_buf->fd = -1;
}
}
response.items[i].num_dma_bufs = 0;
}
response.num_items = 0;
break;
}
default: {
gsr_kms_response response;
response.version = GSR_KMS_PROTOCOL_VERSION;
response.result = KMS_RESULT_INVALID_REQUEST;
response.num_items = 0;
snprintf(response.err_msg, sizeof(response.err_msg), "invalid request type %d, expected %d (%s)", request.type, KMS_REQUEST_TYPE_GET_KMS, "KMS_REQUEST_TYPE_GET_KMS");
fprintf(stderr, "kms server error: %s\n", response.err_msg);
if(send_msg_to_client(socket_fd, &response) == -1)
fprintf(stderr, "kms server error: failed to respond to client request\n");
break;
}
}
}
done:
if(drm.drmfd > 0)
close(drm.drmfd);
if(socket_fd > 0)
close(socket_fd);
return res;
}

11
kms/server/project.conf Normal file
View File

@ -0,0 +1,11 @@
[package]
name = "gsr-kms-server"
type = "executable"
version = "1.0.0"
platforms = ["posix"]
[config]
error_on_warning = "true"
[dependencies]
libdrm = ">=2"