@deepseek-ai/libreoffice-kit 0.1.4 → 0.2.0-alpha5

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 (79) hide show
  1. package/NOTICE +4 -0
  2. package/README.md +49 -9
  3. package/README.zh.md +50 -10
  4. package/lib/cli.js +155 -52
  5. package/lib/editor.js +2061 -0
  6. package/lib/index.js +155 -52
  7. package/lib/types/editor-protocol.d.ts +29 -0
  8. package/lib/types/editor-transport.d.ts +36 -0
  9. package/lib/types/editor-types.d.ts +119 -0
  10. package/lib/types/editor.d.ts +105 -0
  11. package/lib/types/engine.d.ts +4 -2
  12. package/lib/types/fonts.d.ts +4 -8
  13. package/lib/types/native-image-renderer.d.ts +0 -1
  14. package/lib/types/native-process.d.ts +1 -0
  15. package/lib/types/native.d.ts +31 -2
  16. package/lib/types/rendering.d.ts +2 -0
  17. package/lib/types/runtime.d.ts +2 -0
  18. package/lib/types/sheet-geometry.d.ts +1 -1
  19. package/lib/types/worker.d.ts +2 -2
  20. package/lib/worker.js +51 -32
  21. package/native-render/CMakeLists.txt +40 -0
  22. package/native-render/LICENSE +21 -0
  23. package/native-render/README.md +83 -0
  24. package/native-render/README.zh.md +83 -0
  25. package/native-render/include/dsh_render.h +101 -0
  26. package/native-render/include/dsh_render_engine.h +66 -0
  27. package/native-render/include/dsh_render_node.h +27 -0
  28. package/native-render/include/dsh_webgpu.h +52 -0
  29. package/native-render/index.d.ts +145 -0
  30. package/native-render/index.mjs +71 -0
  31. package/native-render/lib/browser/display.d.ts +46 -0
  32. package/native-render/lib/browser/display.js +128 -0
  33. package/native-render/lib/browser/index.d.ts +4 -0
  34. package/native-render/lib/browser/index.js +3 -0
  35. package/native-render/lib/browser/painters.d.ts +9 -0
  36. package/native-render/lib/browser/painters.js +180 -0
  37. package/native-render/lib/browser/types.d.ts +51 -0
  38. package/native-render/lib/browser/types.js +1 -0
  39. package/native-render/lib/electron/adapter.d.ts +9 -0
  40. package/native-render/lib/electron/adapter.js +118 -0
  41. package/native-render/lib/electron/index.d.ts +3 -0
  42. package/native-render/lib/electron/index.js +3 -0
  43. package/native-render/lib/electron/preload.d.ts +13 -0
  44. package/native-render/lib/electron/preload.js +47 -0
  45. package/native-render/lib/electron/transfer.d.ts +15 -0
  46. package/native-render/lib/electron/transfer.js +36 -0
  47. package/native-render/prebuilds/darwin-arm64/libdsh_render_sdk.a +0 -0
  48. package/native-render/prebuilds/darwin-arm64/manifest.json +34 -0
  49. package/native-render/prebuilds/darwin-arm64/render.node +0 -0
  50. package/native-render/prebuilds/darwin-x64/libdsh_render_sdk.a +0 -0
  51. package/native-render/prebuilds/darwin-x64/manifest.json +34 -0
  52. package/native-render/prebuilds/darwin-x64/render.node +0 -0
  53. package/native-render/prebuilds/win32-arm64/dsh_render_sdk.lib +0 -0
  54. package/native-render/prebuilds/win32-arm64/manifest.json +34 -0
  55. package/native-render/prebuilds/win32-arm64/render.node +0 -0
  56. package/native-render/prebuilds/win32-x64/dsh_render_sdk.lib +0 -0
  57. package/native-render/prebuilds/win32-x64/manifest.json +34 -0
  58. package/native-render/prebuilds/win32-x64/render.node +0 -0
  59. package/native-render/receipt.json +23 -0
  60. package/native-render/scripts/build-webgpu.mjs +197 -0
  61. package/native-render/scripts/build.mjs +43 -0
  62. package/native-render/scripts/metadata.mjs +47 -0
  63. package/native-render/scripts/source-identity.mjs +15 -0
  64. package/native-render/scripts/verify-prebuilds.mjs +14 -0
  65. package/native-render/sdk.json +45 -0
  66. package/native-render/src/node-producer.cc +595 -0
  67. package/native-render/src/producer-internal.h +8 -0
  68. package/native-render/src/producer.cc +306 -0
  69. package/native-render/src/receiver.cc +1050 -0
  70. package/native-render/src/relay-transport.inc +293 -0
  71. package/native-render/src/transport.cc +405 -0
  72. package/native-render/src/transport.h +80 -0
  73. package/native-render/src/webgpu.cc +214 -0
  74. package/native-render/src/win-delay-load.LICENSE +24 -0
  75. package/native-render/src/win-delay-load.cc +43 -0
  76. package/native-render/verify.d.mts +4 -0
  77. package/native-render/verify.mjs +101 -0
  78. package/native-render/webgpu-dependencies.json +51 -0
  79. package/package.json +97 -11
