Hermes 0.7.0
Linux game streaming host
Loading...
Searching...
No Matches
pipewire_session.cpp
Go to the documentation of this file.
1
4#include "pipewire_session.h"
5
6#include "session_frame.h"
7#include "session_socket.h"
8
9#include <cerrno>
10#include <mutex>
11#include <pipewire/pipewire.h>
12#include <spa/param/video/format-utils.h>
13
14namespace platf::kwin {
16 pw_thread_loop *loop {};
17 pw_context *context {};
18 pw_core *core {};
19 pw_stream *stream {};
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 {};
25 bool started {};
26 bool stopping {};
27 bool format_ready {};
28 bool pending {};
29 bool streaming {};
30 std::string failure;
31 frame_t latest;
32
33 ~impl_t() {
34 if (started) {
35 pw_thread_loop_stop(loop);
36 }
37 stopping = true;
38 if (stream) {
39 spa_hook_remove(&stream_listener);
40 pw_stream_destroy(stream);
41 }
42 if (core) {
43 spa_hook_remove(&core_listener);
44 pw_core_disconnect(core);
45 }
46 if (context) {
47 pw_context_destroy(context);
48 }
49 if (loop) {
50 pw_thread_loop_destroy(loop);
51 }
52 }
53
54 void fail(std::string message) {
55 if (failure.empty()) {
56 failure = std::move(message);
57 }
58 pw_thread_loop_signal(loop, false);
59 }
60
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);
63 if (self.stopping) {
64 return;
65 }
66 if (state == PW_STREAM_STATE_ERROR) {
67 self.fail(error ? error : "Private PipeWire stream failed");
68 }
69 if (state == PW_STREAM_STATE_STREAMING) {
70 self.streaming = true;
71 }
72 if (state == PW_STREAM_STATE_UNCONNECTED && self.streaming) {
73 self.fail("Private PipeWire stream disconnected");
74 }
75 pw_thread_loop_signal(self.loop, false);
76 }
77
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) {
81 return;
82 }
83 if (!param) {
84 if (self.format_ready) {
85 self.fail("Private capture format was removed");
86 }
87 return;
88 }
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");
93 return;
94 }
95 self.format = format;
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)))),
101 };
102 if (pw_stream_update_params(self.stream, params, 1) < 0) {
103 self.fail("Could not negotiate mapped private capture buffers");
104 }
105 }
106
107 static void process(void *data) {
108 auto &self = *static_cast<impl_t *>(data);
109 auto buffer = pw_stream_dequeue_buffer(self.stream);
110 if (!buffer) {
111 return;
112 }
113 bool valid = false;
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)) {
119 try {
120 valid = copy_bgrx(self.latest.bgrx, plane.data, plane.maxsize, plane.chunk->offset, plane.chunk->size, plane.chunk->stride, self.width, self.height);
121 } catch (...) {
122 // No C++ exception may unwind through a PipeWire callback.
123 pw_stream_queue_buffer(self.stream, buffer);
124 self.fail("Could not allocate private capture frame");
125 return;
126 }
127 }
128 }
129 pw_stream_queue_buffer(self.stream, buffer);
130 if (!valid) {
131 self.fail("Private capture supplied an invalid mapped frame");
132 return;
133 }
134 self.latest.width = self.width;
135 self.latest.height = self.height;
136 self.latest.timestamp = std::chrono::steady_clock::now();
137 self.pending = true;
138 pw_thread_loop_signal(self.loop, false);
139 }
140 };
141
142 video_receiver_t::video_receiver_t(std::unique_ptr<impl_t> state):
143 impl(std::move(state)) {}
144
145 video_receiver_t::~video_receiver_t() = default;
146
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) {
148 error.clear();
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";
152 return nullptr;
153 }
154 static std::once_flag initialized;
155 std::call_once(initialized, [] {
156 pw_init(nullptr, nullptr);
157 });
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);
162 if (!state->loop) {
163 error = "Could not create private PipeWire loop";
164 return nullptr;
165 }
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";
169 return nullptr;
170 }
171 // PIPEWIRE_REMOTE overrides even an absolute remote.name property. Supply
172 // an already connected fd so environment settings cannot select the host.
173 const int fd = connect_session_socket(socket, error);
174 if (fd < 0) {
175 return nullptr;
176 }
177 // PipeWire takes ownership of fd, including on error.
178 state->core = pw_context_connect_fd(state->context, fd, nullptr, 0);
179 if (!state->core) {
180 error = "Could not initialize the specified PipeWire connection";
181 return nullptr;
182 }
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");
188 };
189 return events;
190 }();
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";
196 return nullptr;
197 }
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;
204 return events;
205 }();
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};
212 // KWin uses variable-rate capture; negotiate the rate ceiling separately.
213 format.framerate = {0, 1};
214 format.max_framerate = {framerate, 1};
215 // Negotiate a ceiling rather than requiring an exact compositor rate.
216 // CVT rounding can yield 119.930 Hz for a nominal 120 FPS request.
217 const spa_fraction minimum_rate {0, 1};
218 const spa_pod *params[] {static_cast<const spa_pod *>(spa_pod_builder_add_object(
219 &builder,
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)
234 ))};
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";
238 return nullptr;
239 }
240 // PipeWire applies stream.rules and PIPEWIRE_NODE/PIPEWIRE_PROPS during
241 // connect. Validate their result before activating or running the loop.
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";
247 return nullptr;
248 }
249 if (pw_stream_set_active(state->stream, true) < 0) {
250 error = "Could not activate private capture stream";
251 return nullptr;
252 }
253 if (pw_thread_loop_start(state->loop) < 0) {
254 error = "Could not start private PipeWire loop";
255 return nullptr;
256 }
257 state->started = true;
258 return std::unique_ptr<video_receiver_t>(new video_receiver_t(std::move(state)));
259 }
260
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) {
268 break;
269 }
270 if (result < 0) {
271 impl->fail("Private PipeWire wait failed");
272 break;
273 }
274 }
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) {
280 // Move ownership out while holding the loop lock. PipeWire's mapped buffer
281 // was already returned; the encoder never holds a server-owned mapping.
282 frame = std::move(impl->latest);
283 impl->pending = false;
284 result = frame_result_t::ready;
285 }
286 pw_thread_loop_unlock(impl->loop);
287 return result;
288 }
289} // namespace platf::kwin
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.