@deepseek-ai/libreoffice-kit 0.2.0 → 0.2.3-rc.3

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 (47) hide show
  1. package/NOTICE +1 -1
  2. package/README.md +5 -5
  3. package/README.zh.md +5 -5
  4. package/frame-forwarding/CMakeLists.txt +3 -4
  5. package/frame-forwarding/README.md +21 -17
  6. package/frame-forwarding/README.zh.md +22 -18
  7. package/frame-forwarding/include/dsh_frame_forwarding.h +42 -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 +23 -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 +23 -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 +23 -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 +23 -21
  22. package/frame-forwarding/receipt.json +16 -14
  23. package/frame-forwarding/scripts/build-webgpu.mjs +1 -0
  24. package/frame-forwarding/scripts/build.mjs +3 -3
  25. package/frame-forwarding/scripts/metadata.mjs +12 -8
  26. package/frame-forwarding/scripts/source-identity.mjs +3 -3
  27. package/frame-forwarding/sdk.json +7 -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 +120 -30
  32. package/frame-forwarding/src/receiver.cc +422 -212
  33. package/frame-forwarding/src/relay-transport.inc +38 -10
  34. package/frame-forwarding/src/transport.cc +328 -155
  35. package/frame-forwarding/src/transport.h +73 -9
  36. package/frame-forwarding/verify.d.mts +1 -1
  37. package/frame-forwarding/verify.mjs +19 -17
  38. package/lib/cli.js +6 -6
  39. package/lib/editor.js +15 -10
  40. package/lib/index.js +6 -6
  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/worker.js +3 -2
  45. package/package.json +8 -10
  46. package/frame-forwarding/include/dsh_frame_forwarding_engine.h +0 -66
  47. package/frame-forwarding/include/dsh_frame_forwarding_node.h +0 -27
@@ -1,12 +1,10 @@
1
1
  #if defined(_WIN32)
2
+ // uv.h includes <windows.h>, whose min and max macros would replace std::min and time_point::max.
2
3
  #define NOMINMAX
3
- #define WIN32_LEAN_AND_MEAN
4
- #include <windows.h>
5
- #include <dxgi.h>
6
4
  #endif
7
5
  #include "dsh_frame_forwarding.h"
8
- #include "dsh_frame_forwarding_node.h"
9
6
  #include "producer-internal.h"
7
+ #include <node_api.h>
10
8
  #include <uv.h>
11
9
  #include <algorithm>
12
10
  #include <atomic>
@@ -37,17 +35,19 @@ struct Surface {
37
35
  uint32_t width, height;
38
36
  std::atomic<SurfaceState> state{SurfaceState::acquired};
39
37
  };
