11#include <pipewire/pipewire.h>
12#include <spa/param/video/format-utils.h>
14namespace platf::kwin {
16 pw_thread_loop *loop {};
17 pw_context *context {};
20 spa_hook stream_listener {};
21 spa_hook core_listener {};
22 spa_video_info_raw format {};
23 std::uint32_t width {};
24 std::uint32_t height {};
35 pw_thread_loop_stop(loop);
39 spa_hook_remove(&stream_listener);
40 pw_stream_destroy(stream);
43 spa_hook_remove(&core_listener);
44 pw_core_disconnect(core);
47 pw_context_destroy(context);
50 pw_thread_loop_destroy(loop);
54 void fail(std::string message) {
55 if (failure.empty()) {
56 failure = std::move(message);
58 pw_thread_loop_signal(loop,
false);
61 static void state_changed(
void *data, pw_stream_state, pw_stream_state state,
const char *error) {
62 auto &self = *
static_cast<impl_t *
>(data);
66 if (state == PW_STREAM_STATE_ERROR) {
67 self.fail(error ? error :
"Private PipeWire stream failed");
69 if (state == PW_STREAM_STATE_STREAMING) {
70 self.streaming =
true;
72 if (state == PW_STREAM_STATE_UNCONNECTED && self.streaming) {
73 self.fail(
"Private PipeWire stream disconnected");
75 pw_thread_loop_signal(self.loop,
false);
78 static void param_changed(
void *data, std::uint32_t
id,
const spa_pod *param) {
79 auto &self = *
static_cast<impl_t *
>(data);
80 if (
id != SPA_PARAM_Format) {
84 if (self.format_ready) {
85 self.fail(
"Private capture format was removed");
89 spa_video_info_raw format {};
90 if (spa_format_video_raw_parse(param, &format) < 0 || format.format != SPA_VIDEO_FORMAT_BGRx ||
91 format.size.width != self.width || format.size.height != self.height) {
92 self.fail(
"Private capture negotiated an unexpected pixel format or size");
96 self.format_ready =
true;
97 std::uint8_t buffer[512];
98 spa_pod_builder builder = SPA_POD_BUILDER_INIT(buffer,
sizeof(buffer));
99 const spa_pod *params[] = {
100 static_cast<const spa_pod *
>(spa_pod_builder_add_object(&builder, SPA_TYPE_OBJECT_ParamBuffers, SPA_PARAM_Buffers, SPA_PARAM_BUFFERS_dataType, SPA_POD_CHOICE_FLAGS_Int((1 << SPA_DATA_MemFd) | (1 << SPA_DATA_MemPtr)))),
102 if (pw_stream_update_params(self.stream, params, 1) < 0) {
103 self.fail(
"Could not negotiate mapped private capture buffers");
107 static void process(
void *data) {
108 auto &self = *
static_cast<impl_t *
>(data);
109 auto buffer = pw_stream_dequeue_buffer(self.stream);
114 auto *spa = buffer->buffer;
115 if (self.format_ready && spa && spa->n_datas == 1) {
116 const auto &plane = spa->datas[0];
117 if ((plane.type == SPA_DATA_MemFd || plane.type == SPA_DATA_MemPtr) && plane.chunk &&
118 !(plane.chunk->flags & SPA_CHUNK_FLAG_CORRUPTED)) {
120 valid = copy_bgrx(self.latest.bgrx, plane.data, plane.maxsize, plane.chunk->offset, plane.chunk->size, plane.chunk->stride, self.width, self.height);
123 pw_stream_queue_buffer(self.stream, buffer);
124 self.fail(
"Could not allocate private capture frame");
129 pw_stream_queue_buffer(self.stream, buffer);
131 self.fail(
"Private capture supplied an invalid mapped frame");
134 self.latest.width = self.width;
135 self.latest.height = self.height;
136 self.latest.timestamp = std::chrono::steady_clock::now();
138 pw_thread_loop_signal(self.loop,
false);
142 video_receiver_t::video_receiver_t(std::unique_ptr<impl_t> state):
143 impl(std::move(state)) {}
145 video_receiver_t::~video_receiver_t() =
default;
147 std::unique_ptr<video_receiver_t> video_receiver_t::open(
const std::string &socket, std::uint64_t serial, std::uint32_t width, std::uint32_t height, std::uint32_t framerate, std::string &error) {
149 if (socket.empty() || socket.front() !=
'/' || socket.find(
'\0') != std::string::npos || serial == 0 ||
150 !width || !height || width > 16384 || height > 16384 || !framerate || framerate > 1000) {
151 error =
"Invalid private PipeWire endpoint, node, size, or frame rate";
154 static std::once_flag initialized;
155 std::call_once(initialized, [] {
156 pw_init(
nullptr,
nullptr);
158 auto state = std::make_unique<impl_t>();
159 state->width = width;
160 state->height = height;
161 state->loop = pw_thread_loop_new(
"hermes-private-capture",
nullptr);
163 error =
"Could not create private PipeWire loop";
166 state->context = pw_context_new(pw_thread_loop_get_loop(state->loop),
nullptr, 0);
167 if (!state->context) {
168 error =
"Could not create private PipeWire context";
173 const int fd = connect_session_socket(socket, error);
178 state->core = pw_context_connect_fd(state->context, fd,
nullptr, 0);
180 error =
"Could not initialize the specified PipeWire connection";
183 static const auto core_events = [] {
184 pw_core_events events {};
185 events.version = PW_VERSION_CORE_EVENTS;
186 events.error = [](
void *data, std::uint32_t, int, int,
const char *message) {
187 static_cast<impl_t *
>(data)->fail(message ? message :
"Private PipeWire core error");
191 pw_core_add_listener(state->core, &state->core_listener, &core_events, state.get());
192 const auto target = std::to_string(serial);
193 state->stream = pw_stream_new(state->core,
"Hermes detached desktop", pw_properties_new(PW_KEY_TARGET_OBJECT, target.c_str(), PW_KEY_MEDIA_TYPE,
"Video", PW_KEY_MEDIA_CATEGORY,
"Capture", PW_KEY_MEDIA_ROLE,
"Screen",
nullptr));
194 if (!state->stream) {
195 error =
"Could not create private PipeWire stream";
198 static const auto stream_events = [] {
199 pw_stream_events events {};
200 events.version = PW_VERSION_STREAM_EVENTS;
201 events.state_changed = impl_t::state_changed;
202 events.param_changed = impl_t::param_changed;
203 events.process = impl_t::process;
206 pw_stream_add_listener(state->stream, &state->stream_listener, &stream_events, state.get());
207 std::uint8_t buffer[1024];
208 spa_pod_builder builder = SPA_POD_BUILDER_INIT(buffer,
sizeof(buffer));
209 spa_video_info_raw format {};
210 format.format = SPA_VIDEO_FORMAT_BGRx;
211 format.size = {width, height};
213 format.framerate = {0, 1};
214 format.max_framerate = {framerate, 1};
217 const spa_fraction minimum_rate {0, 1};
218 const spa_pod *params[] {
static_cast<const spa_pod *
>(spa_pod_builder_add_object(
220 SPA_TYPE_OBJECT_Format,
221 SPA_PARAM_EnumFormat,
222 SPA_FORMAT_mediaType,
223 SPA_POD_Id(SPA_MEDIA_TYPE_video),
224 SPA_FORMAT_mediaSubtype,
225 SPA_POD_Id(SPA_MEDIA_SUBTYPE_raw),
226 SPA_FORMAT_VIDEO_format,
227 SPA_POD_Id(format.format),
228 SPA_FORMAT_VIDEO_size,
229 SPA_POD_Rectangle(&format.size),
230 SPA_FORMAT_VIDEO_framerate,
231 SPA_POD_Fraction(&format.framerate),
232 SPA_FORMAT_VIDEO_maxFramerate,
233 SPA_POD_CHOICE_RANGE_Fraction(&format.max_framerate, &minimum_rate, &format.max_framerate)
235 const auto flags =
static_cast<pw_stream_flags
>(PW_STREAM_FLAG_AUTOCONNECT | PW_STREAM_FLAG_MAP_BUFFERS | PW_STREAM_FLAG_DONT_RECONNECT | PW_STREAM_FLAG_INACTIVE);
236 if (pw_stream_connect(state->stream, PW_DIRECTION_INPUT, PW_ID_ANY, flags, params, 1) < 0) {
237 error =
"Could not connect private capture node";
242 const auto *properties = pw_stream_get_properties(state->stream);
243 const char *actual_target = pw_properties_get(properties, PW_KEY_TARGET_OBJECT);
244 const char *reconnect = pw_properties_get(properties, PW_KEY_NODE_DONT_RECONNECT);
245 if (!actual_target || target != actual_target || !reconnect || std::strcmp(reconnect,
"true") != 0) {
246 error =
"PipeWire configuration attempted to override the private capture target or reconnect policy";
249 if (pw_stream_set_active(state->stream,
true) < 0) {
250 error =
"Could not activate private capture stream";
253 if (pw_thread_loop_start(state->loop) < 0) {
254 error =
"Could not start private PipeWire loop";
257 state->started =
true;
258 return std::unique_ptr<video_receiver_t>(
new video_receiver_t(std::move(state)));
261 frame_result_t video_receiver_t::next(frame_t &frame, std::chrono::milliseconds timeout, std::string &error) {
262 pw_thread_loop_lock(impl->loop);
263 timespec deadline {};
264 pw_thread_loop_get_time(impl->loop, &deadline, std::chrono::duration_cast<std::chrono::nanoseconds>(timeout).count());
265 while (!impl->pending && impl->failure.empty()) {
266 int result = pw_thread_loop_timed_wait_full(impl->loop, &deadline);
267 if (result == -ETIMEDOUT) {
271 impl->fail(
"Private PipeWire wait failed");
275 auto result = frame_result_t::timeout;
276 if (!impl->failure.empty()) {
277 error = impl->failure;
278 result = frame_result_t::failed;
279 }
else if (impl->pending) {
282 frame = std::move(impl->latest);
283 impl->pending =
false;
284 result = frame_result_t::ready;
286 pw_thread_loop_unlock(impl->loop);
Video from an explicitly addressed private-session PipeWire node.
Bounds checking for mapped, packed BGRx capture buffers.
Explicit, bounded Unix socket connection without display or remote environment lookup.