@@ -0,0 +1,405 @@
1
+ #include "transport.h"
2
+ #include <algorithm>
3
+ #include <cstring>
4
+ #include <sstream>
5
+ #include <stdexcept>
6
+ #include <vector>
7
+ #include <chrono>
8
+ #if defined(__APPLE__)
9
+ #include <CoreFoundation/CoreFoundation.h>
10
+ #include <IOSurface/IOSurface.h>
11
+ #include <bsm/libbsm.h>
12
+ #include <mach/mach.h>
13
+ #include <mach/notify.h>
14
+ #include <servers/bootstrap.h>
15
+ #include <unistd.h>
16
+ #else
17
+ #define NOMINMAX
18
+ #include <windows.h>
19
+ #include <sddl.h>
20
+ #include <d3d11_4.h>
21
+ #include <dxgi1_2.h>
22
+ #include <wrl/client.h>
23
+ #endif
24
+ namespace dsh_render {
25
+ Endpoint parse_endpoint(const std::string& value) {
26
+ auto a = value.find('|'), b = value.find('|', a + 1), c = value.find('|', b + 1);
27
+ 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
+ auto pid_text = value.substr(a + 1, b - a - 1);
30
+ size_t used = 0;
31
+ auto pid = std::stoul(pid_text, &used);
32
+ Endpoint result{static_cast<uint32_t>(pid), value.substr(b + 1, c - b - 1), value.substr(c + 1)};
33
+ 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
+ return result;
36
+ }
37
+ #if defined(__APPLE__)
38
+ struct MachMessage {
39
+ mach_msg_header_t header;
40
+ mach_msg_body_t body;
41
+ mach_msg_port_descriptor_t port;
42
+ Packet packet;
43
+ mach_msg_audit_trailer_t trailer;
44
+ };
45
+ class MachChannel final : public Channel {
46
+ mach_port_t local_ = MACH_PORT_NULL, remote_ = MACH_PORT_NULL;
47
+ Endpoint endpoint_;
48
+ bool server_;
49
+ std::atomic<bool> stopped_{false};
50
+ std::atomic<uint32_t> peer_{0};
51
+ 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
+ void watch_peer() {
73
+ mach_port_t previous = MACH_PORT_NULL;
74
+ auto result = mach_port_request_notification(mach_task_self(), remote_, MACH_NOTIFY_DEAD_NAME, 0, local_, MACH_MSG_TYPE_MAKE_SEND_ONCE, &previous);
75
+ if (previous) mach_port_deallocate(mach_task_self(), previous);
76
+ if (result != KERN_SUCCESS) stopped_ = true;
77
+ }
78
+ uint32_t peer_pid() const override { return peer_; }
79
+ void interrupt() override { stopped_ = true; }
80
+ bool send(const Packet& packet, uintptr_t resource) override {
81
+ std::lock_guard<std::mutex> lock(writes_);
82
+ if (stopped_ || !remote_) return false;
83
+ MachMessage msg{};
84
+ msg.header.msgh_bits = MACH_MSGH_BITS(MACH_MSG_TYPE_COPY_SEND, 0) | MACH_MSGH_BITS_COMPLEX;
85
+ msg.header.msgh_size = offsetof(MachMessage, trailer);
86
+ msg.header.msgh_remote_port = remote_;
87
+ msg.header.msgh_id = magic;
88
+ msg.body.msgh_descriptor_count = 1;
89
+ msg.port.type = MACH_MSG_PORT_DESCRIPTOR;
90
+ msg.port.disposition = MACH_MSG_TYPE_COPY_SEND;
91
+ mach_port_t surface_port = MACH_PORT_NULL;
92
+ if (packet.kind == hello) msg.port.name = local_;
93
+ else if (resource) msg.port.name = surface_port = IOSurfaceCreateMachPort(reinterpret_cast<IOSurfaceRef>(resource));
94
+ msg.packet = packet;
95
+ 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
+ if (surface_port) mach_port_deallocate(mach_task_self(), surface_port);
97
+ return result == KERN_SUCCESS;
98
+ }
99
+ int receive(Received& out, uint32_t timeout) override {
100
+ 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();
117
+ } else if (out.packet.kind == frame && msg.port.name) {
118
+ out.resource = reinterpret_cast<uintptr_t>(IOSurfaceLookupFromMachPort(msg.port.name));
119
+ }
120
+ 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
+ return 1;
124
+ }
125
+ };
126
+ std::unique_ptr<Channel> listen_channel(Endpoint& endpoint) { return std::make_unique<MachChannel>(endpoint, true); }
127
+ 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);
130
+ }
131
+ uint32_t process_id() { return getpid(); }
132
+ void clear_validation_device() {}
133
+ std::string resource_adapter(uintptr_t) { return "IOSurface"; }
134
+ std::string device_adapter(void*) { return "IOSurface"; }
135
+ void release_resource(uintptr_t resource) { if (resource) CFRelease(reinterpret_cast<IOSurfaceRef>(resource)); }
136
+ 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) {
138
+ if (keyed_mutex) *keyed_mutex = false;
139
+ diagnostic = "IOSurface format or dimensions differ"; adapter = "IOSurface";
140
+ auto surface = reinterpret_cast<IOSurfaceRef>(resource);
141
+ return surface && IOSurfaceGetWidth(surface) == width && IOSurfaceGetHeight(surface) == height &&
142
+ IOSurfaceGetBytesPerRow(surface) == stride && IOSurfaceGetBytesPerElement(surface) == 4 && IOSurfaceGetPixelFormat(surface) == 0x42475241;
143
+ }
144
+ #else
145
+ using Microsoft::WRL::ComPtr;
146
+ HANDLE create_deadline_timer() {
147
+ // The SDK also compiles with Windows 8 target headers, which omit this flag.
148
+ constexpr DWORD high_resolution_timer = 0x00000002;
149
+ auto timer = CreateWaitableTimerExW(nullptr, nullptr, high_resolution_timer, TIMER_MODIFY_STATE | SYNCHRONIZE);
150
+ if (!timer && GetLastError() == ERROR_INVALID_PARAMETER)
151
+ timer = CreateWaitableTimerExW(nullptr, nullptr, 0, TIMER_MODIFY_STATE | SYNCHRONIZE);
152
+ return timer;
153
+ }
154
+ struct ReadbackSync {
155
+ ComPtr<ID3D11Fence> fence;
156
+ ComPtr<ID3D11DeviceContext4> signaling;
157
+ ComPtr<ID3D11Query> query;
158
+ HANDLE event = nullptr;
159
+ uint64_t value = 0;
160
+ bool pending = false, fence_submitted = false, event_armed = false;
161
+ ~ReadbackSync() { if (event) CloseHandle(event); }
162
+ };
163
+ bool gpu_failure(std::string& diagnostic, const char* operation, HRESULT result) {
164
+ std::ostringstream text; text << operation << " HRESULT=0x" << std::hex << static_cast<uint32_t>(result);
165
+ diagnostic = text.str(); return false;
166
+ }
167
+ bool finish_gpu_submission(ID3D11DeviceContext* context, ReadbackSync& sync, std::string& diagnostic) {
168
+ // The query remains valid when fence submission or notification fails after a copy.
169
+ context->End(sync.query.Get());
170
+ sync.pending = true; sync.fence_submitted = false; sync.event_armed = false;
171
+ HRESULT result = S_OK;
172
+ const char* operation = "Cannot signal GPU completion";
173
+ if (sync.fence) {
174
+ result = sync.signaling->Signal(sync.fence.Get(), ++sync.value);
175
+ if (SUCCEEDED(result)) {
176
+ sync.fence_submitted = true;
177
+ operation = "Cannot arm GPU completion event";
178
+ result = sync.fence->SetEventOnCompletion(sync.value, sync.event);
179
+ sync.event_armed = SUCCEEDED(result);
180
+ }
181
+ }
182
+ context->Flush();
183
+ return SUCCEEDED(result) || gpu_failure(diagnostic, operation, result);
184
+ }
185
+ // Pending=0, completed=1, device removed=2; other errors retain ownership.
186
+ int poll_gpu_submission(ID3D11Device* device, ID3D11DeviceContext* context,
187
+ ReadbackSync& sync, bool retiring, std::string& diagnostic) {
188
+ if (!sync.pending) return 1;
189
+ if (retiring && FAILED(device->GetDeviceRemovedReason())) { sync.pending = false; return 2; }
190
+ if (sync.fence_submitted) {
191
+ const auto completed = sync.fence->GetCompletedValue();
192
+ if (completed == UINT64_MAX) { sync.pending = false; gpu_failure(diagnostic, "GPU device removed", DXGI_ERROR_DEVICE_REMOVED); return 2; }
193
+ if (completed >= sync.value) { sync.pending = false; return 1; }
194
+ return 0;
195
+ }
196
+ const auto result = context->GetData(sync.query.Get(), nullptr, 0, D3D11_ASYNC_GETDATA_DONOTFLUSH);
197
+ if (result == S_OK) { sync.pending = false; return 1; }
198
+ if (FAILED(device->GetDeviceRemovedReason())) { sync.pending = false; gpu_failure(diagnostic, "GPU device removed", DXGI_ERROR_DEVICE_REMOVED); return 2; }
199
+ if (result == S_FALSE) return 0;
200
+ gpu_failure(diagnostic, "Cannot query GPU completion", result); return -1;
201
+ }
202
+ uintptr_t create_gpu_retry_timer() { return reinterpret_cast<uintptr_t>(create_deadline_timer()); }
203
+ thread_local ID3D11Device1* validation_device = nullptr;
204
+ void clear_validation_device() {
205
+ if (validation_device) { validation_device->Release(); validation_device = nullptr; }
206
+ }
207
+ std::string adapter_id(LUID luid) {
208
+ std::ostringstream id; id << std::hex << static_cast<uint32_t>(luid.HighPart) << ':' << luid.LowPart;
209
+ return id.str();
210
+ }
211
+ std::string device_adapter(void* device) {
212
+ if (!device) return {};
213
+ ComPtr<IDXGIDevice> dxgi; ComPtr<IDXGIAdapter> adapter; DXGI_ADAPTER_DESC desc{};
214
+ if (FAILED(static_cast<ID3D11Device*>(device)->QueryInterface(IID_PPV_ARGS(&dxgi))) ||
215
+ FAILED(dxgi->GetAdapter(&adapter)) || FAILED(adapter->GetDesc(&desc))) return {};
216
+ return adapter_id(desc.AdapterLuid);
217
+ }
218
+ std::string resource_adapter(uintptr_t resource) {
219
+ ComPtr<IDXGIFactory2> factory; LUID luid{};
220
+ if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&factory))) ||
221
+ FAILED(factory->GetSharedResourceAdapterLuid(reinterpret_cast<HANDLE>(resource), &luid))) return {};
222
+ return adapter_id(luid);
223
+ }
224
+ class PipeChannel final : public Channel {
225
+ HANDLE pipe_ = INVALID_HANDLE_VALUE, stop_ = nullptr, deadline_ = nullptr;
226
+ bool server_, connected_ = false;
227
+ Endpoint endpoint_;
228
+ std::atomic<uint32_t> peer_{0};
229
+ 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;
258
+ }
259
+ 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);
262
+ 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)) {
283
+ const auto error = GetLastError();
284
+ if (cancelled && cancelled()) throw std::runtime_error("Native render connection cancelled or timed out");
285
+ if (!cancelled || (error != ERROR_SEM_TIMEOUT && error != ERROR_PIPE_BUSY))
286
+ throw std::runtime_error("Native render receiver unavailable");
287
+ }
288
+ pipe_ = CreateFileA(endpoint_.name.c_str(), GENERIC_READ | GENERIC_WRITE, 0, nullptr, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, nullptr);
289
+ DWORD mode = PIPE_READMODE_MESSAGE; SetNamedPipeHandleState(pipe_, &mode, nullptr, nullptr);
290
+ 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
+ }
303
+ }
304
+ ~PipeChannel() override { interrupt(); if (pipe_ != INVALID_HANDLE_VALUE) CloseHandle(pipe_); if (stop_) CloseHandle(stop_); if (deadline_) CloseHandle(deadline_); }
305
+ 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 {
308
+ std::lock_guard<std::mutex> lock(writes_);
309
+ if (!connected_ || WaitForSingleObject(stop_, 0) == WAIT_OBJECT_0) return false;
310
+ Packet packet = source;
311
+ HANDLE remote_handle = nullptr, target = nullptr;
312
+ if (resource) {
313
+ target = OpenProcess(PROCESS_DUP_HANDLE, FALSE, peer_);
314
+ if (!target || !DuplicateHandle(GetCurrentProcess(), reinterpret_cast<HANDLE>(resource), target, &remote_handle, 0, FALSE, DUPLICATE_SAME_ACCESS)) {
315
+ if (target) CloseHandle(target); return false;
316
+ }
317
+ packet.resource = reinterpret_cast<uintptr_t>(remote_handle);
318
+ }
319
+ OVERLAPPED operation{}; operation.hEvent = CreateEventW(nullptr, TRUE, FALSE, nullptr); DWORD count = 0;
320
+ bool ok = WriteFile(pipe_, &packet, sizeof(packet), &count, &operation) != FALSE;
321
+ if (!ok && GetLastError() == ERROR_IO_PENDING) ok = wait(operation, INFINITE, count);
322
+ CloseHandle(operation.hEvent);
323
+ if (!ok && remote_handle) {
324
+ HANDLE reclaimed = nullptr;
325
+ if (DuplicateHandle(target, remote_handle, GetCurrentProcess(), &reclaimed, 0, FALSE, DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS)) CloseHandle(reclaimed);
326
+ }
327
+ if (target) CloseHandle(target);
328
+ return ok && count == sizeof(packet);
329
+ }
330
+ int receive(Received& out, uint32_t timeout) override {
331
+ if (WaitForSingleObject(stop_, 0) == WAIT_OBJECT_0) return -1;
332
+ 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;
348
+ out.pid = peer_; out.resource = static_cast<uintptr_t>(out.packet.resource);
349
+ return 1;
350
+ }
351
+ };
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); }
354
+ uint32_t process_id() { return GetCurrentProcessId(); }
355
+ void release_resource(uintptr_t resource) { if (resource) CloseHandle(reinterpret_cast<HANDLE>(resource)); }
356
+ 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) {
358
+ const auto failed = [&](const char* operation, HRESULT result) {
359
+ std::ostringstream text; text << operation << " HRESULT=0x" << std::hex << static_cast<uint32_t>(result);
360
+ if (!adapter.empty()) text << " adapter=" << adapter;
361
+ diagnostic = text.str(); return false;
362
+ };
363
+ adapter = resource_adapter(resource);
364
+ if (adapter.empty()) return failed("Cannot identify shared texture adapter", E_INVALIDARG);
365
+ if (validation_device && device_adapter(validation_device) != adapter) clear_validation_device();
366
+ if (!validation_device) {
367
+ ComPtr<IDXGIFactory1> factory; ComPtr<IDXGIAdapter1> selected;
368
+ auto result = CreateDXGIFactory1(IID_PPV_ARGS(&factory));
369
+ if (FAILED(result)) return failed("Cannot enumerate shared texture adapters", result);
370
+ for (UINT index = 0; ; ++index) {
371
+ ComPtr<IDXGIAdapter1> candidate;
372
+ result = factory->EnumAdapters1(index, &candidate);
373
+ if (result == DXGI_ERROR_NOT_FOUND) break;
374
+ if (FAILED(result)) return failed("Cannot enumerate shared texture adapters", result);
375
+ DXGI_ADAPTER_DESC1 desc{};
376
+ if (SUCCEEDED(candidate->GetDesc1(&desc)) && adapter_id(desc.AdapterLuid) == adapter) { selected = candidate; break; }
377
+ }
378
+ if (!selected) return failed("Shared texture adapter is unavailable", DXGI_ERROR_NOT_FOUND);
379
+ ComPtr<ID3D11Device> device; ComPtr<ID3D11Device1> device1;
380
+ result = D3D11CreateDevice(selected.Get(), D3D_DRIVER_TYPE_UNKNOWN, nullptr, D3D11_CREATE_DEVICE_BGRA_SUPPORT, nullptr, 0, D3D11_SDK_VERSION, &device, nullptr, nullptr);
381
+ if (FAILED(result)) return failed("D3D11 hardware receiver unavailable", result);
382
+ result = device.As(&device1);
383
+ if (FAILED(result)) return failed("D3D11.1 receiver unavailable", result);
384
+ validation_device = device1.Detach();
385
+ }
386
+ ComPtr<ID3D11Texture2D> texture;
387
+ auto result = validation_device->OpenSharedResource1(reinterpret_cast<HANDLE>(resource), IID_PPV_ARGS(&texture));
388
+ if (FAILED(result)) return failed("Shared texture is incompatible with receiver GPU", result);
389
+ D3D11_TEXTURE2D_DESC desc{}; texture->GetDesc(&desc);
390
+ if (keyed_mutex) *keyed_mutex = (desc.MiscFlags & D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX) != 0;
391
+ const bool valid = desc.Width == width && desc.Height == height && desc.Format == DXGI_FORMAT_B8G8R8A8_UNORM &&
392
+ stride == width * 4 && desc.MipLevels == 1 && desc.ArraySize == 1 && desc.SampleDesc.Count == 1 && (desc.MiscFlags & D3D11_RESOURCE_MISC_SHARED_NTHANDLE);
393
+ if (!valid) diagnostic = "Shared D3D11 texture format, dimensions or sharing flags differ; adapter=" + adapter;
394
+ texture.Reset();
395
+ // This context submits no GPU work; Flush retires released validation textures.
396
+ ComPtr<ID3D11DeviceContext> reclamation;
397
+ validation_device->GetImmediateContext(&reclamation);
398
+ reclamation->Flush();
399
+ return valid;
400
+
401
+ }
402
+ #include "relay-transport.inc"
403
+ #endif
404
+ uintptr_t receive_resource(Received& received) { auto resource = received.resource; received.resource = 0; return resource; }
405
+ }
@@ -0,0 +1,80 @@
1
+ #pragma once
2
+ #include <atomic>
3
+ #include <cstdint>
4
+ #include <memory>
5
+ #include <mutex>
6
+ #include <string>
7
+ #include <vector>
8
+ #include <functional>
9
+ #include <chrono>
10
+ #include "dsh_render.h"
11
+ namespace dsh_render {
12
+ constexpr uint32_t magic = 0x44535231;
13
+ enum Kind : uint32_t { hello = 1, ready, frame, release, message, goodbye, allocate, allocated, deallocate };
14
+ /** hello.max_frames carries optional capabilities; zero is the legacy producer. */
15
+ constexpr uint32_t hello_keyed_mutex = 1;
16
+ struct Packet {
17
+ uint32_t marker = magic, version = DSH_RENDER_PROTOCOL_VERSION, kind = 0;
18
+ uint32_t width = 0, height = 0, stride = 0, max_frames = 0;
19
+ uint64_t frame_id = 0, allocation_id = 0, max_bytes = 0, resource = 0;
20
+ char token[65] = {};
21
+ char text[DSH_RENDER_TEXT_CAPACITY] = {};
22
+ };
23
+ struct Received { Packet packet; uint32_t pid = 0; uintptr_t resource = 0; };
24
+ /** A private single-peer channel. receive returns 1 data, 0 timeout, -1 closed/error. */
25
+ class Channel {
26
+ public:
27
+ virtual ~Channel() = default;
28
+ virtual int receive(Received&, uint32_t timeout_ms) = 0;
29
+ virtual bool send(const Packet&, uintptr_t resource = 0) = 0;
30
+ virtual void interrupt() = 0;
31
+ virtual uint32_t peer_pid() const = 0;
32
+ };
33
+ struct Endpoint { uint32_t pid; std::string token, name; };
34
+ Endpoint parse_endpoint(const std::string& value);
35
+ std::unique_ptr<Channel> listen_channel(Endpoint& endpoint);
36
+ std::unique_ptr<Channel> connect_channel(const Endpoint& endpoint, const std::function<bool()>& cancelled = {});
37
+ uint32_t process_id();
38
+ uintptr_t receive_resource(Received& received);
39
+ void release_resource(uintptr_t resource);
40
+ void clear_validation_device();
41
+ uint64_t resource_bytes(uintptr_t resource);
42
+ bool resource_dimensions(uintptr_t resource, uint32_t width, uint32_t height, uint32_t stride, std::string& diagnostic, std::string& adapter, bool* keyed_mutex = nullptr);
43
+ /** Adapter owning a shared resource, or an empty string when it cannot be identified. */
44
+ std::string resource_adapter(uintptr_t resource);
45
+ /** Adapter owning the producer's graphics device. */
46
+ std::string device_adapter(void* device);
47
+ #if defined(_WIN32)
48
+ /** Bounded source readiness check before Chromium's unbounded key-0 acquisition. */
49
+ bool resource_ready(uintptr_t resource, std::chrono::steady_clock::time_point deadline, std::string& diagnostic);
50
+ struct RelayDevice;
51
+ struct RelayTexture;
52
+ struct RelayReadback;
53
+ uintptr_t relay_handle(const std::shared_ptr<RelayTexture>& texture);
54
+ bool relay_begin(uintptr_t resource, uint32_t width, uint32_t height,
55
+ const std::string& adapter, std::chrono::steady_clock::time_point deadline, const std::atomic<bool>& stopped,
56
+ std::shared_ptr<RelayDevice>& display, std::shared_ptr<RelayTexture>& slot, std::string& diagnostic);
57
+ int relay_advance(const std::shared_ptr<RelayTexture>& slot, const std::atomic<bool>& stopped,
58
+ std::chrono::steady_clock::time_point deadline, std::string& diagnostic);
59
+ uintptr_t relay_completion_event(const std::shared_ptr<RelayTexture>& slot);
60
+ /** True only after every submitted copy completes or its device is removed. */
61
+ bool relay_gpu_idle(const std::shared_ptr<RelayTexture>& slot, std::string& diagnostic);
62
+ bool relay_readback_begin(uintptr_t resource, uint32_t width, uint32_t height,
63
+ std::shared_ptr<RelayReadback>& slot, std::string& diagnostic,
64
+ std::chrono::steady_clock::time_point deadline);
65
+ int relay_readback_ready(const std::shared_ptr<RelayReadback>& slot, bool retiring, std::string& diagnostic);
66
+ uintptr_t relay_readback_event(const std::shared_ptr<RelayReadback>& slot);
67
+ int relay_upload(const std::shared_ptr<RelayReadback>& source, uint32_t width, uint32_t height,
68
+ const std::string& adapter, std::shared_ptr<RelayDevice>& display, std::shared_ptr<RelayTexture>& target,
69
+ std::chrono::steady_clock::time_point deadline, const std::atomic<bool>& stopped, std::string& diagnostic);
70
+ uintptr_t create_gpu_retry_timer();
71
+ /** Borrowed device; the relay image retains its lifetime. */
72
+ void* relay_output_device(const std::shared_ptr<RelayTexture>& texture);
73
+ void relay_forget_source(const std::shared_ptr<RelayTexture>& texture);
74
+ /** Copy the retained image and signal its existing completion fence. */
75
+ bool relay_copy_output(const std::shared_ptr<RelayTexture>& texture, void* destination, std::string& diagnostic);
76
+ bool relay_readback_image(const std::shared_ptr<RelayTexture>& texture, std::shared_ptr<RelayReadback>& staging, std::string& diagnostic);
77
+ int relay_with_pixels(const std::shared_ptr<RelayReadback>& staging,
78
+ const std::function<bool(const uint8_t*, uint32_t)>& consume, std::string& diagnostic);
79
+ #endif
80
+ }