40
- enum class Kind { acquire, write, render, submit, discard, send, start, update, stop };
38
+ /** Producer commands by their JavaScript code; code 5 is a latest-frame submit. */
39
+ enum class Kind { acquire = 0, write = 1, submit = 2, discard = 3, send = 4 };
40
+ constexpr uint64_t submit_latest_command = 5;
41
41
  struct Job {
42
42
  Kind kind;
43
43
  napi_deferred deferred = nullptr;
44
44
  napi_ref buffer = nullptr;
45
45
  const void* pixels = nullptr;
46
46
  size_t stride = 0;
47
- uint32_t width = 0, height = 0, generation = 0;
48
- double interval = 0;
49
- uint64_t frame_id = 0, input_sequence = 0;
50
- bool restore_lease = false;
47
+ uint32_t width = 0, height = 0;
48
+ uint64_t frame_id = 0;
49
+ // A submission through dsh_frame_forwarding_submit_latest.
50
+ bool restore_lease = false, latest = false;
51
51
  std::string text;
52
52
  std::shared_ptr<Surface> surface;
53
53
  Clock::time_point deadline;
@@ -61,7 +61,6 @@ struct Producer : std::enable_shared_from_this<Producer> {
61
61
  napi_env env;
62
62
  napi_threadsafe_function callback = nullptr;
63
63
  napi_deferred ready = nullptr, closed = nullptr;
64
- napi_ref engine_reference = nullptr;
65
64
  napi_async_cleanup_hook_handle cleanup = nullptr;
66
65
  uv_async_t done{};
67
66
  bool environment_closing = false, main_released = false, delivered = false, closing_handle = false;
@@ -77,17 +76,9 @@ struct Producer : std::enable_shared_from_this<Producer> {
77
76
  std::map<dsh_frame_forwarding_surface*, std::shared_ptr<Surface>> surfaces;
78
77
  size_t pending = 0;
79
78
  uint32_t max_pending, timeout_ms;
80
- std::string endpoint;
79
+ /** TX credential of the channel this producer connects to. */
80
+ std::string tx;
81
81
  dsh_frame_forwarding_client* client = nullptr;
82
- const dsh_frame_forwarding_engine_v1* factory = nullptr;
83
- const dsh_frame_forwarding_engine_v2* changing_factory = nullptr;
84
- void* engine = nullptr;
85
- bool streaming = false;
86
- bool frame_pending = false, prepare_pending = false;
87
- uint32_t width = 0, height = 0, generation = 0;
88
- double interval = 0;
89
- uint64_t next_frame = 1, input_sequence = 0;
90
- Clock::time_point created = Clock::now(), next_tick, next_prepare, render_deadline;
91
82
 
92
83
  void interrupt() {
93
84
  { std::lock_guard<std::mutex> lock(mutex); stopped = true; }
@@ -124,53 +115,23 @@ struct Producer : std::enable_shared_from_this<Producer> {
124
115
  emit(delivery);
125
116
  }
126
117
  static int cancelled(void* data) { return static_cast<Producer*>(data)->stopped; }
127
- static int rendering_cancelled(void* data) {
128
- auto self = static_cast<Producer*>(data);
129
- return self->stopped || Clock::now() >= self->render_deadline;
130
- }
131
- void draw(dsh_frame_forwarding_surface* surface, uint32_t w, uint32_t h, uint64_t frame_id) {
132
- if (!factory) throw std::runtime_error("Producer has no native rendering engine");
133
- render_deadline = Clock::now() + std::chrono::milliseconds(timeout_ms);
134
- const dsh_frame_forwarding_target target{dsh_frame_forwarding_surface_native(surface), dsh_frame_forwarding_surface_shared_handle(surface),
135
- dsh_frame_forwarding_device(client), w, h, frame_id, input_sequence,
136
- std::chrono::duration<double>(Clock::now() - created).count(), this, rendering_cancelled};
137
- char error[512]{};
138
- #if defined(_WIN32)
139
- auto keyed = static_cast<IDXGIKeyedMutex*>(dsh_frame_forwarding_surface_keyed_mutex(surface));
140
- if (!keyed || keyed->AcquireSync(0, timeout_ms) != S_OK)
141
- throw std::runtime_error("Native engine target keyed mutex acquisition failed or timed out");
142
- #endif
143
- const auto rendered = factory->render(engine, &target, error, sizeof(error));
144
- #if defined(_WIN32)
145
- if (keyed->ReleaseSync(0) != S_OK)
146
- throw std::runtime_error("Native engine target keyed mutex release failed");
147
- #endif
148
- if (!rendered)
149
- throw std::runtime_error(error[0] ? error : "Native engine rendering failed");
150
- if (rendering_cancelled(this)) throw std::runtime_error("Native engine rendering cancelled or timed out");
151
- }
152
118
  void process(std::unique_ptr<Job> job) {
153
119
  if (Clock::now() >= job->deadline) {
154
120
  if (job->surface && (job->kind == Kind::submit || job->kind == Kind::discard))
155
121
  job->restore_lease = true;
156
122
  complete(std::move(job), "Native producer operation timed out"); return;
157
123
  }
158
- char error[512]{};
159
124
  try {
160
125
  switch (job->kind) {
161
126
  case Kind::acquire:
162
- if (streaming) { complete(std::move(job), "Stop streaming before acquiring a manual surface"); return; }
163
127
  acquisitions.push_back(std::move(job)); return;
164
128
  case Kind::write:
165
129
  if (!dsh_frame_forwarding_write_bgra_with_timeout(job->surface->native, job->pixels, job->stride, timeout_ms))
166
130
  throw std::runtime_error("Native producer CPU upload failed or timed out");
167
131
  break;
168
- case Kind::render:
169
- draw(job->surface->native, job->surface->width, job->surface->height, next_frame); break;
170
132
  case Kind::submit:
171
- if (!dsh_frame_forwarding_submit(client, job->surface->native, job->frame_id, job->text.c_str()))
133
+ if (!(job->latest ? dsh_frame_forwarding_submit_latest : dsh_frame_forwarding_submit)(client, job->surface->native, job->frame_id, job->text.c_str()))
172
134
  throw std::runtime_error("Native producer submission failed");
173
- next_frame = std::max(next_frame, job->frame_id + 1);
174
135
  surfaces.erase(job->surface->native); break;
175
136
  case Kind::discard:
176
137
  dsh_frame_forwarding_discard(client, job->surface->native); surfaces.erase(job->surface->native);
@@ -178,19 +139,6 @@ struct Producer : std::enable_shared_from_this<Producer> {
178
139
  case Kind::send:
179
140
  if (!dsh_frame_forwarding_send(client, job->text.c_str())) throw std::runtime_error("Native producer control send failed");
180
141
  break;
181
- case Kind::start:
182
- if (!factory) { complete(std::move(job), "Producer has no native rendering engine"); return; }
183
- if (!surfaces.empty() || !acquisitions.empty()) { complete(std::move(job), "Release manual surfaces before streaming"); return; }
184
- width = job->width; height = job->height; generation = job->generation; interval = job->interval;
185
- streaming = true; frame_pending = true; prepare_pending = true; next_tick = Clock::now(); break;
186
- case Kind::update:
187
- if (!factory) { complete(std::move(job), "Producer has no native rendering engine"); return; }
188
- if (job->input_sequence < input_sequence) { complete(std::move(job), "Native input sequence moved backwards"); return; }
189
- if (!factory->update(engine, job->text.c_str(), error, sizeof(error)))
190
- throw std::runtime_error(error[0] ? error : "Native engine update failed");
191
- input_sequence = job->input_sequence;
192
- prepare_pending = true; next_tick = Clock::now(); break;
193
- case Kind::stop: streaming = false; break;
194
142
  }
195
143
  complete(std::move(job));
196
144
  } catch (const std::exception& exception) {
@@ -216,45 +164,6 @@ struct Producer : std::enable_shared_from_this<Producer> {
216
164
  complete(std::move(job)); acquisitions.erase(acquisitions.begin());
217
165
  }
218
166
  }
219
- bool changed() {
220
- if (!changing_factory) return true;
221
- render_deadline = Clock::now() + std::chrono::milliseconds(timeout_ms);
222
- const dsh_frame_forwarding_frame_info frame{width, height, input_sequence,
223
- std::chrono::duration<double>(Clock::now() - created).count(), this, rendering_cancelled};
224
- char error[512]{};
225
- const auto result = changing_factory->prepare(engine, &frame, error, sizeof(error));
226
- if (result != 0 && result != 1)
227
- throw std::runtime_error(error[0] ? error : "Native engine frame preparation failed");
228
- if (rendering_cancelled(this)) throw std::runtime_error("Native engine preparation cancelled or timed out");
229
- return result == 1;
230
- }
231
- void advance_tick() {
232
- const auto period = std::chrono::duration_cast<Clock::duration>(std::chrono::duration<double, std::milli>(interval));
233
- next_tick += period;
234
- const auto finished = Clock::now();
235
- // Skip elapsed deadlines without adding a full interval to every GPU completion.
236
- if (next_tick <= finished) next_tick += period * ((finished - next_tick) / period + 1);
237
- }
238
- void tick() {
239
- if (!streaming || Clock::now() < next_tick) return;
240
- if (prepare_pending || Clock::now() >= next_prepare) {
241
- const bool has_changes = changed();
242
- frame_pending = frame_pending || has_changes;
243
- prepare_pending = false;
244
- next_prepare = Clock::now() + std::chrono::duration_cast<Clock::duration>(std::chrono::duration<double, std::milli>(interval));
245
- }
246
- if (!frame_pending) { prepare_pending = true; advance_tick(); return; }
247
- if (!acquisition_ready) return;
248
- auto surface = dsh_frame_forwarding_acquire(client, width, height);
249
- if (!surface) { acquisition_ready = false; return; }
250
- const auto id = next_frame++;
251
- draw(surface, width, height, id);
252
- char metadata[256];
253
- std::snprintf(metadata, sizeof(metadata), "{\"requestId\":\"stream-%llu\",\"generation\":%u,\"revision\":%llu,\"inputSequence\":%llu}",
254
- static_cast<unsigned long long>(id), generation, static_cast<unsigned long long>(id), static_cast<unsigned long long>(input_sequence));
255
- if (!dsh_frame_forwarding_submit(client, surface, id, metadata)) throw std::runtime_error("Native streaming submission failed");
256
- frame_pending = false; prepare_pending = true; advance_tick();
257
- }
258
167
  void poll() {
259
168
  while (!stopped) {
260
169
  {
@@ -276,8 +185,6 @@ struct Producer : std::enable_shared_from_this<Producer> {
276
185
  void wait_for_work() {
277
186
  auto deadline = Clock::time_point::max();
278
187
  for (const auto& job : acquisitions) deadline = std::min(deadline, job->deadline);
279
- if (streaming) deadline = std::min(deadline,
280
- !acquisition_ready && frame_pending ? std::max(next_tick, next_prepare) : next_tick);
281
188
  std::unique_lock<std::mutex> lock(mutex);
282
189
  wake.wait_until(lock, deadline, [&] { return stopped || incoming_ready || !jobs.empty(); });
283
190
  }
@@ -286,12 +193,8 @@ struct Producer : std::enable_shared_from_this<Producer> {
286
193
  std::string failure;
287
194
  try {
288
195
  char error[512]{};
289
- if (factory) {
290
- engine = factory->create(factory->configuration, error, sizeof(error));
291
- if (!engine) throw std::runtime_error(error[0] ? error : "Native engine initialization failed");
292
- }
293
- const dsh_frame_forwarding_connect_options options{factory ? factory->device(engine) : nullptr, timeout_ms, this, cancelled};
294
- auto opened = dsh_frame_forwarding_connect_with_options(endpoint.c_str(), &options, error, sizeof(error));
196
+ const dsh_frame_forwarding_connect_options options{nullptr, timeout_ms, this, cancelled};
197
+ auto opened = dsh_frame_forwarding_connect_with_options(tx.c_str(), &options, error, sizeof(error));
295
198
  if (!opened) throw std::runtime_error(error[0] ? error : "Native producer connection failed");
296
199
  {
297
200
  std::lock_guard<std::mutex> lock(client_mutex); client = opened;
@@ -326,7 +229,7 @@ struct Producer : std::enable_shared_from_this<Producer> {
326
229
  if (!stopped) throw std::runtime_error(event.text[0] ? event.text : "Native receiver disconnected");
327
230
  break;
328
231
  }
329
- acquire_pending(); tick();
232
+ acquire_pending();
330
233
  wait_for_work();
331
234
  }
332
235
  } catch (const std::exception& exception) { failure = exception.what(); }
@@ -344,7 +247,6 @@ struct Producer : std::enable_shared_from_this<Producer> {
344
247
  dsh_frame_forwarding_client* closing_client;
345
248
  { std::lock_guard<std::mutex> lock(client_mutex); closing_client = client; client = nullptr; }
346
249
  if (closing_client) dsh_frame_forwarding_close(closing_client);
347
- if (engine) { factory->destroy(engine); engine = nullptr; }
348
250
  emit(new Delivery{Delivery::closed, nullptr, {}});
349
251
  {
350
252
  std::lock_guard<std::mutex> lock(dispatch_mutex);
@@ -365,7 +267,6 @@ void done_closed(uv_handle_t* handle) {
365
267
  }
366
268
  void abandon_setup(Producer* self, bool handle_initialized) {
367
269
  self->stopped = true; self->ended = true; self->environment_closing = true; self->closing_handle = true;
368
- if (self->engine_reference) { napi_delete_reference(self->env, self->engine_reference); self->engine_reference = nullptr; }
369
270
  if (self->callback) {
370
271
  self->close_dispatcher();
371
272
  }
@@ -376,7 +277,6 @@ void finish_on_main(Producer* self) {
376
277
  if (!self->ended || (!self->delivered && !self->environment_closing) || self->closing_handle) return;
377
278
  self->closing_handle = true;
378
279
  self->worker.join();
379
- if (self->engine_reference) { napi_delete_reference(self->env, self->engine_reference); self->engine_reference = nullptr; }
380
280
  if (!self->environment_closing) {
381
281
  napi_handle_scope scope;
382
282
  if (napi_open_handle_scope(self->env, &scope) == napi_ok) {
@@ -400,7 +300,7 @@ void dispatch(napi_env env, napi_value callback, void* context, void* data) {
400
300
  auto& job = *delivery->job;
401
301
  if (job.kind != Kind::discard) { std::lock_guard<std::mutex> lock(self->mutex); --self->pending; }
402
302
  if (job.buffer) napi_delete_reference(env, job.buffer);
403
- if (job.surface && (job.kind == Kind::write || job.kind == Kind::render)) {
303
+ if (job.surface && job.kind == Kind::write) {
404
304
  auto expected = SurfaceState::busy;
405
305
  job.surface->state.compare_exchange_strong(expected, SurfaceState::acquired);
406
306
  }
@@ -451,31 +351,13 @@ template<typename T> std::shared_ptr<T> external(napi_env env, napi_value value,
451
351
  return *static_cast<std::shared_ptr<T>*>(data);
452
352
  }
453
353
  napi_value create_producer(napi_env env, napi_callback_info info) {
454
- size_t count = 5; napi_value args[5]; napi_get_cb_info(env, info, &count, args, nullptr, nullptr);
354
+ size_t count = 4; napi_value args[4]; napi_get_cb_info(env, info, &count, args, nullptr, nullptr);
455
355
  uint64_t max_pending, timeout; napi_valuetype callback_type;
456
356
  auto self = std::make_shared<Producer>(); self->env = env;
457
- if (count != 5 || !string(env, args[0], self->endpoint, 4096) ||
357
+ if (count != 4 || !string(env, args[0], self->tx, 4096) ||
458
358
  !integer(env, args[1], max_pending, 1, 65536) || !integer(env, args[2], timeout, 1, UINT32_MAX) ||
459
- napi_typeof(env, args[4], &callback_type) != napi_ok || callback_type != napi_function)
359
+ napi_typeof(env, args[3], &callback_type) != napi_ok || callback_type != napi_function)
460
360
  return invalid(env, "Invalid native producer options");
461
- napi_valuetype type; napi_typeof(env, args[3], &type);
462
- if (type != napi_undefined && type != napi_null) {
463
- bool valid = false; void* factory = nullptr;
464
- if (napi_check_object_type_tag(env, args[3], &dsh_frame_forwarding_engine_tag, &valid) != napi_ok || !valid ||
465
- napi_unwrap(env, args[3], &factory) != napi_ok || !factory) return invalid(env, "Expected an exported native rendering engine");
466
- self->factory = static_cast<dsh_frame_forwarding_engine_v1*>(factory);
467
- const bool version_one = self->factory->version == 1 && self->factory->size == sizeof(dsh_frame_forwarding_engine_v1);
468
- const bool version_two = self->factory->version == 2 && self->factory->size == sizeof(dsh_frame_forwarding_engine_v2);
469
- if (!version_one && !version_two) return invalid(env, "Unsupported native rendering engine ABI");
470
- if (!self->factory->create || !self->factory->destroy || !self->factory->device || !self->factory->update || !self->factory->render)
471
- return invalid(env, "Unsupported native rendering engine ABI");
472
- if (version_two) {
473
- self->changing_factory = static_cast<dsh_frame_forwarding_engine_v2*>(factory);
474
- if (!self->changing_factory->prepare) return invalid(env, "Native engine v2 requires prepare");
475
- }
476
- if (napi_create_reference(env, args[3], 1, &self->engine_reference) != napi_ok)
477
- return invalid(env, "Cannot retain native rendering engine");
478
- }
479
361
  self->max_pending = static_cast<uint32_t>(max_pending); self->timeout_ms = static_cast<uint32_t>(timeout);
480
362
  napi_value result, native, ready, closed; napi_create_object(env, &result);
481
363
  napi_create_promise(env, &self->ready, &ready); napi_create_promise(env, &self->closed, &closed);
@@ -484,10 +366,9 @@ napi_value create_producer(napi_env env, napi_callback_info info) {
484
366
  napi_type_tag_object(env, native, &producer_tag);
485
367
  property(env, result, "native", native); property(env, result, "ready", ready); property(env, result, "closed", closed);
486
368
  auto callback_holder = new std::shared_ptr<Producer>(self);
487
- if (napi_create_threadsafe_function(env, args[4], nullptr, text(env, "DSH native producer"), max_pending + 4, 2,
369
+ if (napi_create_threadsafe_function(env, args[3], nullptr, text(env, "DSH native producer"), max_pending + 4, 2,
488
370
  callback_holder, [](napi_env, void* data, void*) { delete static_cast<std::shared_ptr<Producer>*>(data); }, self.get(), dispatch, &self->callback) != napi_ok) {
489
371
  delete callback_holder;
490
- if (self->engine_reference) napi_delete_reference(env, self->engine_reference);
491
372
  return invalid(env, "Cannot create native producer dispatcher");
492
373
  }
493
374
  uv_loop_t* loop;
@@ -531,26 +412,18 @@ napi_value command(napi_env env, napi_callback_info info) {
531
412
  size_t count = 7; napi_value args[7]; napi_get_cb_info(env, info, &count, args, nullptr, nullptr);
532
413
  if (count < 2) return invalid(env, "Expected native producer command");
533
414
  auto self = external<Producer>(env, args[0], producer_tag); uint64_t kind;
534
- if (!self || !integer(env, args[1], kind, 0, 8)) return invalid(env, "Invalid native producer command");
535
- auto job = std::make_unique<Job>(); job->kind = static_cast<Kind>(kind);
536
- if (!self->factory && (job->kind == Kind::render || job->kind == Kind::start || job->kind == Kind::update))
537
- return invalid(env, "Producer has no native rendering engine");
415
+ if (!self || !integer(env, args[1], kind, 0, submit_latest_command)) return invalid(env, "Invalid native producer command");
416
+ // The latest-frame submission shares submit's lease and validation rules.
417
+ auto job = std::make_unique<Job>(); job->latest = kind == submit_latest_command;
418
+ job->kind = job->latest ? Kind::submit : static_cast<Kind>(kind);
538
419
  uint64_t width, height, value;
539
420
  napi_value buffer = nullptr;
540
421
  switch (job->kind) {
541
422
  case Kind::acquire:
542
- case Kind::start:
543
423
  if (count < 4 || !integer(env, args[2], width, 1, 16384) || !integer(env, args[3], height, 1, 16384)) return invalid(env, "Invalid native surface dimensions");
544
424
  job->width = static_cast<uint32_t>(width); job->height = static_cast<uint32_t>(height);
545
- if (job->kind == Kind::start) {
546
- if (count != 6 || !integer(env, args[4], value, 0, UINT32_MAX) ||
547
- napi_get_value_double(env, args[5], &job->interval) != napi_ok || !std::isfinite(job->interval) ||
548
- job->interval < 1 || job->interval > UINT32_MAX) return invalid(env, "Invalid native stream options");
549
- job->generation = static_cast<uint32_t>(value);
550
- }
551
425
  break;
552
426
  case Kind::write:
553
- case Kind::render:
554
427
  case Kind::submit:
555
428
  case Kind::discard:
556
429
  if (count < 3 || !(job->surface = external<Surface>(env, args[2], surface_tag)) || job->surface->owner.lock() != self)
@@ -568,11 +441,8 @@ napi_value command(napi_env env, napi_callback_info info) {
568
441
  }
569
442
  break;
570
443
  case Kind::send:
571
- case Kind::update:
572
444
  if (count < 3 || !string(env, args[2], job->text)) return invalid(env, "Native control JSON exceeds the UTF-8 limit");
573
- if (job->kind == Kind::update && (count != 4 || !integer(env, args[3], job->input_sequence))) return invalid(env, "Invalid native input sequence");
574
445
  break;
575
- case Kind::stop: break;
576
446
  }
577
447
  return queue(env, self, std::move(job), buffer);
578
448
  }
@@ -21,7 +21,9 @@ using namespace dsh_frame_forwarding;
21
21
  struct dsh_frame_forwarding_surface {
22
22
  uint32_t width = 0, height = 0, stride = 0;
23
23
  uint64_t bytes = 0, frame_id = 0, allocation_id = 0;
24
- enum { pending, granted, available, acquired, submitted } state = pending;
24
+ // A queued surface holds a complete latest-frame submission that waits for receiver credit.
25
+ enum { pending, granted, available, acquired, submitted, queued } state = pending;
26
+ std::string metadata;
25
27
  dsh_frame_forwarding_client* owner = nullptr;
26
28
  #if defined(__APPLE__)
27
29
  IOSurfaceRef surface = nullptr;
@@ -47,13 +49,68 @@ struct dsh_frame_forwarding_client {
47
49
  #endif
48
50
  };
49
51
  namespace {
52
+ /** Send a complete surface, marked replaceable for a latest-frame submission; the caller holds pool_mutex. */
53
+ bool send_frame(dsh_frame_forwarding_client* client, dsh_frame_forwarding_surface* surface, uint64_t frame_id, const char* metadata_json,
54
+ bool replaceable) {
55
+ Packet packet; packet.kind = frame; packet.max_frames = replaceable ? frame_replaceable : 0;
56
+ if (!metadata_json || std::strlen(metadata_json) >= sizeof(packet.text)) return false;
57
+ std::strcpy(packet.text, metadata_json);
58
+ packet.width = surface->width; packet.height = surface->height; packet.stride = surface->stride;
59
+ packet.frame_id = frame_id; packet.allocation_id = surface->allocation_id;
60
+ #if defined(__APPLE__)
61
+ auto resource = reinterpret_cast<uintptr_t>(surface->surface);
62
+ #else
63
+ auto resource = reinterpret_cast<uintptr_t>(surface->handle);
64
+ #endif
65
+ if (!client->channel->send(packet, resource)) return false;
66
+ surface->frame_id = frame_id; surface->state = dsh_frame_forwarding_surface::submitted; return true;
67
+ }
68
+ /** Whether fewer submissions await release than the latest-frame limit, which leaves one surface with the producer. */
69
+ bool latest_credit(const dsh_frame_forwarding_client* client) {
70
+ uint32_t outstanding = 0;
71
+ for (auto& surface : client->surfaces) if (surface->state == dsh_frame_forwarding_surface::submitted) ++outstanding;
72
+ return outstanding < std::max<uint32_t>(1, client->max_frames - 1);
73
+ }
74
+ /** Send the queued latest frame once credit allows; the caller holds pool_mutex. */
75
+ void send_queued(dsh_frame_forwarding_client* client) {
76
+ if (!latest_credit(client)) return;
77
+ for (auto& surface : client->surfaces) {
78
+ if (surface->state != dsh_frame_forwarding_surface::queued) continue;
79
+ if (!send_frame(client, surface.get(), surface->frame_id, surface->metadata.c_str(), true)) client->error = "Frame-forwarding frame channel closed";
80
+ surface->metadata.clear(); return;
81
+ }
82
+ }
50
83
  void copy_error(char* output, size_t size, const char* message) {
51
84
  if (output && size) { std::strncpy(output, message, size - 1); output[size - 1] = 0; }
52
85
  }
86
+ /**
87
+ * Return every surface that is neither acquired nor submitted to the receiver; the caller holds pool_mutex.
88
+ * @returns Whether every deallocation was sent.
89
+ */
90
+ bool release_idle(dsh_frame_forwarding_client* client) {
91
+ bool sent = true;
92
+ client->surfaces.erase(std::remove_if(client->surfaces.begin(), client->surfaces.end(), [&](auto& surface) {
93
+ if (surface->state == dsh_frame_forwarding_surface::acquired || surface->state == dsh_frame_forwarding_surface::submitted) return false;
94
+ Packet packet; packet.kind = deallocate; packet.allocation_id = surface->allocation_id;
95
+ sent = client->channel->send(packet) && sent; return true;
96
+ }), client->surfaces.end());
97
+ return sent;
98
+ }
53
99
  bool set_text(Packet& packet, const char* text) {
54
100
  if (!text || std::strlen(text) >= sizeof(packet.text)) return false;
55
101
  std::strcpy(packet.text, text); return true;
56
102
  }
103
+ /** Diagnostic for a receiver's refusal; "channel-busy" names a channel whose producer is still connected or draining. */
104
+ std::string refusal(const Packet& packet) {
105
+ const std::string reason(packet.text, strnlen(packet.text, sizeof(packet.text)));
106
+ if (reason == reject_busy) return "channel-busy: the frame-forwarding channel already has a producer or a waiting successor";
107
+ if (reason == reject_capability) return "Frame-forwarding receiver requires a transferable TX producer";
108
+ if (reason == reject_local_handles) return "Frame-forwarding receiver requires a producer that names only its own handles";
109
+ if (reason == reject_credential) return "Frame-forwarding TX credential was rejected";
110
+ if (reason == reject_closed) return "Frame-forwarding channel is closed";
111
+ if (reason.rfind(reject_protocol, 0) == 0) return "Frame-forwarding " + reason;
112
+ return "Frame-forwarding receiver rejected handshake";
113
+ }
57
114
  #if defined(__APPLE__)
58
115
  void set_number(CFMutableDictionaryRef dictionary, CFStringRef key, int64_t value) {
59
116
  auto number = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt64Type, &value);
@@ -68,7 +125,7 @@ dsh_frame_forwarding_client* dsh_frame_forwarding_connect(const char* endpoint_t
68
125
  static dsh_frame_forwarding_client* connect_impl(const char* endpoint_text, void* device,
69
126
  const dsh_frame_forwarding_connect_options* options, char* error, size_t error_size) {
70
127
  try {
71
- if (!endpoint_text) throw std::runtime_error("Missing native render endpoint");
128
+ if (!endpoint_text) throw std::runtime_error("Missing frame-forwarding TX credential");
72
129
  auto endpoint = parse_endpoint(endpoint_text);
73
130
  auto client = std::make_unique<dsh_frame_forwarding_client>();
74
131
  const auto started = std::chrono::steady_clock::now();
@@ -86,21 +143,30 @@ static dsh_frame_forwarding_client* connect_impl(const char* endpoint_text, void
86
143
  nullptr, 0, D3D11_SDK_VERSION, &client->device, nullptr, &client->context)))
87
144
  throw std::runtime_error("D3D11 hardware device unavailable");
88
145
  set_text(packet, device_adapter(client->device.Get()).c_str());
89
- packet.max_frames = hello_keyed_mutex;
146
+ packet.max_frames = hello_keyed_mutex | hello_transferable | hello_producer_local_handles;
90
147
  #else
91
148
  if (device) throw std::runtime_error("IOSurface producer does not accept a graphics device");
149
+ packet.max_frames = hello_transferable | hello_producer_local_handles;
92
150
  #endif
93
- if (!client->channel->send(packet)) throw std::runtime_error("Cannot send native render handshake");
151
+ if (!client->channel->send(packet)) throw std::runtime_error("Cannot send frame-forwarding handshake");
94
152
  Received received;
95
153
  int result;
96
154
  do {
97
- if (cancelled()) throw std::runtime_error("Native render connection cancelled or timed out");
155
+ if (cancelled()) throw std::runtime_error("Frame-forwarding connection cancelled or timed out");
98
156
  result = client->channel->receive(received, 100);
99
157
  } while (result == 0);
100
- if (result < 0 || received.packet.marker != magic || received.packet.version != DSH_FRAME_FORWARDING_PROTOCOL_VERSION || received.packet.kind != ready ||
101
- !received.packet.max_frames || !received.packet.max_bytes)
102
- throw std::runtime_error("Native render receiver rejected handshake");
103
- client->max_frames = received.packet.max_frames; client->max_bytes = received.packet.max_bytes;
158
+ const auto& reply = received.packet;
159
+ if (result < 0 || reply.marker != magic || reply.version != DSH_FRAME_FORWARDING_PROTOCOL_VERSION)
160
+ throw std::runtime_error("Frame-forwarding receiver rejected handshake");
161
+ if (reply.kind == goodbye) throw std::runtime_error(refusal(reply));
162
+ const auto connection = parse_connection(reply.token);
163
+ if (reply.kind != ready || !reply.max_frames || !reply.max_bytes) throw std::runtime_error("Frame-forwarding receiver rejected handshake");
164
+ // A receiver that predates transferable channels answers without a connection identifier.
165
+ if (!connection) throw std::runtime_error("Frame-forwarding receiver does not support transferable TX credentials");
166
+ // A receiver that does not echo the capability would read this producer's handle values as handles of its own.
167
+ if (!(reply.stride & hello_producer_local_handles)) throw std::runtime_error("Frame-forwarding receiver does not accept producer-local handles");
168
+ client->channel->bind_connection(connection);
169
+ client->max_frames = reply.max_frames; client->max_bytes = reply.max_bytes;
104
170
  return client.release();
105
171
  } catch (const std::exception& exception) { copy_error(error, error_size, exception.what()); return nullptr; }
106
172
  }
@@ -115,22 +181,25 @@ dsh_frame_forwarding_client* dsh_frame_forwarding_connect_with_options(const cha
115
181
  dsh_frame_forwarding_surface* dsh_frame_forwarding_acquire(dsh_frame_forwarding_client* client, uint32_t width, uint32_t height) {
116
182
  if (!client || client->stopped) return nullptr;
117
183
  std::lock_guard<std::mutex> lock(client->pool_mutex);
118
- if (!width || !height || width > 16384 || height > 16384) { client->error = "Native render dimensions outside supported range"; return nullptr; }
119
- dsh_frame_forwarding_surface* granted_surface = nullptr;
184
+ if (!width || !height || width > 16384 || height > 16384) { client->error = "Frame-forwarding dimensions outside supported range"; return nullptr; }
185
+ dsh_frame_forwarding_surface *granted_surface = nullptr, *queued_surface = nullptr;
186
+ bool allocation_pending = false;
120
187
  for (auto& surface : client->surfaces) {
121
188
  if (surface->width != width || surface->height != height) continue;
122
189
  if (surface->state == dsh_frame_forwarding_surface::available) {
123
190
  surface->state = dsh_frame_forwarding_surface::acquired; return surface.get();
124
191
  }
125
- if (surface->state == dsh_frame_forwarding_surface::pending) return nullptr;
126
- if (surface->state == dsh_frame_forwarding_surface::granted) { granted_surface = surface.get(); break; }
192
+ if (surface->state == dsh_frame_forwarding_surface::pending) allocation_pending = true;
193
+ if (surface->state == dsh_frame_forwarding_surface::queued) queued_surface = surface.get();
194
+ if (surface->state == dsh_frame_forwarding_surface::granted && !granted_surface) granted_surface = surface.get();
127
195
  }
196
+ // The newer frame rendered into an unsent latest submission replaces it.
197
+ if (!granted_surface && queued_surface) {
198
+ queued_surface->metadata.clear(); queued_surface->state = dsh_frame_forwarding_surface::acquired; return queued_surface;
199
+ }
200
+ if (!granted_surface && allocation_pending) return nullptr;
128
201
  if (!granted_surface) {
129
- client->surfaces.erase(std::remove_if(client->surfaces.begin(), client->surfaces.end(), [&](auto& surface) {
130
- if (surface->state == dsh_frame_forwarding_surface::acquired || surface->state == dsh_frame_forwarding_surface::submitted) return false;
131
- Packet packet; packet.kind = deallocate; packet.allocation_id = surface->allocation_id;
132
- client->channel->send(packet); return true;
133
- }), client->surfaces.end());
202
+ release_idle(client);
134
203
  uint64_t allocated_bytes = 0;
135
204
  for (auto& surface : client->surfaces) allocated_bytes += surface->bytes;
136
205
  #if defined(__APPLE__)
@@ -141,13 +210,13 @@ dsh_frame_forwarding_surface* dsh_frame_forwarding_acquire(dsh_frame_forwarding_
141
210
  #else
142
211
  uint64_t required_bytes = static_cast<uint64_t>(width) * height * 4;
143
212
  #endif
144
- if (required_bytes > client->max_bytes) { client->error = "Native render texture exceeds view byte budget"; return nullptr; }
213
+ if (required_bytes > client->max_bytes) { client->error = "Frame-forwarding texture exceeds view byte budget"; return nullptr; }
145
214
  if (client->surfaces.size() >= client->max_frames || allocated_bytes + required_bytes > client->max_bytes) return nullptr;
146
215
  auto pending_surface = std::make_unique<dsh_frame_forwarding_surface>();
147
216
  pending_surface->width = width; pending_surface->height = height; pending_surface->owner = client;
148
217
  pending_surface->bytes = required_bytes; pending_surface->allocation_id = client->next_allocation++;
149
218
  Packet request; request.kind = allocate; request.allocation_id = pending_surface->allocation_id; request.max_bytes = required_bytes;
150
- if (!client->channel->send(request)) { client->error = "Native render allocation channel closed"; return nullptr; }
219
+ if (!client->channel->send(request)) { client->error = "Frame-forwarding allocation channel closed"; return nullptr; }
151
220
  client->surfaces.push_back(std::move(pending_surface)); return nullptr;
152
221
  }
153
222
  auto surface = granted_surface;
@@ -233,20 +302,40 @@ int dsh_frame_forwarding_write_bgra_with_timeout(dsh_frame_forwarding_surface* s
233
302
  }
234
303
  int dsh_frame_forwarding_submit(dsh_frame_forwarding_client* client, dsh_frame_forwarding_surface* surface, uint64_t frame_id, const char* metadata_json) {
235
304
  if (!client || !surface || surface->owner != client || !frame_id || frame_id > 9007199254740991ULL || client->stopped) return 0;
236
- Packet packet; packet.kind = frame;
237
- if (!set_text(packet, metadata_json)) return 0;
305
+ if (!metadata_json || std::strlen(metadata_json) >= DSH_FRAME_FORWARDING_TEXT_CAPACITY) return 0;
306
+ std::lock_guard<std::mutex> lock(client->pool_mutex);
307
+ if (surface->state != dsh_frame_forwarding_surface::acquired) return 0;
308
+ for (auto& other : client->surfaces) {
309
+ if ((other->state == dsh_frame_forwarding_surface::submitted || other->state == dsh_frame_forwarding_surface::queued)
310
+ && other->frame_id == frame_id) return 0;
311
+ }
312
+ return send_frame(client, surface, frame_id, metadata_json, false) ? 1 : 0;
313
+ }
314
+ int dsh_frame_forwarding_submit_latest(dsh_frame_forwarding_client* client, dsh_frame_forwarding_surface* surface, uint64_t frame_id, const char* metadata_json) {
315
+ if (!client || !surface || surface->owner != client || !frame_id || frame_id > 9007199254740991ULL || client->stopped) return 0;
316
+ if (!metadata_json || std::strlen(metadata_json) >= DSH_FRAME_FORWARDING_TEXT_CAPACITY) return 0;
238
317
  std::lock_guard<std::mutex> lock(client->pool_mutex);
239
318
  if (surface->state != dsh_frame_forwarding_surface::acquired) return 0;
240
319
  for (auto& other : client->surfaces) if (other->state == dsh_frame_forwarding_surface::submitted && other->frame_id == frame_id) return 0;
241
- packet.width = surface->width; packet.height = surface->height; packet.stride = surface->stride;
242
- packet.frame_id = frame_id; packet.allocation_id = surface->allocation_id;
243
- #if defined(__APPLE__)
244
- auto resource = reinterpret_cast<uintptr_t>(surface->surface);
245
- #else
246
- auto resource = reinterpret_cast<uintptr_t>(surface->handle);
320
+ // An unsent older latest frame returns to the pool; the receiver never saw it.
321
+ for (auto& other : client->surfaces) {
322
+ if (other->state != dsh_frame_forwarding_surface::queued) continue;
323
+ other->metadata.clear(); other->state = dsh_frame_forwarding_surface::available;
324
+ }
325
+ if (latest_credit(client)) return send_frame(client, surface, frame_id, metadata_json, true) ? 1 : 0;
326
+ try { surface->metadata = metadata_json; } catch (const std::bad_alloc&) { return 0; }
327
+ surface->frame_id = frame_id; surface->state = dsh_frame_forwarding_surface::queued; return 1;
328
+ }
329
+ int dsh_frame_forwarding_trim(dsh_frame_forwarding_client* client) {
330
+ if (!client || client->stopped) return 0;
331
+ std::lock_guard<std::mutex> lock(client->pool_mutex);
332
+ const bool sent = release_idle(client);
333
+ #if defined(_WIN32)
334
+ // D3D11 destroys a released texture only when its context next flushes, which an idle producer would not do.
335
+ client->context->Flush();
247
336
  #endif
248
- if (!client->channel->send(packet, resource)) return 0;
249
- surface->frame_id = frame_id; surface->state = dsh_frame_forwarding_surface::submitted; return 1;
337
+ if (sent) return 1;
338
+ client->error = "Frame-forwarding allocation channel closed"; return 0;
250
339
  }
251
340
  void dsh_frame_forwarding_discard(dsh_frame_forwarding_client* client, dsh_frame_forwarding_surface* surface) {
252
341
  if (!client || !surface || surface->owner != client) return;
@@ -275,6 +364,7 @@ int dsh_frame_forwarding_poll_activity(dsh_frame_forwarding_client* client, uint
275
364
  surface->state = dsh_frame_forwarding_surface::available; break;
276
365
  }
277
366
  }
367
+ send_queued(client);
278
368
  } else if (received.packet.kind == allocated) {
279
369
  std::lock_guard<std::mutex> lock(client->pool_mutex);
280
370
  for (auto& surface : client->surfaces) {