@deepseek-ai/libreoffice-kit 0.2.0-alpha7 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/NOTICE +1 -1
  2. package/README.md +7 -7
  3. package/README.zh.md +7 -7
  4. package/frame-forwarding/CMakeLists.txt +3 -4
  5. package/frame-forwarding/README.md +18 -18
  6. package/frame-forwarding/README.zh.md +19 -19
  7. package/frame-forwarding/include/dsh_frame_forwarding.h +33 -9
  8. package/frame-forwarding/index.d.ts +58 -54
  9. package/frame-forwarding/index.mjs +14 -17
  10. package/frame-forwarding/prebuilds/darwin-arm64/frame-forwarding.node +0 -0
  11. package/frame-forwarding/prebuilds/darwin-arm64/libdsh_frame_forwarding_sdk.a +0 -0
  12. package/frame-forwarding/prebuilds/darwin-arm64/manifest.json +22 -21
  13. package/frame-forwarding/prebuilds/darwin-x64/frame-forwarding.node +0 -0
  14. package/frame-forwarding/prebuilds/darwin-x64/libdsh_frame_forwarding_sdk.a +0 -0
  15. package/frame-forwarding/prebuilds/darwin-x64/manifest.json +22 -21
  16. package/frame-forwarding/prebuilds/win32-arm64/dsh_frame_forwarding_sdk.lib +0 -0
  17. package/frame-forwarding/prebuilds/win32-arm64/frame-forwarding.node +0 -0
  18. package/frame-forwarding/prebuilds/win32-arm64/manifest.json +22 -21
  19. package/frame-forwarding/prebuilds/win32-x64/dsh_frame_forwarding_sdk.lib +0 -0
  20. package/frame-forwarding/prebuilds/win32-x64/frame-forwarding.node +0 -0
  21. package/frame-forwarding/prebuilds/win32-x64/manifest.json +22 -21
  22. package/frame-forwarding/receipt.json +15 -14
  23. package/frame-forwarding/scripts/build-webgpu.mjs +1 -0
  24. package/frame-forwarding/scripts/build.mjs +5 -4
  25. package/frame-forwarding/scripts/metadata.mjs +11 -8
  26. package/frame-forwarding/scripts/source-identity.mjs +3 -3
  27. package/frame-forwarding/sdk.json +6 -5
  28. package/frame-forwarding/{include/dsh_webgpu.h → src/graphite-interop-internal.hxx} +22 -22
  29. package/frame-forwarding/src/{webgpu.cc → graphite-interop.cc} +34 -24
  30. package/frame-forwarding/src/node-producer.cc +24 -154
  31. package/frame-forwarding/src/producer.cc +93 -26
  32. package/frame-forwarding/src/receiver.cc +416 -212
  33. package/frame-forwarding/src/relay-transport.inc +38 -10
  34. package/frame-forwarding/src/transport.cc +307 -141
  35. package/frame-forwarding/src/transport.h +60 -9
  36. package/frame-forwarding/verify.d.mts +1 -1
  37. package/frame-forwarding/verify.mjs +19 -17
  38. package/lib/cli.js +79 -8
  39. package/lib/editor.js +16 -11
  40. package/lib/index.js +79 -8
  41. package/lib/types/editor.d.ts +17 -4
  42. package/lib/types/engine.d.ts +1 -1
  43. package/lib/types/fonts.d.ts +1 -1
  44. package/lib/types/index.d.ts +4 -2
  45. package/lib/types/pdf.d.ts +10 -0
  46. package/lib/worker.js +4 -3
  47. package/package.json +8 -10
  48. package/frame-forwarding/include/dsh_frame_forwarding_engine.h +0 -66
  49. package/frame-forwarding/include/dsh_frame_forwarding_node.h +0 -27
@@ -1,6 +1,7 @@
1
1
  #include "transport.h"
2
2
  #include <algorithm>
3
3
  #include <cstring>
4
+ #include <cstdio>
4
5
  #include <sstream>
5
6
  #include <stdexcept>
6
7
  #include <vector>
@@ -25,15 +26,39 @@ namespace dsh_frame_forwarding {
25
26
  Endpoint parse_endpoint(const std::string& value) {
26
27
  auto a = value.find('|'), b = value.find('|', a + 1), c = value.find('|', b + 1);
27
28
  if (a == std::string::npos || b == std::string::npos || c == std::string::npos || value.substr(0, a) != "1")
28
- throw std::runtime_error("Unsupported native render endpoint");
29
+ throw std::runtime_error("Unsupported frame-forwarding endpoint");
29
30
  auto pid_text = value.substr(a + 1, b - a - 1);
30
31
  size_t used = 0;
31
32
  auto pid = std::stoul(pid_text, &used);
32
33
  Endpoint result{static_cast<uint32_t>(pid), value.substr(b + 1, c - b - 1), value.substr(c + 1)};
33
34
  if (used != pid_text.size() || !pid || pid > UINT32_MAX || result.token.size() != 64 || result.name.empty() || result.name.size() > 200)
34
- throw std::runtime_error("Invalid native render endpoint");
35
+ throw std::runtime_error("Invalid frame-forwarding endpoint");
35
36
  return result;
36
37
  }
38
+ uint64_t parse_connection(const char (&token)[65]) {
39
+ if (!std::memchr(token, 0, sizeof(token)) || !token[0] || token[0] == '0' || std::strlen(token) > 16) return 0;
40
+ uint64_t value = 0;
41
+ for (const char* digit = token; *digit; ++digit) {
42
+ if (*digit < '0' || *digit > '9') return 0;
43
+ value = value * 10 + static_cast<uint64_t>(*digit - '0');
44
+ }
45
+ return value <= 9007199254740991ULL ? value : 0;
46
+ }
47
+ void Channel::bind_connection(uint64_t id) {
48
+ connection_ = id;
49
+ std::snprintf(connection_text_, sizeof(connection_text_), "%llu", static_cast<unsigned long long>(id));
50
+ }
51
+ int Channel::receive(Received& out, uint32_t timeout_ms) {
52
+ const auto result = receive_packet(out, timeout_ms);
53
+ if (result != 1 || !connection_ || std::strncmp(out.packet.token, connection_text_, sizeof(out.packet.token)) == 0) return result;
54
+ release_resource(out.resource); out.resource = 0; foreign_ = true; interrupt(); return -1;
55
+ }
56
+ bool Channel::send(const Packet& packet, uintptr_t resource) {
57
+ if (!connection_) return send_packet(packet, resource);
58
+ Packet stamped = packet;
59
+ std::memcpy(stamped.token, connection_text_, sizeof(stamped.token));
60
+ return send_packet(stamped, resource);
61
+ }
37
62
  #if defined(__APPLE__)
38
63
  struct MachMessage {
39
64
  mach_msg_header_t header;
@@ -42,42 +67,85 @@ struct MachMessage {
42
67
  Packet packet;
43
68
  mach_msg_audit_trailer_t trailer;
44
69
  };
70
+ /**
71
+ * Receive one protocol message: 1 data, 0 timeout, -1 failure, -2 a message of another shape (destroyed), -3 the
72
+ * watched peer's dead-name notice. Releasing a notification request's send-once right posts a notice that is -2.
73
+ */
74
+ int receive_mach(mach_port_t port, uint32_t timeout, MachMessage& msg, uint32_t& pid) {
75
+ auto result = mach_msg(&msg.header, MACH_RCV_MSG | MACH_RCV_TIMEOUT |
76
+ MACH_RCV_TRAILER_TYPE(MACH_MSG_TRAILER_FORMAT_0) | MACH_RCV_TRAILER_ELEMENTS(MACH_RCV_TRAILER_AUDIT),
77
+ 0, sizeof(msg), port, timeout, MACH_PORT_NULL);
78
+ if (result == MACH_RCV_TIMED_OUT) return 0;
79
+ if (result != KERN_SUCCESS) return -1;
80
+ if (msg.header.msgh_id == MACH_NOTIFY_DEAD_NAME) { mach_msg_destroy(&msg.header); return -3; }
81
+ if (msg.header.msgh_size != offsetof(MachMessage, trailer) || !(msg.header.msgh_bits & MACH_MSGH_BITS_COMPLEX) ||
82
+ msg.body.msgh_descriptor_count != 1 || msg.port.type != MACH_MSG_PORT_DESCRIPTOR) {
83
+ mach_msg_destroy(&msg.header); return -2;
84
+ }
85
+ auto* trailer = reinterpret_cast<mach_msg_audit_trailer_t*>(reinterpret_cast<char*>(&msg) + msg.header.msgh_size);
86
+ if (trailer->msgh_trailer_size < sizeof(mach_msg_audit_trailer_t)) { mach_msg_destroy(&msg.header); return -2; }
87
+ pid = static_cast<uint32_t>(audit_token_to_pid(trailer->msgh_audit));
88
+ return 1;
89
+ }
90
+ mach_port_t allocate_port() {
91
+ mach_port_t port = MACH_PORT_NULL;
92
+ if (mach_port_allocate(mach_task_self(), MACH_PORT_RIGHT_RECEIVE, &port) != KERN_SUCCESS) throw std::runtime_error("Cannot allocate frame-forwarding Mach port");
93
+ if (mach_port_insert_right(mach_task_self(), port, port, MACH_MSG_TYPE_MAKE_SEND) != KERN_SUCCESS) {
94
+ mach_port_mod_refs(mach_task_self(), port, MACH_PORT_RIGHT_RECEIVE, -1); throw std::runtime_error("Cannot allocate frame-forwarding Mach port");
95
+ }
96
+ return port;
97
+ }
98
+ void destroy_port(mach_port_t port) {
99
+ if (!port) return;
100
+ mach_port_deallocate(mach_task_self(), port);
101
+ mach_port_mod_refs(mach_task_self(), port, MACH_PORT_RIGHT_RECEIVE, -1);
102
+ }
103
+ /**
104
+ * One producer connection. The producer's hello carries its reply port; the receiver answers on it with ready, whose
105
+ * descriptor is the connection port this channel receives on, so every connection owns its ports.
106
+ */
45
107
  class MachChannel final : public Channel {
46
108
  mach_port_t local_ = MACH_PORT_NULL, remote_ = MACH_PORT_NULL;
47
- Endpoint endpoint_;
48
109
  bool server_;
110
+ /** The process this connection's packets must come from: the receiver for a producer, the candidate for a receiver. */
111
+ uint32_t source_pid_;
49
112
  std::atomic<bool> stopped_{false};
50
113
  std::atomic<uint32_t> peer_{0};
51
114
  std::mutex writes_;
52
- public:
53
- MachChannel(Endpoint endpoint, bool server) : endpoint_(std::move(endpoint)), server_(server) {
54
- if (mach_port_allocate(mach_task_self(), MACH_PORT_RIGHT_RECEIVE, &local_) != KERN_SUCCESS ||
55
- mach_port_insert_right(mach_task_self(), local_, local_, MACH_MSG_TYPE_MAKE_SEND) != KERN_SUCCESS)
56
- { if (local_) mach_port_mod_refs(mach_task_self(), local_, MACH_PORT_RIGHT_RECEIVE, -1); throw std::runtime_error("Cannot allocate native render Mach port"); }
57
- kern_return_t result;
58
- if (server_) result = bootstrap_register(bootstrap_port, const_cast<char*>(endpoint_.name.c_str()), local_);
59
- else result = bootstrap_look_up(bootstrap_port, const_cast<char*>(endpoint_.name.c_str()), &remote_);
60
- if (result != KERN_SUCCESS) {
61
- mach_port_deallocate(mach_task_self(), local_);
62
- mach_port_mod_refs(mach_task_self(), local_, MACH_PORT_RIGHT_RECEIVE, -1);
63
- throw std::runtime_error("Cannot register or discover native render Mach endpoint");
64
- }
65
- if (!server_) watch_peer();
66
- }
67
- ~MachChannel() override {
68
- if (server_) { const auto ignored = bootstrap_register(bootstrap_port, const_cast<char*>(endpoint_.name.c_str()), MACH_PORT_NULL); (void)ignored; }
69
- if (remote_) mach_port_deallocate(mach_task_self(), remote_);
70
- if (local_) { mach_port_deallocate(mach_task_self(), local_); mach_port_mod_refs(mach_task_self(), local_, MACH_PORT_RIGHT_RECEIVE, -1); }
71
- }
72
115
  void watch_peer() {
73
116
  mach_port_t previous = MACH_PORT_NULL;
74
117
  auto result = mach_port_request_notification(mach_task_self(), remote_, MACH_NOTIFY_DEAD_NAME, 0, local_, MACH_MSG_TYPE_MAKE_SEND_ONCE, &previous);
75
118
  if (previous) mach_port_deallocate(mach_task_self(), previous);
76
119
  if (result != KERN_SUCCESS) stopped_ = true;
77
120
  }
121
+ /** Cancel the dead-name request so releasing the right posts no port-deleted notice. */
122
+ void unwatch_peer() {
123
+ mach_port_t previous = MACH_PORT_NULL;
124
+ mach_port_request_notification(mach_task_self(), remote_, MACH_NOTIFY_DEAD_NAME, 0, MACH_PORT_NULL, MACH_MSG_TYPE_MAKE_SEND_ONCE, &previous);
125
+ if (previous) mach_port_deallocate(mach_task_self(), previous);
126
+ }
127
+ public:
128
+ /** Producer side: discover the listener; ready later replaces it with the connection port. */
129
+ explicit MachChannel(const Endpoint& endpoint) : server_(false), source_pid_(endpoint.pid) {
130
+ local_ = allocate_port();
131
+ if (bootstrap_look_up(bootstrap_port, const_cast<char*>(endpoint.name.c_str()), &remote_) != KERN_SUCCESS) {
132
+ destroy_port(local_); throw std::runtime_error("Cannot discover frame-forwarding Mach endpoint");
133
+ }
134
+ watch_peer();
135
+ }
136
+ /** Receiver side: adopt the candidate's reply port and open a connection port for it. */
137
+ MachChannel(mach_port_t reply, uint32_t pid) : remote_(reply), server_(true), source_pid_(pid) {
138
+ try { local_ = allocate_port(); } catch (...) { mach_port_deallocate(mach_task_self(), reply); throw; }
139
+ peer_ = pid; watch_peer();
140
+ }
141
+ ~MachChannel() override {
142
+ if (remote_) { unwatch_peer(); mach_port_deallocate(mach_task_self(), remote_); }
143
+ destroy_port(local_);
144
+ }
78
145
  uint32_t peer_pid() const override { return peer_; }
79
146
  void interrupt() override { stopped_ = true; }
80
- bool send(const Packet& packet, uintptr_t resource) override {
147
+ protected:
148
+ bool send_packet(const Packet& packet, uintptr_t resource) override {
81
149
  std::lock_guard<std::mutex> lock(writes_);
82
150
  if (stopped_ || !remote_) return false;
83
151
  MachMessage msg{};
@@ -89,44 +157,64 @@ class MachChannel final : public Channel {
89
157
  msg.port.type = MACH_MSG_PORT_DESCRIPTOR;
90
158
  msg.port.disposition = MACH_MSG_TYPE_COPY_SEND;
91
159
  mach_port_t surface_port = MACH_PORT_NULL;
92
- if (packet.kind == hello) msg.port.name = local_;
160
+ if ((!server_ && packet.kind == hello) || (server_ && packet.kind == ready)) msg.port.name = local_;
93
161
  else if (resource) msg.port.name = surface_port = IOSurfaceCreateMachPort(reinterpret_cast<IOSurfaceRef>(resource));
94
162
  msg.packet = packet;
95
163
  auto result = mach_msg(&msg.header, MACH_SEND_MSG | MACH_SEND_TIMEOUT, msg.header.msgh_size, 0, MACH_PORT_NULL, 1000, MACH_PORT_NULL);
96
164
  if (surface_port) mach_port_deallocate(mach_task_self(), surface_port);
97
165
  return result == KERN_SUCCESS;
98
166
  }
99
- int receive(Received& out, uint32_t timeout) override {
167
+ int receive_packet(Received& out, uint32_t timeout) override {
100
168
  if (stopped_) return -1;
101
- MachMessage msg{};
102
- auto result = mach_msg(&msg.header, MACH_RCV_MSG | MACH_RCV_TIMEOUT |
103
- MACH_RCV_TRAILER_TYPE(MACH_MSG_TRAILER_FORMAT_0) | MACH_RCV_TRAILER_ELEMENTS(MACH_RCV_TRAILER_AUDIT),
104
- 0, sizeof(msg), local_, timeout, MACH_PORT_NULL);
105
- if (result == MACH_RCV_TIMED_OUT) return stopped_ ? -1 : 0;
106
- if (result != KERN_SUCCESS) return -1;
107
- if (msg.header.msgh_size != offsetof(MachMessage, trailer) || !(msg.header.msgh_bits & MACH_MSGH_BITS_COMPLEX) ||
108
- msg.body.msgh_descriptor_count != 1 || msg.port.type != MACH_MSG_PORT_DESCRIPTOR) {
109
- mach_msg_destroy(&msg.header); return -1;
110
- }
111
- auto* trailer = reinterpret_cast<mach_msg_audit_trailer_t*>(reinterpret_cast<char*>(&msg) + msg.header.msgh_size);
112
- if (trailer->msgh_trailer_size < sizeof(mach_msg_audit_trailer_t)) { mach_msg_destroy(&msg.header); return -1; }
113
- out.pid = static_cast<uint32_t>(audit_token_to_pid(trailer->msgh_audit));
114
- out.packet = msg.packet;
115
- if (server_ && out.packet.kind == hello && !remote_ && std::strncmp(out.packet.token, endpoint_.token.c_str(), sizeof(out.packet.token)) == 0) {
116
- remote_ = msg.port.name; peer_ = out.pid; msg.port.name = MACH_PORT_NULL; watch_peer();
169
+ MachMessage msg{}; uint32_t pid = 0;
170
+ const auto result = receive_mach(local_, timeout, msg, pid);
171
+ if (result == 0 || result == -2) return stopped_ ? -1 : 0;
172
+ if (result < 0) return -1;
173
+ out.pid = pid; out.packet = msg.packet;
174
+ if (pid != source_pid_) { mach_msg_destroy(&msg.header); return -1; }
175
+ if (!server_ && out.packet.kind == ready && msg.port.name) {
176
+ // The connection port replaces the listener for every later packet.
177
+ unwatch_peer(); mach_port_deallocate(mach_task_self(), remote_); remote_ = msg.port.name; msg.port.name = MACH_PORT_NULL; watch_peer();
117
178
  } else if (out.packet.kind == frame && msg.port.name) {
118
179
  out.resource = reinterpret_cast<uintptr_t>(IOSurfaceLookupFromMachPort(msg.port.name));
119
180
  }
120
181
  if (msg.port.name) mach_port_deallocate(mach_task_self(), msg.port.name);
121
- if (!server_ && out.pid != endpoint_.pid) { release_resource(out.resource); out.resource = 0; return -1; }
122
- if (!server_) peer_ = out.pid;
123
182
  return 1;
124
183
  }
125
184
  };
126
- std::unique_ptr<Channel> listen_channel(Endpoint& endpoint) { return std::make_unique<MachChannel>(endpoint, true); }
185
+ class MachListener final : public Listener {
186
+ mach_port_t port_ = MACH_PORT_NULL;
187
+ std::string name_;
188
+ std::atomic<bool> stopped_{false};
189
+ public:
190
+ explicit MachListener(const Endpoint& endpoint) : name_(endpoint.name) {
191
+ port_ = allocate_port();
192
+ if (bootstrap_register(bootstrap_port, const_cast<char*>(name_.c_str()), port_) != KERN_SUCCESS) {
193
+ destroy_port(port_); throw std::runtime_error("Cannot register frame-forwarding Mach endpoint");
194
+ }
195
+ }
196
+ ~MachListener() override {
197
+ const auto ignored = bootstrap_register(bootstrap_port, const_cast<char*>(name_.c_str()), MACH_PORT_NULL); (void)ignored;
198
+ destroy_port(port_);
199
+ }
200
+ void interrupt() override { stopped_ = true; }
201
+ int accept(Candidate& candidate, uint32_t timeout) override {
202
+ if (stopped_) return -1;
203
+ MachMessage msg{}; uint32_t pid = 0;
204
+ const auto result = receive_mach(port_, timeout, msg, pid);
205
+ if (result == 0 || result <= -2) return stopped_ ? -1 : 0;
206
+ if (result < 0) return -1;
207
+ if (msg.packet.kind != hello || !msg.port.name || msg.port.disposition != MACH_MSG_TYPE_PORT_SEND) { mach_msg_destroy(&msg.header); return 0; }
208
+ const auto reply = msg.port.name;
209
+ candidate.hello = Received{}; candidate.hello.packet = msg.packet; candidate.hello.pid = pid;
210
+ candidate.channel = std::make_unique<MachChannel>(reply, pid);
211
+ return 1;
212
+ }
213
+ };
214
+ std::unique_ptr<Listener> listen(Endpoint& endpoint, uint32_t) { return std::make_unique<MachListener>(endpoint); }
127
215
  std::unique_ptr<Channel> connect_channel(const Endpoint& endpoint, const std::function<bool()>& cancelled) {
128
- if (cancelled && cancelled()) throw std::runtime_error("Native render connection cancelled or timed out");
129
- return std::make_unique<MachChannel>(endpoint, false);
216
+ if (cancelled && cancelled()) throw std::runtime_error("Frame-forwarding connection cancelled or timed out");
217
+ return std::make_unique<MachChannel>(endpoint);
130
218
  }
131
219
  uint32_t process_id() { return getpid(); }
132
220
  void clear_validation_device() {}
@@ -134,7 +222,8 @@ std::string resource_adapter(uintptr_t) { return "IOSurface"; }
134
222
  std::string device_adapter(void*) { return "IOSurface"; }
135
223
  void release_resource(uintptr_t resource) { if (resource) CFRelease(reinterpret_cast<IOSurfaceRef>(resource)); }
136
224
  uint64_t resource_bytes(uintptr_t resource) { return IOSurfaceGetAllocSize(reinterpret_cast<IOSurfaceRef>(resource)); }
137
- bool resource_dimensions(uintptr_t resource, uint32_t width, uint32_t height, uint32_t stride, std::string& diagnostic, std::string& adapter, bool* keyed_mutex) {
225
+ bool resource_dimensions(uintptr_t resource, uint32_t width, uint32_t height, uint32_t stride,
226
+ std::chrono::steady_clock::time_point, std::string& diagnostic, std::string& adapter, bool* keyed_mutex) {
138
227
  if (keyed_mutex) *keyed_mutex = false;
139
228
  diagnostic = "IOSurface format or dimensions differ"; adapter = "IOSurface";
140
229
  auto surface = reinterpret_cast<IOSurfaceRef>(resource);
@@ -221,92 +310,79 @@ std::string resource_adapter(uintptr_t resource) {
221
310
  FAILED(factory->GetSharedResourceAdapterLuid(reinterpret_cast<HANDLE>(resource), &luid))) return {};
222
311
  return adapter_id(luid);
223
312
  }
313
+ /** Overlapped I/O wait shared by pipe channels and the listener: 1 completed, 0 timed out, -1 stopped or failed. */
314
+ int wait_pipe(HANDLE pipe, OVERLAPPED& operation, HANDLE stop, HANDLE deadline, DWORD timeout, DWORD& count) {
315
+ HANDLE events[] = {operation.hEvent, stop, deadline};
316
+ const bool timed = timeout != 0 && timeout != INFINITE;
317
+ if (timed) {
318
+ LARGE_INTEGER due; due.QuadPart = -static_cast<LONGLONG>(timeout) * 10000;
319
+ if (!SetWaitableTimer(deadline, &due, 0, nullptr, nullptr, FALSE)) {
320
+ CancelIoEx(pipe, &operation);
321
+ return GetOverlappedResult(pipe, &operation, &count, TRUE) ? 1 : -1;
322
+ }
323
+ }
324
+ // A millisecond pipe poll must not round up to the system's coarse clock tick.
325
+ auto result = WaitForMultipleObjects(timed ? 3 : 2, events, FALSE, timed ? INFINITE : timeout);
326
+ if (timed) {
327
+ CancelWaitableTimer(deadline);
328
+ if (result == WAIT_OBJECT_0 + 2) result = WAIT_TIMEOUT;
329
+ }
330
+ if (result != WAIT_OBJECT_0) {
331
+ CancelIoEx(pipe, &operation);
332
+ const bool completed = GetOverlappedResult(pipe, &operation, &count, TRUE) != FALSE;
333
+ // Completion can race the deadline; preserve a successfully received message.
334
+ if (result == WAIT_TIMEOUT && completed) return 1;
335
+ return result == WAIT_TIMEOUT ? 0 : -1;
336
+ }
337
+ return GetOverlappedResult(pipe, &operation, &count, FALSE) ? 1 : -1;
338
+ }
339
+ /** One connected pipe instance: the producer's client handle, or one instance the listener accepted. */
224
340
  class PipeChannel final : public Channel {
225
341
  HANDLE pipe_ = INVALID_HANDLE_VALUE, stop_ = nullptr, deadline_ = nullptr;
226
- bool server_, connected_ = false;
227
- Endpoint endpoint_;
228
342
  std::atomic<uint32_t> peer_{0};
229
343
  std::mutex writes_;
230
- bool wait(OVERLAPPED& operation, DWORD timeout, DWORD& count) {
231
- HANDLE events[] = {operation.hEvent, stop_, deadline_};
232
- const bool timed = timeout != 0 && timeout != INFINITE;
233
- if (timed) {
234
- LARGE_INTEGER due; due.QuadPart = -static_cast<LONGLONG>(timeout) * 10000;
235
- if (!SetWaitableTimer(deadline_, &due, 0, nullptr, nullptr, FALSE)) {
236
- const auto error = GetLastError();
237
- CancelIoEx(pipe_, &operation);
238
- if (GetOverlappedResult(pipe_, &operation, &count, TRUE)) return true;
239
- SetLastError(error);
240
- return false;
241
- }
242
- }
243
- // A millisecond pipe poll must not round up to the system's coarse clock tick.
244
- auto result = WaitForMultipleObjects(timed ? 3 : 2, events, FALSE, timed ? INFINITE : timeout);
245
- if (timed) {
246
- CancelWaitableTimer(deadline_);
247
- if (result == WAIT_OBJECT_0 + 2) result = WAIT_TIMEOUT;
248
- }
249
- if (result != WAIT_OBJECT_0) {
250
- CancelIoEx(pipe_, &operation);
251
- const bool completed = GetOverlappedResult(pipe_, &operation, &count, TRUE) != FALSE;
252
- // Completion can race the deadline; preserve a successfully received message.
253
- if (result == WAIT_TIMEOUT && completed) return true;
254
- SetLastError(result == WAIT_TIMEOUT ? ERROR_OPERATION_ABORTED : ERROR_BROKEN_PIPE);
255
- return false;
256
- }
257
- return GetOverlappedResult(pipe_, &operation, &count, FALSE) != FALSE;
344
+ void open_events() {
345
+ stop_ = CreateEventW(nullptr, TRUE, FALSE, nullptr);
346
+ deadline_ = create_deadline_timer();
347
+ if (!stop_ || !deadline_) throw std::runtime_error("Cannot create frame-forwarding I/O wait events");
348
+ }
349
+ void close_handles() {
350
+ if (pipe_ != INVALID_HANDLE_VALUE) CloseHandle(pipe_);
351
+ if (stop_) CloseHandle(stop_);
352
+ if (deadline_) CloseHandle(deadline_);
353
+ pipe_ = INVALID_HANDLE_VALUE; stop_ = nullptr; deadline_ = nullptr;
258
354
  }
259
355
  public:
260
- PipeChannel(Endpoint endpoint, bool server, const std::function<bool()>& cancelled = {}) : server_(server), endpoint_(std::move(endpoint)) {
261
- stop_ = CreateEventW(nullptr, TRUE, FALSE, nullptr);
356
+ /** Producer side: connect to the receiver's pipe and check its process identity. */
357
+ PipeChannel(const Endpoint& endpoint, const std::function<bool()>& cancelled) {
262
358
  try {
263
- deadline_ = create_deadline_timer();
264
- if (!stop_ || !deadline_) throw std::runtime_error("Cannot create native render I/O wait events");
265
- if (server_) {
266
- HANDLE token = nullptr; DWORD size = 0;
267
- if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token)) throw std::runtime_error("Cannot inspect receiver identity");
268
- GetTokenInformation(token, TokenUser, nullptr, 0, &size);
269
- std::vector<unsigned char> data(size);
270
- bool ok = GetTokenInformation(token, TokenUser, data.data(), size, &size) != FALSE;
271
- CloseHandle(token);
272
- LPSTR sid = nullptr;
273
- if (!ok || !ConvertSidToStringSidA(reinterpret_cast<TOKEN_USER*>(data.data())->User.Sid, &sid)) throw std::runtime_error("Cannot encode receiver identity");
274
- std::string sddl = std::string("D:P(A;;GA;;;") + sid + ")"; LocalFree(sid);
275
- PSECURITY_DESCRIPTOR descriptor = nullptr;
276
- if (!ConvertStringSecurityDescriptorToSecurityDescriptorA(sddl.c_str(), SDDL_REVISION_1, &descriptor, nullptr)) throw std::runtime_error("Cannot restrict render pipe");
277
- SECURITY_ATTRIBUTES security{sizeof(security), descriptor, FALSE};
278
- pipe_ = CreateNamedPipeA(endpoint_.name.c_str(), PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED | FILE_FLAG_FIRST_PIPE_INSTANCE,
279
- PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT | PIPE_REJECT_REMOTE_CLIENTS, 1, sizeof(Packet) * 4, sizeof(Packet) * 4, 0, &security);
280
- LocalFree(descriptor);
281
- } else {
282
- while (!WaitNamedPipeA(endpoint_.name.c_str(), cancelled ? 100 : 10000)) {
359
+ open_events();
360
+ while (!WaitNamedPipeA(endpoint.name.c_str(), cancelled ? 100 : 10000)) {
283
361
  const auto error = GetLastError();
284
- if (cancelled && cancelled()) throw std::runtime_error("Native render connection cancelled or timed out");
362
+ if (cancelled && cancelled()) throw std::runtime_error("Frame-forwarding connection cancelled or timed out");
285
363
  if (!cancelled || (error != ERROR_SEM_TIMEOUT && error != ERROR_PIPE_BUSY))
286
- throw std::runtime_error("Native render receiver unavailable");
364
+ throw std::runtime_error("Frame-forwarding receiver unavailable");
287
365
  }
288
- pipe_ = CreateFileA(endpoint_.name.c_str(), GENERIC_READ | GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, nullptr);
366
+ pipe_ = CreateFileA(endpoint.name.c_str(), GENERIC_READ | GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, nullptr);
367
+ if (pipe_ == INVALID_HANDLE_VALUE) throw std::runtime_error("Frame-forwarding receiver unavailable");
289
368
  DWORD mode = PIPE_READMODE_MESSAGE; SetNamedPipeHandleState(pipe_, &mode, nullptr, nullptr);
290
369
  ULONG pid = 0;
291
- if (!GetNamedPipeServerProcessId(pipe_, &pid) || pid != endpoint_.pid) {
292
- CloseHandle(pipe_); pipe_ = INVALID_HANDLE_VALUE; throw std::runtime_error("Native render receiver identity mismatch");
293
- }
294
- peer_ = pid; connected_ = true;
295
- }
296
- if (pipe_ == INVALID_HANDLE_VALUE) throw std::runtime_error("Cannot open private native render pipe");
297
- } catch (...) {
298
- if (pipe_ != INVALID_HANDLE_VALUE) CloseHandle(pipe_);
299
- if (stop_) CloseHandle(stop_);
300
- if (deadline_) CloseHandle(deadline_);
301
- throw;
302
- }
370
+ if (!GetNamedPipeServerProcessId(pipe_, &pid) || pid != endpoint.pid) throw std::runtime_error("Frame-forwarding receiver identity mismatch");
371
+ peer_ = pid;
372
+ } catch (...) { close_handles(); throw; }
303
373
  }
304
- ~PipeChannel() override { interrupt(); if (pipe_ != INVALID_HANDLE_VALUE) CloseHandle(pipe_); if (stop_) CloseHandle(stop_); if (deadline_) CloseHandle(deadline_); }
374
+ /** Receiver side: adopt an instance whose client connected. */
375
+ PipeChannel(HANDLE pipe, uint32_t pid) : pipe_(pipe) {
376
+ try { open_events(); } catch (...) { close_handles(); throw; }
377
+ peer_ = pid;
378
+ }
379
+ ~PipeChannel() override { interrupt(); close_handles(); }
305
380
  uint32_t peer_pid() const override { return peer_; }
306
- void interrupt() override { SetEvent(stop_); CancelIoEx(pipe_, nullptr); }
307
- bool send(const Packet& source, uintptr_t resource) override {
381
+ void interrupt() override { if (stop_) SetEvent(stop_); if (pipe_ != INVALID_HANDLE_VALUE) CancelIoEx(pipe_, nullptr); }
382
+ protected:
383
+ bool send_packet(const Packet& source, uintptr_t resource) override {
308
384
  std::lock_guard<std::mutex> lock(writes_);
309
- if (!connected_ || WaitForSingleObject(stop_, 0) == WAIT_OBJECT_0) return false;
385
+ if (WaitForSingleObject(stop_, 0) == WAIT_OBJECT_0) return false;
310
386
  Packet packet = source;
311
387
  HANDLE remote_handle = nullptr, target = nullptr;
312
388
  if (resource) {
@@ -318,7 +394,7 @@ class PipeChannel final : public Channel {
318
394
  }
319
395
  OVERLAPPED operation{}; operation.hEvent = CreateEventW(nullptr, TRUE, FALSE, nullptr); DWORD count = 0;
320
396
  bool ok = WriteFile(pipe_, &packet, sizeof(packet), &count, &operation) != FALSE;
321
- if (!ok && GetLastError() == ERROR_IO_PENDING) ok = wait(operation, INFINITE, count);
397
+ if (!ok && GetLastError() == ERROR_IO_PENDING) ok = wait_pipe(pipe_, operation, stop_, deadline_, INFINITE, count) == 1;
322
398
  CloseHandle(operation.hEvent);
323
399
  if (!ok && remote_handle) {
324
400
  HANDLE reclaimed = nullptr;
@@ -327,34 +403,117 @@ class PipeChannel final : public Channel {
327
403
  if (target) CloseHandle(target);
328
404
  return ok && count == sizeof(packet);
329
405
  }
330
- int receive(Received& out, uint32_t timeout) override {
406
+ int receive_packet(Received& out, uint32_t timeout) override {
331
407
  if (WaitForSingleObject(stop_, 0) == WAIT_OBJECT_0) return -1;
332
408
  OVERLAPPED operation{}; operation.hEvent = CreateEventW(nullptr, TRUE, FALSE, nullptr); DWORD count = 0;
333
- if (!connected_) {
334
- bool ok = ConnectNamedPipe(pipe_, &operation) != FALSE;
335
- auto error = GetLastError();
336
- if (!ok && error == ERROR_PIPE_CONNECTED) ok = true;
337
- else if (!ok && error == ERROR_IO_PENDING) ok = wait(operation, timeout, count);
338
- if (!ok) { CloseHandle(operation.hEvent); return WaitForSingleObject(stop_, 0) == WAIT_OBJECT_0 ? -1 : 0; }
339
- ULONG pid = 0;
340
- if (!GetNamedPipeClientProcessId(pipe_, &pid)) { CloseHandle(operation.hEvent); return -1; }
341
- peer_ = pid; connected_ = true; ResetEvent(operation.hEvent);
342
- }
343
- bool ok = ReadFile(pipe_, &out.packet, sizeof(Packet), &count, &operation) != FALSE;
344
- if (!ok && GetLastError() == ERROR_IO_PENDING) ok = wait(operation, timeout, count);
345
- auto error = GetLastError(); CloseHandle(operation.hEvent);
346
- if (!ok) return error == ERROR_OPERATION_ABORTED && WaitForSingleObject(stop_, 0) != WAIT_OBJECT_0 ? 0 : -1;
347
- if (count != sizeof(Packet)) return -1;
409
+ int result = ReadFile(pipe_, &out.packet, sizeof(Packet), &count, &operation) != FALSE ? 1 : -1;
410
+ if (result < 0 && GetLastError() == ERROR_IO_PENDING) result = wait_pipe(pipe_, operation, stop_, deadline_, timeout, count);
411
+ CloseHandle(operation.hEvent);
412
+ if (result == 0) return WaitForSingleObject(stop_, 0) == WAIT_OBJECT_0 ? -1 : 0;
413
+ if (result < 0 || count != sizeof(Packet)) return -1;
348
414
  out.pid = peer_; out.resource = static_cast<uintptr_t>(out.packet.resource);
349
415
  return 1;
350
416
  }
351
417
  };
352
- std::unique_ptr<Channel> listen_channel(Endpoint& endpoint) { return std::make_unique<PipeChannel>(endpoint, true); }
353
- std::unique_ptr<Channel> connect_channel(const Endpoint& endpoint, const std::function<bool()>& cancelled) { return std::make_unique<PipeChannel>(endpoint, false, cancelled); }
418
+ /** Per-user pipe security; remote clients are rejected by the pipe mode. */
419
+ std::string user_pipe_sddl() {
420
+ HANDLE token = nullptr; DWORD size = 0;
421
+ if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token)) throw std::runtime_error("Cannot inspect receiver identity");
422
+ GetTokenInformation(token, TokenUser, nullptr, 0, &size);
423
+ std::vector<unsigned char> data(size);
424
+ bool ok = GetTokenInformation(token, TokenUser, data.data(), size, &size) != FALSE;
425
+ CloseHandle(token);
426
+ LPSTR sid = nullptr;
427
+ if (!ok || !ConvertSidToStringSidA(reinterpret_cast<TOKEN_USER*>(data.data())->User.Sid, &sid)) throw std::runtime_error("Cannot encode receiver identity");
428
+ std::string sddl = std::string("D:P(A;;GA;;;") + sid + ")"; LocalFree(sid);
429
+ return sddl;
430
+ }
431
+ /**
432
+ * Pipe instances of one channel name. One instance waits for a client at a time; an instance whose client connected
433
+ * becomes a candidate after its hello arrives within the handshake deadline. The active connection, a waiting
434
+ * successor and a candidate being refused each hold an instance.
435
+ */
436
+ class PipeListener final : public Listener {
437
+ std::string name_, sddl_;
438
+ uint32_t handshake_ms_;
439
+ HANDLE stop_ = nullptr, deadline_ = nullptr, instance_ = INVALID_HANDLE_VALUE;
440
+ OVERLAPPED connect_{};
441
+ bool first_ = true, connecting_ = false;
442
+ static constexpr DWORD instances = 4;
443
+ void open_instance() {
444
+ PSECURITY_DESCRIPTOR descriptor = nullptr;
445
+ if (!ConvertStringSecurityDescriptorToSecurityDescriptorA(sddl_.c_str(), SDDL_REVISION_1, &descriptor, nullptr)) throw std::runtime_error("Cannot restrict frame-forwarding pipe");
446
+ SECURITY_ATTRIBUTES security{sizeof(security), descriptor, FALSE};
447
+ const DWORD open_mode = PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED | (first_ ? FILE_FLAG_FIRST_PIPE_INSTANCE : 0);
448
+ instance_ = CreateNamedPipeA(name_.c_str(), open_mode, PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT | PIPE_REJECT_REMOTE_CLIENTS,
449
+ instances, sizeof(Packet) * 4, sizeof(Packet) * 4, 0, &security);
450
+ LocalFree(descriptor);
451
+ if (instance_ == INVALID_HANDLE_VALUE) throw std::runtime_error("Cannot open private frame-forwarding pipe");
452
+ first_ = false;
453
+ }
454
+ void close_handles() {
455
+ if (instance_ != INVALID_HANDLE_VALUE) { CancelIoEx(instance_, nullptr); CloseHandle(instance_); instance_ = INVALID_HANDLE_VALUE; }
456
+ if (connect_.hEvent) { CloseHandle(connect_.hEvent); connect_.hEvent = nullptr; }
457
+ if (stop_) { CloseHandle(stop_); stop_ = nullptr; }
458
+ if (deadline_) { CloseHandle(deadline_); deadline_ = nullptr; }
459
+ }
460
+ public:
461
+ PipeListener(const Endpoint& endpoint, uint32_t handshake_ms) : name_(endpoint.name), handshake_ms_(handshake_ms) {
462
+ try {
463
+ sddl_ = user_pipe_sddl();
464
+ stop_ = CreateEventW(nullptr, TRUE, FALSE, nullptr);
465
+ deadline_ = create_deadline_timer();
466
+ connect_.hEvent = CreateEventW(nullptr, TRUE, FALSE, nullptr);
467
+ if (!stop_ || !deadline_ || !connect_.hEvent) throw std::runtime_error("Cannot create frame-forwarding I/O wait events");
468
+ open_instance();
469
+ } catch (...) { close_handles(); throw; }
470
+ }
471
+ ~PipeListener() override { close_handles(); }
472
+ void interrupt() override { SetEvent(stop_); if (instance_ != INVALID_HANDLE_VALUE) CancelIoEx(instance_, nullptr); }
473
+ int accept(Candidate& candidate, uint32_t timeout) override {
474
+ if (WaitForSingleObject(stop_, 0) == WAIT_OBJECT_0) return -1;
475
+ if (instance_ == INVALID_HANDLE_VALUE) open_instance();
476
+ DWORD count = 0;
477
+ if (!connecting_) {
478
+ ResetEvent(connect_.hEvent);
479
+ const bool connected = ConnectNamedPipe(instance_, &connect_) != FALSE;
480
+ const auto error = GetLastError();
481
+ if (!connected && error == ERROR_IO_PENDING) connecting_ = true;
482
+ else if (!connected && error != ERROR_PIPE_CONNECTED) { CloseHandle(instance_); instance_ = INVALID_HANDLE_VALUE; return 0; }
483
+ }
484
+ if (connecting_) {
485
+ HANDLE events[] = {connect_.hEvent, stop_};
486
+ const auto waited = WaitForMultipleObjects(2, events, FALSE, timeout);
487
+ if (waited == WAIT_TIMEOUT) return 0;
488
+ if (waited != WAIT_OBJECT_0) return -1;
489
+ connecting_ = false;
490
+ if (!GetOverlappedResult(instance_, &connect_, &count, FALSE)) { CloseHandle(instance_); instance_ = INVALID_HANDLE_VALUE; return 0; }
491
+ }
492
+ // The connected instance belongs to its candidate; the next accept opens another one.
493
+ HANDLE pipe = instance_; instance_ = INVALID_HANDLE_VALUE;
494
+ ULONG pid = 0;
495
+ if (!GetNamedPipeClientProcessId(pipe, &pid)) { CloseHandle(pipe); return 0; }
496
+ auto channel = std::make_unique<PipeChannel>(pipe, static_cast<uint32_t>(pid));
497
+ Received hello;
498
+ if (channel->receive(hello, handshake_ms_) != 1) { release_resource(hello.resource); return 0; }
499
+ candidate.hello = hello; candidate.channel = std::move(channel);
500
+ return 1;
501
+ }
502
+ };
503
+ std::unique_ptr<Listener> listen(Endpoint& endpoint, uint32_t handshake_ms) { return std::make_unique<PipeListener>(endpoint, handshake_ms); }
504
+ std::unique_ptr<Channel> connect_channel(const Endpoint& endpoint, const std::function<bool()>& cancelled) { return std::make_unique<PipeChannel>(endpoint, cancelled); }
354
505
  uint32_t process_id() { return GetCurrentProcessId(); }
355
506
  void release_resource(uintptr_t resource) { if (resource) CloseHandle(reinterpret_cast<HANDLE>(resource)); }
356
507
  uint64_t resource_bytes(uintptr_t) { return 0; }
357
- bool resource_dimensions(uintptr_t resource, uint32_t width, uint32_t height, uint32_t stride, std::string& diagnostic, std::string& adapter, bool* keyed_mutex) {
508
+ bool source_ready(ID3D11Texture2D* texture, std::chrono::steady_clock::time_point deadline, std::string& diagnostic);
509
+ /**
510
+ * Open a producer frame on the validation device of its adapter and check its description. The texture stays open
511
+ * in `texture`, also when the description is invalid. While the producer renders, a keyed-mutex frame released
512
+ * without taking key 0, or opened a second time, stays charged to this process's GPU memory after release; callers
513
+ * take key 0 on this open and never open the frame again.
514
+ */
515
+ bool open_frame(uintptr_t resource, uint32_t width, uint32_t height, uint32_t stride, std::string& diagnostic,
516
+ std::string& adapter, bool* keyed_mutex, ComPtr<ID3D11Texture2D>& texture) {
358
517
  const auto failed = [&](const char* operation, HRESULT result) {
359
518
  std::ostringstream text; text << operation << " HRESULT=0x" << std::hex << static_cast<uint32_t>(result);
360
519
  if (!adapter.empty()) text << " adapter=" << adapter;
@@ -383,7 +542,6 @@ bool resource_dimensions(uintptr_t resource, uint32_t width, uint32_t height, ui
383
542
  if (FAILED(result)) return failed("D3D11.1 receiver unavailable", result);
384
543
  validation_device = device1.Detach();
385
544
  }
386
- ComPtr<ID3D11Texture2D> texture;
387
545
  auto result = validation_device->OpenSharedResource1(reinterpret_cast<HANDLE>(resource), IID_PPV_ARGS(&texture));
388
546
  if (FAILED(result)) return failed("Shared texture is incompatible with receiver GPU", result);
389
547
  D3D11_TEXTURE2D_DESC desc{}; texture->GetDesc(&desc);
@@ -391,13 +549,21 @@ bool resource_dimensions(uintptr_t resource, uint32_t width, uint32_t height, ui
391
549
  const bool valid = desc.Width == width && desc.Height == height && desc.Format == DXGI_FORMAT_B8G8R8A8_UNORM &&
392
550
  stride == width * 4 && desc.MipLevels == 1 && desc.ArraySize == 1 && desc.SampleDesc.Count == 1 && (desc.MiscFlags & D3D11_RESOURCE_MISC_SHARED_NTHANDLE);
393
551
  if (!valid) diagnostic = "Shared D3D11 texture format, dimensions or sharing flags differ; adapter=" + adapter;
552
+ return valid;
553
+ }
554
+ bool resource_dimensions(uintptr_t resource, uint32_t width, uint32_t height, uint32_t stride,
555
+ std::chrono::steady_clock::time_point deadline, std::string& diagnostic, std::string& adapter, bool* keyed_mutex) {
556
+ ComPtr<ID3D11Texture2D> texture;
557
+ bool valid = open_frame(resource, width, height, stride, diagnostic, adapter, keyed_mutex, texture);
558
+ if (!texture) return false;
559
+ std::string synchronization;
560
+ if (!source_ready(texture.Get(), deadline, synchronization) && valid) { diagnostic = synchronization; valid = false; }
394
561
  texture.Reset();
395
562
  // This context submits no GPU work; Flush retires released validation textures.
396
563
  ComPtr<ID3D11DeviceContext> reclamation;
397
564
  validation_device->GetImmediateContext(&reclamation);
398
565
  reclamation->Flush();
399
566
  return valid;
400
-
401
567
  }
402
568
  #include "relay-transport.inc"
403
569
  #endif