@deepseek-ai/libreoffice-kit 0.1.5 → 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 (77) hide show
  1. package/NOTICE +4 -0
  2. package/README.md +44 -8
  3. package/README.zh.md +45 -9
  4. package/lib/cli.js +109 -46
  5. package/lib/editor.js +2061 -0
  6. package/lib/index.js +109 -46
  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 +30 -2
  16. package/lib/types/runtime.d.ts +2 -0
  17. package/lib/types/worker.d.ts +2 -2
  18. package/lib/worker.js +38 -31
  19. package/native-render/CMakeLists.txt +40 -0
  20. package/native-render/LICENSE +21 -0
  21. package/native-render/README.md +83 -0
  22. package/native-render/README.zh.md +83 -0
  23. package/native-render/include/dsh_render.h +101 -0
  24. package/native-render/include/dsh_render_engine.h +66 -0
  25. package/native-render/include/dsh_render_node.h +27 -0
  26. package/native-render/include/dsh_webgpu.h +52 -0
  27. package/native-render/index.d.ts +145 -0
  28. package/native-render/index.mjs +71 -0
  29. package/native-render/lib/browser/display.d.ts +46 -0
  30. package/native-render/lib/browser/display.js +128 -0
  31. package/native-render/lib/browser/index.d.ts +4 -0
  32. package/native-render/lib/browser/index.js +3 -0
  33. package/native-render/lib/browser/painters.d.ts +9 -0
  34. package/native-render/lib/browser/painters.js +180 -0
  35. package/native-render/lib/browser/types.d.ts +51 -0
  36. package/native-render/lib/browser/types.js +1 -0
  37. package/native-render/lib/electron/adapter.d.ts +9 -0
  38. package/native-render/lib/electron/adapter.js +118 -0
  39. package/native-render/lib/electron/index.d.ts +3 -0
  40. package/native-render/lib/electron/index.js +3 -0
  41. package/native-render/lib/electron/preload.d.ts +13 -0
  42. package/native-render/lib/electron/preload.js +47 -0
  43. package/native-render/lib/electron/transfer.d.ts +15 -0
  44. package/native-render/lib/electron/transfer.js +36 -0
  45. package/native-render/prebuilds/darwin-arm64/libdsh_render_sdk.a +0 -0
  46. package/native-render/prebuilds/darwin-arm64/manifest.json +34 -0
  47. package/native-render/prebuilds/darwin-arm64/render.node +0 -0
  48. package/native-render/prebuilds/darwin-x64/libdsh_render_sdk.a +0 -0
  49. package/native-render/prebuilds/darwin-x64/manifest.json +34 -0
  50. package/native-render/prebuilds/darwin-x64/render.node +0 -0
  51. package/native-render/prebuilds/win32-arm64/dsh_render_sdk.lib +0 -0
  52. package/native-render/prebuilds/win32-arm64/manifest.json +34 -0
  53. package/native-render/prebuilds/win32-arm64/render.node +0 -0
  54. package/native-render/prebuilds/win32-x64/dsh_render_sdk.lib +0 -0
  55. package/native-render/prebuilds/win32-x64/manifest.json +34 -0
  56. package/native-render/prebuilds/win32-x64/render.node +0 -0
  57. package/native-render/receipt.json +23 -0
  58. package/native-render/scripts/build-webgpu.mjs +197 -0
  59. package/native-render/scripts/build.mjs +43 -0
  60. package/native-render/scripts/metadata.mjs +47 -0
  61. package/native-render/scripts/source-identity.mjs +15 -0
  62. package/native-render/scripts/verify-prebuilds.mjs +14 -0
  63. package/native-render/sdk.json +45 -0
  64. package/native-render/src/node-producer.cc +595 -0
  65. package/native-render/src/producer-internal.h +8 -0
  66. package/native-render/src/producer.cc +306 -0
  67. package/native-render/src/receiver.cc +1050 -0
  68. package/native-render/src/relay-transport.inc +293 -0
  69. package/native-render/src/transport.cc +405 -0
  70. package/native-render/src/transport.h +80 -0
  71. package/native-render/src/webgpu.cc +214 -0
  72. package/native-render/src/win-delay-load.LICENSE +24 -0
  73. package/native-render/src/win-delay-load.cc +43 -0
  74. package/native-render/verify.d.mts +4 -0
  75. package/native-render/verify.mjs +101 -0
  76. package/native-render/webgpu-dependencies.json +51 -0
  77. package/package.json +95 -10
@@ -18,7 +18,7 @@ export interface FontFace {
18
18
  readonly italic: boolean;
19
19
  readonly fixed: boolean;
20
20
  readonly postscriptName: string | null;
21
- /** Decoded glyph ranges; absent until a match reads this face's coverage. */
21
+ /** Optional complete glyph ranges supplied by the metadata owner. */
22
22
  coverage?: GlyphRange[];
23
23
  }
24
24
  /** All faces decoded from one unchanged physical file, including an empty parse result. */
@@ -88,19 +88,13 @@ export declare function systemFontDirectories(platform?: NodeJS.Platform, home?:
88
88
  * @throws when the root exists but cannot be read for a reason other than its absence or protection.
89
89
  */
90
90
  export declare function mobileAssetFontDirectories(assets: string): string[];
91
- /**
92
- * Decode glyph coverage for one parsed face.
93
- * @param font - The parsed physical face.
94
- * @returns the inclusive ranges the face renders, or none when its glyph tables reject decoding.
95
- */
96
- export declare function faceCoverage(font: Font): GlyphRange[];
97
91
  /**
98
92
  * @param parsed - Parsed font file: one face, or a collection of faces.
99
93
  * @param face - Indexed metadata naming the face inside that file.
100
94
  * @returns the physical face the index names.
101
95
  * @throws when the file no longer provides the indexed face.
102
96
  */
103
- export declare function indexedFace(parsed: Font | FontCollection, face: Pick<FontFace, 'faceIndex' | 'postscriptName'>): Font;
97
+ export declare function indexedFace(parsed: Font | Pick<FontCollection, 'fonts'>, face: Pick<FontFace, 'faceIndex' | 'postscriptName'>): Font;
104
98
  /**
105
99
  * VCL weight, width, and fixed-pitch values for one parsed face.
106
100
  * @param font - The parsed physical face, whose `OS/2` and `post` tables may be absent.
@@ -123,6 +117,8 @@ export declare function indexSystemFonts(options: FontIndexOptions, previous?: R
123
117
  export declare class SystemFontCatalog {
124
118
  private readonly options;
125
119
  private readonly faces;
120
+ private readonly queried;
121
+ private readonly byFile;
126
122
  /**
127
123
  * @param options - Host metadata snapshot and fallback families.
128
124
  */
@@ -6,7 +6,6 @@ import type { ResolvedOptions } from './options.ts';
6
6
  export declare function renderImagesWithNative(request: {
7
7
  readonly engine: NativeEngine;
8
8
  readonly options: ResolvedOptions;
9
- readonly inputPath: string;
10
9
  readonly source: Uint8Array;
11
10
  readonly scratch: string;
12
11
  readonly profile: string;
@@ -5,6 +5,7 @@ export interface NativeChild extends EventEmitter {
5
5
  stdin: Writable;
6
6
  stdout: Readable;
7
7
  stderr: Readable;
8
+ readonly pid?: number | undefined;
8
9
  readonly exitCode: number | null;
9
10
  readonly signalCode: NodeJS.Signals | null;
10
11
  kill(signal: NodeJS.Signals): boolean;
@@ -20,6 +20,16 @@ export declare function prepareNativeFontProfile(profile: string, substitutions:
20
20
  * @returns the environment the helper starts with.
21
21
  */
22
22
  export declare function nativeEnvironment(profile: string, programDirectory: string, source?: NodeJS.ProcessEnv, platform?: string): Record<string, string>;
23
+ /**
24
+ * Prepare short Windows engine paths owned by the caller's private profile.
25
+ * @param engine - Verified engine installation; its resources remain in place.
26
+ * @param profile - Private operation directory that owns the temporary executable and junction.
27
+ * @returns Engine paths and a release function to call once, after the helper closes and before removing the profile.
28
+ */
29
+ export declare function prepareNativeEngine(engine: NativeEngine, profile: string): Promise<{
30
+ engine: NativeEngine;
31
+ release(): Promise<void>;
32
+ }>;
23
33
  /**
24
34
  * Keep Windows engine resources reachable through a short profile-owned path until the helper exits.
25
35
  * @param engine - Verified engine installation; its resources remain in place.
@@ -28,11 +38,26 @@ export declare function nativeEnvironment(profile: string, programDirectory: str
28
38
  * @returns The operation result after removing the resource junction.
29
39
  */
30
40
  export declare function withNativeEngine<T>(engine: NativeEngine, profile: string, run: (engine: NativeEngine) => Promise<T>): Promise<T>;
41
+ /**
42
+ * Prepare the document transport accepted by the pinned helper.
43
+ * @param engine - Resolved helper and input protocol.
44
+ * @param input - Owned document bytes and validated format.
45
+ * @param profile - Private directory retained until the helper exits and removed by the operation owner.
46
+ * @param signal - Cancellation of input preparation.
47
+ * @returns Helper arguments and an optional binary stdin prefix.
48
+ */
49
+ export declare function prepareNativeInput(engine: NativeEngine, input: {
50
+ bytes: Uint8Array;
51
+ format: string;
52
+ }, profile: string, signal: AbortSignal): Promise<{
53
+ args: string[];
54
+ bytes?: Uint8Array;
55
+ }>;
31
56
  /**
32
57
  * Run one native conversion and await bounded result transport.
33
58
  * @param engine - Resolved native engine installation.
34
59
  * @param options - Validated conversion limits.
35
- * @param input - Private source path inside the conversion scratch directory.
60
+ * @param input - Owned source bytes and format; older pinned helpers receive a private input file.
36
61
  * @param output - Private PDF path inside the conversion scratch directory.
37
62
  * @param profile - Conversion-owned profile directory.
38
63
  * @param fonts - Installed font files the helper may load.
@@ -41,5 +66,8 @@ export declare function withNativeEngine<T>(engine: NativeEngine, profile: strin
41
66
  * @param operation - Validated output format, recalculation, and worksheet selection.
42
67
  * @throws ConversionError for a reported conversion failure, and the abort reason for cancellation.
43
68
  */
44
- export declare function runNative(engine: NativeEngine, options: ResolvedOptions, input: string, output: string, profile: string, fonts: readonly string[], substitutions: readonly FontSubstitution[], signal: AbortSignal, operation?: Pick<ConversionSpec, 'format' | 'recalculate' | 'sheet'>): Promise<void>;
69
+ export declare function runNative(engine: NativeEngine, options: ResolvedOptions, input: {
70
+ bytes: Uint8Array;
71
+ format: string;
72
+ }, output: string, profile: string, fonts: readonly string[], substitutions: readonly FontSubstitution[], signal: AbortSignal, operation?: Pick<ConversionSpec, 'format' | 'recalculate' | 'sheet'>): Promise<void>;
45
73
  //# sourceMappingURL=native.d.ts.map
@@ -2,6 +2,8 @@
2
2
  export interface RuntimeInfo {
3
3
  readonly version: string;
4
4
  readonly backend: 'native' | 'wasm';
5
+ /** Whether the selected engine implements the native preview protocol; independent of GPU availability. */
6
+ readonly nativePreview: boolean;
5
7
  readonly cliPath: string;
6
8
  readonly nodeApiPath: string;
7
9
  }
@@ -4,9 +4,9 @@ import type { ConversionSpec } from './operations.ts';
4
4
  import type { Engine } from './engine.ts';
5
5
  import type { FontFace } from './fonts.ts';
6
6
  import type { ResolvedOptions } from './options.ts';
7
- /** Worker input: inspected paths, validated limits, the resolved engine, and the current font snapshot. */
7
+ /** Worker input: owned source bytes, validated limits, the resolved engine, and the current font snapshot. */
8
8
  export interface WorkerRequest {
9
- readonly inputPath: string;
9
+ readonly bytes: Uint8Array;
10
10
  readonly extension: string;
11
11
  readonly operation: ConversionSpec | ImageRenderSpec;
12
12
  readonly options: ResolvedOptions;
package/lib/worker.js CHANGED
@@ -119,28 +119,6 @@ function fontFamilyPriority(requested, groups, pitch = 0, symbols = false) {
119
119
  }
120
120
  return [...priority.values()];
121
121
  }
122
- function ranges(font) {
123
- const points = font.characterSet.filter((point) => font.hasGlyphForCodePoint(point)).sort((left, right) => left - right);
124
- const result = [];
125
- for (const point of points) {
126
- const last = result.at(-1);
127
- if (last !== void 0 && point <= last[1] + 1) last[1] = Math.max(last[1], point);
128
- else result.push([point, point]);
129
- }
130
- return result;
131
- }
132
- /**
133
- * Decode glyph coverage for one parsed face.
134
- * @param font - The parsed physical face.
135
- * @returns the inclusive ranges the face renders, or none when its glyph tables reject decoding.
136
- */
137
- function faceCoverage(font) {
138
- try {
139
- return ranges(font);
140
- } catch {
141
- return [];
142
- }
143
- }
144
122
  /**
145
123
  * @param parsed - Parsed font file: one face, or a collection of faces.
146
124
  * @param face - Indexed metadata naming the face inside that file.
@@ -152,12 +130,6 @@ function indexedFace(parsed, face) {
152
130
  if (font === void 0 || font.postscriptName !== face.postscriptName) throw new Error("The indexed font face is no longer available; recreate the converter.");
153
131
  return font;
154
132
  }
155
- function covers(face, points) {
156
- if (points.length === 0) return [];
157
- if (face.coverage === void 0) face.coverage = faceCoverage(indexedFace(create(readFont(face)), face));
158
- const coverage = face.coverage;
159
- return points.filter((point) => coverage.some(([first, last]) => point >= first && point <= last));
160
- }
161
133
  function regionalPriority(face, language) {
162
134
  const locale = language.toLowerCase();
163
135
  const preferred = locale.startsWith("ja") ? ["jp"] : locale.startsWith("ko") ? ["kr"] : locale.startsWith("zh") ? /hant|tw|hk|mo/.test(locale) ? ["tc", "hk"] : ["sc"] : [];
@@ -169,12 +141,19 @@ function regionalPriority(face, language) {
169
141
  var SystemFontCatalog = class {
170
142
  options;
171
143
  faces;
144
+ queried = /* @__PURE__ */ new Map();
145
+ byFile = /* @__PURE__ */ new Map();
172
146
  /**
173
147
  * @param options - Host metadata snapshot and fallback families.
174
148
  */
175
149
  constructor(options) {
176
150
  this.options = options;
177
151
  this.faces = options.faces.map((face) => ({ ...face }));
152
+ for (const face of this.faces) {
153
+ const members = this.byFile.get(face.path) ?? [];
154
+ members.push(face);
155
+ this.byFile.set(face.path, members);
156
+ }
178
157
  }
179
158
  /**
180
159
  * Find installed faces covering the requested family or missing characters.
@@ -208,7 +187,36 @@ var SystemFontCatalog = class {
208
187
  const files = /* @__PURE__ */ new Set();
209
188
  for (const { face } of ranked) {
210
189
  signal.throwIfAborted();
211
- const covered = covers(face, [...missing]);
190
+ let covered;
191
+ if (face.coverage !== void 0) {
192
+ const coverage = face.coverage;
193
+ covered = [...missing].filter((point) => coverage.some(([first, last]) => point >= first && point <= last));
194
+ } else {
195
+ let known = this.queried.get(face);
196
+ if (known === void 0) {
197
+ known = /* @__PURE__ */ new Map();
198
+ this.queried.set(face, known);
199
+ }
200
+ const unknown = [...missing].filter((point) => !known.has(point));
201
+ if (unknown.length > 0) {
202
+ const parsed = create(readFont(face));
203
+ const collection = "fonts" in parsed ? { fonts: parsed.fonts } : parsed;
204
+ for (const member of this.byFile.get(face.path)) {
205
+ let answers = this.queried.get(member);
206
+ if (answers === void 0) {
207
+ answers = /* @__PURE__ */ new Map();
208
+ this.queried.set(member, answers);
209
+ }
210
+ const font = indexedFace(collection, member);
211
+ try {
212
+ for (const point of unknown) answers.set(point, font.hasGlyphForCodePoint(point));
213
+ } catch {
214
+ for (const point of unknown) answers.set(point, false);
215
+ }
216
+ }
217
+ }
218
+ covered = [...missing].filter((point) => known.get(point));
219
+ }
212
220
  if (missing.size > 0 && covered.length === 0) continue;
213
221
  if (!files.has(face.path)) {
214
222
  selected.push(face);
@@ -1421,8 +1429,7 @@ function requireParentPort(port) {
1421
1429
  }
1422
1430
  const port = requireParentPort(parentPort);
1423
1431
  try {
1424
- const { inputPath, extension, operation, options, engine, scratch, fontFaces, fontCache } = workerData;
1425
- const bytes = readFileSync(inputPath);
1432
+ const { bytes, extension, operation, options, engine, scratch, fontFaces, fontCache } = workerData;
1426
1433
  const images = "kind" in operation && operation.kind === "images";
1427
1434
  if (images && extension === "pdf" && new TextDecoder().decode(bytes.subarray(0, 5)) !== "%PDF-") throw new ConversionError("invalid-document", "Input does not contain a PDF header.");
1428
1435
  const document = images && extension === "pdf" ? {
@@ -0,0 +1,40 @@
1
+ cmake_minimum_required(VERSION 3.20)
2
+ file(READ "${CMAKE_CURRENT_SOURCE_DIR}/sdk.json" DSH_RENDER_METADATA)
3
+ string(JSON DSH_RENDER_VERSION GET "${DSH_RENDER_METADATA}" version)
4
+ string(REGEX REPLACE "-.*$" "" DSH_RENDER_CMAKE_VERSION "${DSH_RENDER_VERSION}")
5
+ project(dsh_render VERSION ${DSH_RENDER_CMAKE_VERSION} LANGUAGES CXX)
6
+ add_library(dsh_render_sdk STATIC src/producer.cc src/transport.cc)
7
+ target_compile_features(dsh_render_sdk PUBLIC cxx_std_17)
8
+ target_include_directories(dsh_render_sdk PUBLIC include PRIVATE src)
9
+ set_target_properties(dsh_render_sdk PROPERTIES POSITION_INDEPENDENT_CODE ON)
10
+ target_compile_options(dsh_render_sdk PRIVATE $<$<PLATFORM_ID:Windows>:/EHsc>)
11
+ if(APPLE)
12
+ target_link_libraries(dsh_render_sdk PUBLIC "-framework IOSurface" "-framework CoreFoundation" bsm)
13
+ elseif(WIN32)
14
+ target_compile_definitions(dsh_render_sdk PUBLIC _WIN32_WINNT=0x0602)
15
+ target_link_libraries(dsh_render_sdk PUBLIC d3d11 dxgi advapi32)
16
+ else()
17
+ message(FATAL_ERROR "DSH native render requires macOS or Windows")
18
+ endif()
19
+ install(TARGETS dsh_render_sdk ARCHIVE DESTINATION lib)
20
+ install(FILES include/dsh_render.h include/dsh_render_engine.h include/dsh_render_node.h DESTINATION include)
21
+
22
+ option(DSH_RENDER_WEBGPU "Build the native WebGPU producer adapter" OFF)
23
+ if(DSH_RENDER_WEBGPU)
24
+ if(NOT DSH_DAWN_SOURCE_DIR)
25
+ message(FATAL_ERROR "Use scripts/build-webgpu.mjs to prepare the pinned Dawn sources")
26
+ endif()
27
+ set(BUILD_SHARED_LIBS OFF CACHE BOOL "" FORCE)
28
+ set(DAWN_BUILD_MONOLITHIC_LIBRARY STATIC CACHE STRING "" FORCE)
29
+ set(DAWN_ENABLE_INSTALL ON CACHE BOOL "" FORCE)
30
+ add_subdirectory("${DSH_DAWN_SOURCE_DIR}" dawn)
31
+ set_target_properties(webgpu_dawn PROPERTIES OUTPUT_NAME dawn)
32
+ add_library(dsh_webgpu STATIC src/webgpu.cc)
33
+ target_compile_features(dsh_webgpu PUBLIC cxx_std_20)
34
+ target_include_directories(dsh_webgpu PUBLIC include)
35
+ target_link_libraries(dsh_webgpu PUBLIC dsh_render_sdk dawn::webgpu_dawn)
36
+ set_target_properties(dsh_webgpu PROPERTIES POSITION_INDEPENDENT_CODE ON)
37
+ target_compile_options(dsh_webgpu PRIVATE $<$<PLATFORM_ID:Windows>:/EHsc>)
38
+ install(TARGETS dsh_webgpu ARCHIVE DESTINATION lib)
39
+ install(FILES include/dsh_webgpu.h DESTINATION include)
40
+ endif()
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 DeepSeek
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,83 @@
1
+ # Native rendering SDK
2
+
3
+ English | [中文](README.zh.md)
4
+
5
+ The `@deepseek-ai/libreoffice-kit/native-render` package connects an authorized native producer to Electron Main without routing pixels through DSH Host. This public Kit subpath contains Node/TypeScript producer and receiver APIs backed by the same Electron-independent C/C++ SDK. Its payload includes explicitly listed C/C++ build sources; source globs and source maps are excluded. macOS uses IOSurface with Mach port transfer; Windows uses D3D11 shared NT handles and an owner-only named pipe. Separate browser and Electron subpaths provide presentation and texture ownership; consumers own authorization and application commands.
6
+
7
+ Installing Kit with `--omit=optional` provides the SDK without Office engines or the Windows Office pipe dependency Koffi. Normal installation retains both optional dependency selections. Neither SDK installation nor SDK communication compiles or downloads binaries.
8
+
9
+ ## Receiver
10
+
11
+ Create one `createBudget(maxBytes)` per window and pass it to every `createReceiver({ maxFrames, maxBytes, budget, displayAdapter, readbackTimeoutMs, framePolicy }, onEvent)`. Start the owned producer through its normal application lifecycle, bind its PID once with `bindProducer(pid)`, and pass the private `endpoint` directly to that producer. The endpoint contains authentication credentials and must never reach the Renderer or logs.
12
+
13
+ Frame events carry `transport: "shared-texture"`, an eight-byte native handle, the producer's `frameId`, and a receiver-owned `deliveryId`. Call `release(deliveryId)` only after Electron reports `allReferencesReleased`; queue submission and frame timeout do not release consumer ownership. Delivery IDs remain distinct when a producer reuses a released frame ID. Duplicate releases return false. `close()` asynchronously drains submitted GPU work and joins the owned workers; delivered resources remain retained until release or receiver destruction. A stalled GPU can keep close pending; cancellation never frees resources still used by that GPU.
14
+
15
+ Windows shared-texture receivers require the compositor’s actual adapter LUID in `displayAdapter`; creating one without it fails. The producer reports its device LUID during authentication, and the receiver verifies it against each texture. For matching adapters, keyed producer textures are imported directly; legacy textures are copied into a receiver-owned shared target. `sourceKeyedMutex` reports the actual source descriptor, independent of the handshake declaration. For different adapters, a native worker reads back the entire source texture and uploads its premultiplied BGRA pixels into a shared texture on the compositor’s adapter. JavaScript receives only its handle. `adapterId` identifies the source; `presentationAdapterId` identifies the exported texture’s adapter and is null for macOS IOSurface.
16
+
17
+ The receiver’s Windows target uses a keyed mutex recognized by Chromium to order GPU access; Electron’s reference-release callback controls lifetime but does not replace this synchronization. Cross-adapter copies preserve row pitch and return source credit as soon as the readback GPU copy completes; the independent target remains held until Electron releases its delivery. Same-adapter copying and macOS IOSurface retain source credit through delivery release. GPU completion uses reusable fence events when supported and bounded query polling otherwise. `readbackTimeoutMs` bounds native frame preparation and delivery; timeout or cancellation stops new work while retaining submitted copies until GPU completion or device removal. Worker termination and receiver garbage collection use the same asynchronous cleanup.
18
+
19
+ [Chromium 152 acquires key 0 with `INFINITE`](https://github.com/chromium/chromium/blob/24072c1aa400ec4a89dc738b6b6acd12a8589b6f/gpu/command_buffer/service/dxgi_shared_handle_manager.cc#L129). Before direct handoff, the receiver worker performs a bounded acquire/release readiness check. This moves a possible CPU wait to that worker without copying pixels; it does not impose a timeout on Chromium. A producer must release before submitting and must not access the surface until credit returns. A producer that violates this after the check can still stall Chromium or trigger its GPU watchdog.
20
+
21
+ Shared-texture `framePolicy` defaults to `ordered`, preserving independent request/reply frames such as Office tiles. Continuous streams may select `latest`: a completed relay readback replaces the frame whose upload has not begun, with at most one pending frame and one upload in progress. Two staging slots allow source copying while a prepared frame waits for a target. Held targets stop further uploads; ordered delivery also stops readback when both staging slots are occupied.
22
+
23
+ The byte budget reserves one surface per macOS allocation or declared Windows same-adapter keyed allocation. A legacy same-adapter allocation reserves a source plus target. The optional hello capability permits the smaller reservation; a declared keyed producer that supplies a non-keyed texture is rejected. An undeclared keyed source can still be imported directly, with the conservative legacy reservation. Relay reserves up to `N = maxFrames` source textures, `N` independent targets, and two staging textures. Target and staging capacity tracks the connection's largest requested frame; source and pool growth receive one atomic budget grant. Relay limits each frame to `maxBytes / (2N + 2)` bytes and advertises `N` times that allowance to the producer. With three frames and 256 MiB, three 4K BGRA sources plus the five receiver textures reserve 253.125 MiB. Idle storage retains its reservation; closing frees independent pool slots while each held target retains its own budget until release. Renderer queues and canvas storage have separate limits; this budget is not a process-memory ceiling.
24
+
25
+ `send(json)` queues a bounded control message without blocking Main on native I/O. Producer messages arrive as `message` events. OS peer identity is checked in addition to the endpoint credential. A receiver accepts one producer connection and cannot be rebound. Errors require the consumer to terminate or replace that connection. Frames discarded before delivery release their native resources; delivered frames still require explicit release after closure.
26
+
27
+ ## Node/TypeScript producer
28
+
29
+ Import `createProducer` from `@deepseek-ai/libreoffice-kit/native-render` inside the owning Node process. Bind the receiver to that Node process's PID; an in-process plugin uses `process.pid`. Pass the private endpoint, `maxPendingOperations`, `operationTimeoutMs`, and an optional native engine descriptor. Await `ready`, and register explicit `close()` with the owning plugin's disposal. The [TypeScript API](index.d.ts) defines operations and resource ownership.
30
+
31
+ A dedicated native worker serializes connection, uploads, engine callbacks, mutex waits and submission. A separate polling thread wakes it on credit and control events; acquisition does not poll on a timer. Accepted operations may queue before readiness; excess ordinary operations reject, including control messages. Discard has one reserved queue slot per owned lease so a full queue cannot prevent release. Pending acquisitions wait for credits without blocking worker execution. Acquisition timeout rejects that request without closing the producer. Transport or uncertain GPU completion failures close the connection. `closed` resolves after queued operations settle and the worker, client and engine are destroyed. Event-listener exceptions are contained; listeners remain responsible for their own diagnostics. Worker termination uses asynchronous native cleanup. Set `DSH_RENDER_DIAGNOSTICS=1` to report contained producer callback exceptions to stderr.
32
+
33
+ `acquire(width, height)` returns an explicit surface lease. Await `writeBgra(buffer, stride)` or `render()`, then `submit(frameId, metadata)` or `discard()`; surface `close()` is a discard alias. Busy or consumed surfaces reject reuse. Garbage collection never grants frame credit. Submission consumes the lease, but the underlying texture remains unavailable until the receiver releases its frame.
34
+
35
+ CPU uploads borrow a non-shared Node Buffer until the returned promise settles. During that time callers must not modify it, detach it or transfer its backing ArrayBuffer. Row stride may exceed the packed row width. The binding retains the Buffer and avoids an intermediate binding copy; the C SDK still copies or uploads those bytes. CPU upload is not GPU zero-copy.
36
+
37
+ For continuous GPU rendering, supply an engine exported by another Node addon using [dsh_render_node.h](include/dsh_render_node.h). Its [engine callbacks](include/dsh_render_engine.h) run serially on the producer worker. The descriptor stays alive through engine destruction. `render` borrows the acquired native texture and releases imports before returning. Windows callbacks queue work on the supplied device's immediate context while the SDK owns key 0; they must not acquire that lock themselves. macOS callbacks complete GPU work before returning. Both observe cancellation. Third-party callbacks must return promptly; the SDK cannot preempt arbitrary engine code. Engine creation, update and destruction must not call JavaScript.
38
+
39
+ `start({ width, height, generation, frameIntervalMs })` renders continuously in native code; `update(json, inputSequence)` applies batched engine state, and `stop()` stops new frames. The interval includes rendering time and accepts fractions such as `1000 / 60`; elapsed deadlines are skipped without catch-up bursts. Manual leases must be released before starting. Frame metadata contains request ID, viewport generation, revision and the latest applied input sequence.
40
+
41
+ Engine ABI v2 adds `prepare` before surface acquisition: return 1 for a changed frame, 0 for no change, or -1 for failure. An unchanged frame makes no acquisition or submission and consumes no credit. A declared change remains pending through credit waits; preparation continues at the stream cadence, and newer updates may replace the state rendered when credit arrives. Start and resize force one frame, and updates make the next change check immediately eligible. ABI v1 keeps continuous rendering; manual Node callers skip a frame by not acquiring or submitting it. Manual `surface.render()` does not call `prepare`.
42
+
43
+ The display path can match the C producer's native path without per-frame JavaScript or pixel readback on the same adapter. End-to-end performance still depends on engine work, callbacks, pacing, GPU choice and CPU copying. Displayed-frame intervals, skipped revisions, input-to-observed-frame latency and memory require separate measurement; arrival throughput alone is not displayed FPS. Both languages use the same automatic receiver transport.
44
+
45
+ ## C/C++ producer
46
+
47
+ Include `include/dsh_render.h` and link the matching `libdsh_render_sdk.a` or `dsh_render_sdk.lib`, or build the sources listed in `sdk.json`. The API has no Node or Electron dependency. Poll on one thread; acquisition, writing, submission and discard may run on another. Callers must serialize use of the same graphics context. Interrupt polling, join that thread, and close the client after all its API calls return.
48
+
49
+ On Windows, `dsh_render_connect_with_device` accepts the application’s `ID3D11Device` and retains it until close. Passing null, or using `dsh_render_connect`, creates a default device. `dsh_render_connect_with_options` additionally bounds connection/handshake time and accepts a cancellation callback on the connecting thread. Applications choose their own GPU; DSH selects the transport. Serialize the adopted device’s immediate context with SDK writes. macOS requires a null device.
50
+
51
+ Acquisition initially returns null while the receiver grants allocation credit. Poll and retry when the owning application is ready; do not spin. Allocation requests enter a shared FIFO budget queue. Grants cover idle pool allocations as well as displayed frames. A null acquisition otherwise indicates exhausted credits; terminal allocation errors are reported by polling with `kind = -1` and explanatory text. Stop processing on a negative poll result and preserve its diagnostic before closing. A consumer must bound its overall operation lifetime and disconnect on timeout.
52
+
53
+ Textures use top-left BGRA8 premultiplied pixels in sRGB. Windows surfaces have a keyed mutex using key 0. Acquisition grants a lease without locking: SDK CPU uploads and engine callbacks own the write lock; external GPU writers own it themselves through `dsh_render_surface_keyed_mutex` or their import API. Writers release key 0 after queueing commands and release imported objects/views before submit or discard. CPU uploads copy the input before returning and do not wait for GPU completion; `dsh_render_write_bgra_with_timeout` bounds mutex acquisition. `AcquireSync` can block the CPU. macOS writers must complete GPU work before submit or discard. Reusing a surface requires both a new acquisition and the write lock on Windows. If GPU access release fails, close the connection without reusing the surface.
54
+
55
+ Frame IDs must be integers from 1 through 9007199254740991 and unique among outstanding submissions. `dsh_render_submit` returns 1 when submitted and 0 on failure. A failed submission leaves a valid acquisition with the caller for retry or discard under the same GPU completion requirements.
56
+
57
+ Windows Vulkan and D3D12 consumers borrow the NT handle through `dsh_render_surface_shared_handle` while the surface is acquired. They must use the SDK's GPU adapter and enable keyed-mutex synchronization in their import API, following the ownership rules above. The SDK owns the handle; callers must not close it. The function returns null on macOS. Receiver copies acquire the source mutex with a bounded timeout when the actual texture descriptor declares one; legacy textures retain the completed-write requirement.
58
+
59
+ Application JSON, frame correlation, input semantics, viewport generations and input acknowledgements are defined by the consuming application protocol. Control messages are limited to 16383 UTF-8 bytes. The SDK does not expose arbitrary process launching or native handles to webpages. The SDK has no LibreOffice runtime dependency; applications may install Kit with `--omit=optional` when only native rendering is needed.
60
+
61
+ ## Build and validation
62
+
63
+ Run `node scripts/build.mjs` on the target platform with complete matching Node headers available. The SDK version comes from the public Kit package metadata. Set `DSH_NODE_INCLUDE` explicitly when necessary; Windows additionally requires a developer toolchain environment and `DSH_NODE_LIB`. Builds produce precompiled Node-API and static SDK artifacts with SHA-256 receipts. Installation never invokes a compiler. Public Kit packing requires all four supported targets from one source commit. Partial payloads cannot be packed. The verifier checks addon and static-library architectures, artifact hashes, source hashes, versions and protocol before signing. Desktop runtime packaging retains only the selected target’s native-render prebuilds, along with the package license.
64
+
65
+ Run `pnpm test` in this directory after building. `DSH_NATIVE_RENDER_PACKAGE_ROOT` selects an installed SDK payload for transport and lifecycle tests; diagnostics may be retained outside the package with `DSH_NATIVE_RENDER_DIAGNOSTICS`. Fixture setup gives each complete compile/link group 120 seconds within a 180-second setup hook; protocol and runner deadlines are separate. Compiler receipts preserve the resolved executable, arguments, working directory, elapsed time, direct-child outcome and stdout/stderr. Compiler descendant exit is not observed. Parent fixtures prepare GPU inspectors and pass their paths only to owned runners, retaining the temporary files until those runners exit. The native CI lane runs C transport and Node producer integration tests serially before packing, including asynchronous shutdown and Worker termination. Performance and Electron shared-texture import require separate actual GPU validation; a successful native transport test alone does not establish those results.
66
+
67
+ ## Browser and Electron presentation
68
+
69
+ `@deepseek-ai/libreoffice-kit/native-render/browser` exports `NativeFrameDisplay`, `createNativeFramePainter`, and their types. Importing this entry does not load Electron, Office or native addons and allocates no graphics resources. The generic view identifier preserves application-specific string types. Applications own view creation, authorization, producer control and input arbitration.
70
+
71
+ `NativeFrameDisplay.present()` takes ownership of a frame lease and releases it after painting or rejection. Hidden documents wait for visibility; a generation change or disposal cancels the wait. The owner separately updates producer visibility. Dispose the display before removing its canvas.
72
+
73
+ `@deepseek-ai/libreoffice-kit/native-render/electron` exports `detectNativeRenderAdapter` and `sendNativeFrame` for Electron Main. Adapter detection waits for complete Chromium GPU information and observes its exported Direct3D11 texture within one supplied deadline. Unsupported backends or software compositing return `null` without creating an offscreen window. Cancellation also covers GPU initialization and window construction. After the application validates the recipient and frame metadata, `sendNativeFrame` owns the delivery credit through submission failure or Electron's final GPU-reference release. Its completion does not imply GPU release. The required failure callback synchronously stops producer I/O before Main releases its import or returns the delivery credit; the submission promise then rejects.
74
+
75
+ `@deepseek-ai/libreoffice-kit/native-render/electron/preload` exports `createNativeTextureReceiver` for a sandboxed preload. Bundle this entry with Electron external, and install its single document-wide receiver before starting production. Register at most one listener per view. Unsubscribe and revocation stop future deliveries; consumers retain delivered leases until explicit release. Missing consumers, frame extraction failures and throwing listeners release the imported texture. IPC authorization and application lifecycle remain with the caller.
76
+
77
+ ## Distribution
78
+
79
+ The public Kit package exports the Node SDK, SDK metadata, verifier, browser and Electron entries independently. Resolve the SDK JSON file and read its `header`, `sources`, and `staticLibraries[target]` paths relative to that directory. Normal installation and runtime use the bundled addon without compiling or downloading native binaries.
80
+
81
+ The browser painters/display, Electron adapter probe and generic texture ownership tests originate from DeepSeek Harness commit `21261bee8b9a820c62c9e42cade3ff644b747a29`, under `packages/client/native-render` and `apps/desktop`. Their unit tests are maintained with these implementations; DSH retains application integration tests.
82
+
83
+ The MIT SDK originated in DeepSeek Harness commit `4438b67c13d529c9882d89893ed5cd610ace11cc`. Its WebGPU adapter retains the Office fixes from LibreOffice Kit commit `2ae2de8c7e88df00e74ee538ebd5662f47c7a1df`. The Node binding and standalone C SDK share the source tree used by the Kit engine build. Protocol version 1 and engine ABI versions 1 and 2 are unchanged.
@@ -0,0 +1,83 @@
1
+ # 原生渲染 SDK
2
+
3
+ [English](README.md) | 中文
4
+
5
+ `@deepseek-ai/libreoffice-kit/native-render` 将经过授权的原生生产者连接到 Electron Main,像素不经过 DSH Host。这个公开子路径提供 Node/TypeScript 生产者与接收者,以及不依赖 Electron 的 C/C++ SDK。包内明确列出可供编译的源码;macOS 使用 IOSurface 与 Mach 端口传递,Windows 使用 D3D11 共享 NT 句柄和仅拥有者可访问的命名管道。独立 browser 与 Electron 子路径提供呈现和纹理所有权管理;消费方负责鉴权和应用控制协议。
6
+
7
+ 使用 `--omit=optional` 安装 Kit 可仅使用 SDK,不安装 Office 引擎或 Windows Office 管道依赖 Koffi。普通安装保留这些可选依赖的选择规则。SDK 安装和通信均不编译或下载二进制。
8
+
9
+ ## 接收端
10
+
11
+ 每个窗口创建一个 `createBudget(maxBytes)`,传给窗口内所有 `createReceiver({ maxFrames, maxBytes, budget, displayAdapter, readbackTimeoutMs, framePolicy }, onEvent)`。通过应用已有生命周期启动生产者,仅调用一次 `bindProducer(pid)` 绑定其 PID,并直接向生产者提供私有 `endpoint`。端点包含认证凭据,不得进入 Renderer 或日志。
12
+
13
+ 帧事件通过 `transport: "shared-texture"` 携带八字节原生句柄、生产者的 `frameId` 和接收端持有的 `deliveryId`。仅在 Electron 发出 `allReferencesReleased` 后调用 `release(deliveryId)`;提交队列和帧超时不解除消费者的所有权。生产者复用已释放的帧 ID 时,交付 ID 仍然不同。重复释放返回 false。`close()` 异步等待已提交 GPU 工作完成并回收所属线程;已交付资源保留至显式释放或接收端销毁。GPU 停滞可能使关闭持续等待;取消操作不会释放该 GPU 仍在使用的资源。
14
+
15
+ Windows shared-texture 接收端要求 `displayAdapter` 提供合成器实际使用的适配器 LUID;缺失时创建失败。生产者在认证时报告设备 LUID,接收端逐帧验证纹理的实际适配器。同卡时,带 keyed mutex 的生产者纹理直接导入;旧纹理复制到接收端持有的共享目标。`sourceKeyedMutex` 报告实际源纹理描述符,与握手声明无关。跨卡时,原生工作线程读回整张源纹理,将其预乘 BGRA 像素上传到合成器所用适配器上的共享纹理。JavaScript 仅接收句柄。`adapterId` 标识源卡;`presentationAdapterId` 标识导出纹理所属适配器,macOS IOSurface 的该值为 null。
16
+
17
+ 接收端在 Windows 上通过 Chromium 可识别的 keyed mutex 协调目标纹理的 GPU 访问;Electron 的引用释放回调控制生命周期,不能代替这项同步。跨卡复制遵循行跨度,GPU 读回复制完成后立即归还源信用;独立目标仍保持占用,直到 Electron 释放其交付。同卡复制和 macOS IOSurface 的源信用仍随交付释放。GPU 完成通知在设备支持时复用 fence 事件,否则使用有界 query 轮询。`readbackTimeoutMs` 限制原生帧准备与交付的时间;超时或取消会停止新工作,同时保留已提交复制的资源,直到 GPU 完成或设备移除。Worker 终止和接收端垃圾回收使用相同的异步清理。
18
+
19
+ [Chromium 152 使用 `INFINITE` 获取 key 0](https://github.com/chromium/chromium/blob/24072c1aa400ec4a89dc738b6b6acd12a8589b6f/gpu/command_buffer/service/dxgi_shared_handle_manager.cc#L129)。直接交付前,接收端工作线程有界获取并释放锁,检查源纹理是否就绪。这将可能的 CPU 等待移至该线程,不复制像素,也无法限制 Chromium 自身的等待。生产者必须在提交前释放锁,且在信用归还前不得访问表面。在检查后违反规则的生产者仍可能阻塞 Chromium 或触发 GPU 看门狗。
20
+
21
+ shared-texture 的 `framePolicy` 默认为 `ordered`,保留 Office 瓦片等独立请求与响应帧。连续流可以选择 `latest`:完成的中转读回替换尚未开始上传的帧,最多保留一帧等待和一帧上传。两个暂存槽允许源复制与等待目标的准备帧并存。目标被持有时停止后续上传;有序交付在两个暂存槽均占用时也停止读回。
22
+
23
+ 字节预算为每个 macOS 分配或声明 keyed mutex 的 Windows 同卡分配预留一份表面。旧同卡分配预留源和目标各一份。可选 hello 能力声明允许较小的预留;声明 keyed mutex 却提供无锁纹理的生产者会被拒绝。未声明但带锁的源纹理也可直接导入,预算仍按旧路径保守预留。中转最多预留 `N = maxFrames` 张源纹理、`N` 张独立目标及两张暂存纹理。目标和暂存容量按当前连接申请过的最大帧计算;源及池扩容通过一次原子预算授予。中转将每帧限制为 `maxBytes / (2N + 2)` 字节,向生产者声明其 `N` 倍的额度。三帧、256 MiB 配置下,三张 4K BGRA 源与五张接收端纹理合计预留 253.125 MiB。闲置存储保留预算;关闭释放独立池槽,仍被持有的各目标仅保留自己的预算直到释放。渲染进程队列和画布存储有独立限制;该预算不是进程内存上限。
24
+
25
+ `send(json)` 将控制消息加入有界队列,不让 Main 阻塞于原生 I/O。生产者消息以 `message` 事件到达。除端点凭据外还验证操作系统提供的对端身份。接收端只接受一个生产者连接且不能重新绑定。发生错误时消费者应终止或替换该连接。交付前丢弃的帧释放其原生资源;已交付帧在连接关闭后仍需显式释放。
26
+
27
+ ## Node/TypeScript 生产者
28
+
29
+ 在所属 Node 进程中,从 `@deepseek-ai/libreoffice-kit/native-render` 导入 `createProducer`。将接收端绑定至该 Node 进程的 PID;进程内插件使用 `process.pid`。传入私有端点、`maxPendingOperations`、`operationTimeoutMs` 及可选原生引擎描述符。等待 `ready`,并在所属插件的销毁流程中注册显式 `close()`。[TypeScript API](index.d.ts) 定义操作和资源所有权。
30
+
31
+ 专用原生工作线程串行执行连接、上传、引擎回调、锁等待及提交。独立轮询线程收到信用和控制事件后唤醒它;表面获取不使用定时器轮询。就绪前可以将操作入队;超出额度的普通操作被拒绝,包括控制消息。每个持有的租约均预留一个 discard 队列位置,因此队列满时仍可归还表面。等待额度的获取操作不会阻塞工作线程执行。获取超时仅拒绝该请求,不关闭生产者。传输故障或无法确认 GPU 完成的错误会关闭连接。`closed` 在排队操作全部完成,且工作线程、客户端和引擎销毁后解决。事件监听器异常被隔离;监听器自行负责诊断。Worker 终止通过异步原生清理处理。 设置 `DSH_RENDER_DIAGNOSTICS=1` 可将已隔离的生产者回调异常报告到 stderr。
32
+
33
+ `acquire(width, height)` 返回显式表面租约。等待 `writeBgra(buffer, stride)` 或 `render()`,再调用 `submit(frameId, metadata)` 或 `discard()`;表面的 `close()` 等同于 discard。忙碌或已消费的表面拒绝复用。垃圾回收不会归还帧额度。提交消耗租约,但底层纹理仍须等待接收端释放该帧后才可复用。
34
+
35
+ CPU 上传借用非共享的 Node Buffer,直到返回的 promise 完成。在此期间,调用者不得修改 Buffer、分离其底层 ArrayBuffer 或转移所有权。行跨度可以大于紧密排列的行宽。绑定层持有 Buffer,省去绑定层的中间复制;C SDK 仍需复制或上传像素。CPU 上传不属于 GPU 零拷贝。
36
+
37
+ 持续 GPU 渲染需要提供由另一 Node addon 通过 [dsh_render_node.h](include/dsh_render_node.h) 导出的引擎。[引擎回调](include/dsh_render_engine.h) 在生产者工作线程上串行运行,描述符保留至引擎销毁。`render` 借用已获取的原生纹理,并在返回前释放导入对象。Windows 回调在所提供设备的即时上下文上排队命令,由 SDK 持有 key 0;回调不得重复获取该锁。macOS 回调在返回前完成 GPU 工作。两者都须遵守取消回调。第三方回调必须及时返回;SDK 无法抢占任意引擎代码。引擎创建、更新和销毁不得调用 JavaScript。
38
+
39
+ `start({ width, height, generation, frameIntervalMs })` 在原生代码中持续渲染;`update(json, inputSequence)` 批量更新引擎状态,`stop()` 停止新帧。帧间隔包含渲染耗时,支持 `1000 / 60` 等小数;已过的截止时刻会被跳过,不会突发补帧。启动前必须释放手动租约。帧元数据包含请求 ID、视口代次、修订号和最新应用的输入序列。
40
+
41
+ 引擎 ABI v2 在获取表面前增加 `prepare`:有变化返回 1,无变化返回 0,失败返回 -1。无变化的帧不获取、不提交,也不消耗信用。已声明的变化在等待信用期间保持待处理;准备工作继续按流的节奏执行,新更新也可以替换信用到达后要绘制的状态。启动和调整尺寸强制生成一帧,更新会让下一次变化检查立即具备执行条件。ABI v1 保持持续渲染;Node 手动调用方通过不获取、不提交来跳过一帧。手动 `surface.render()` 不调用 `prepare`。
42
+
43
+ 同卡时,显示可以沿用 C 生产者的原生路径,不逐帧执行 JavaScript 或像素读回。端到端性能仍取决于引擎工作量、回调、节奏、GPU 选择及 CPU 复制。实际显示帧间隔、跳过的修订、输入到观测帧延迟和内存需分别测量;到达吞吐不等于显示 FPS。两种语言使用相同的接收端自动传输策略。
44
+
45
+ ## C/C++ 生产者
46
+
47
+ 包含 `include/dsh_render.h` 并链接对应的 `libdsh_render_sdk.a` 或 `dsh_render_sdk.lib`,也可以构建 `sdk.json` 列出的源码。API 不依赖 Node 或 Electron。仅一个线程执行轮询;获取、写入、提交和归还表面可以在另一线程执行。调用者必须串行使用同一图形上下文。先中断轮询并等待该线程退出,所有 API 调用返回后再关闭客户端。
48
+
49
+ 在 Windows 上,`dsh_render_connect_with_device` 接受应用的 `ID3D11Device`,并保留引用至关闭。传入空值或使用 `dsh_render_connect` 会创建默认设备。`dsh_render_connect_with_options` 还限制连接及握手时长,并接受在连接线程执行的取消回调。应用自行选择 GPU,DSH 选择传输方式。使用被接管设备的即时上下文时须与 SDK 写入串行执行。macOS 要求传入空设备。
50
+
51
+ 首次获取表面时返回空值,等待接收端授予分配额度。轮询后在所属应用适合的时机重试,不得忙等。分配请求进入共享 FIFO 预算队列。额度同时覆盖闲置池和显示中的帧。其他获取空值表示额度不足;终止性分配错误由轮询返回 `kind = -1` 和说明文本。轮询返回负数时停止处理,并在关闭前保留诊断信息。消费者必须限制操作总时长,超时后断开连接。
52
+
53
+ 纹理采用左上原点、sRGB、BGRA8 预乘像素。Windows 表面带有使用 key 0 的 keyed mutex。获取租约不加锁:SDK CPU 上传和引擎回调持有写锁;外部 GPU 写入方通过 `dsh_render_surface_keyed_mutex` 或导入 API 自行持锁。写入方将命令排队后释放 key 0,并在提交或归还前释放导入对象和视图。CPU 上传在返回前复制输入,不等待 GPU 完成;`dsh_render_write_bgra_with_timeout` 限制锁获取时间。`AcquireSync` 可能阻塞 CPU。macOS 写入方必须在提交或归还前完成 GPU 工作。复用表面需要重新获取租约,Windows 上还必须取得写锁。GPU 访问释放失败时,应关闭连接,不得复用表面。
54
+
55
+ 帧 ID 必须是 1 到 9007199254740991 之间的整数,且在尚未释放的提交中唯一。`dsh_render_submit` 提交成功返回 1,失败返回 0。提交失败后,有效的获取仍归调用方所有,可在满足相同 GPU 完成要求后重试或归还。
56
+
57
+ Windows Vulkan 和 D3D12 消费者在表面获取期间,通过 `dsh_render_surface_shared_handle` 借用 NT 句柄。消费者必须使用 SDK 所在的 GPU 适配器,并在导入 API 中启用 keyed mutex 同步,遵守上述所有权规则。句柄归 SDK 所有,调用方不得关闭。macOS 上该函数返回空值。接收端复制会在实际纹理描述符声明 keyed mutex 时有界获取源锁;旧纹理仍要求写入已经完成。
58
+
59
+ 应用 JSON、帧关联、输入语义、视口代次及输入确认由消费者协议定义。控制消息上限为 16383 个 UTF-8 字节。SDK 不向网页暴露任意进程启动或原生句柄。
60
+
61
+ ## 构建与验证
62
+
63
+ 在目标平台运行 `node scripts/build.mjs`,并提供完整且匹配的 Node 头文件。SDK 版本读取公开 Kit 包元数据。需要时显式设置 `DSH_NODE_INCLUDE`;Windows 还需要开发者工具链环境和 `DSH_NODE_LIB`。构建产出预编译 Node-API 插件、静态 SDK 及 SHA-256 回执。正常安装不调用编译器。公开 Kit 打包必须包含同一源码提交的四个平台,不能打包局部产物。校验同时检查插件和静态库架构、二进制和源码哈希、版本及协议。Desktop 运行时仅保留目标平台插件和必要元数据、许可证。
64
+
65
+ 构建后在本目录运行 `pnpm test`。测试沿用串行范围,覆盖 C 传输、Node 生产者、异步关闭及 Worker 终止。`DSH_NATIVE_RENDER_PACKAGE_ROOT` 可选择已安装 SDK,`DSH_NATIVE_RENDER_DIAGNOSTICS` 可将失败诊断保留到包外目录。性能及 Electron 共享纹理导入仍需实际 GPU 验证。
66
+
67
+ ## 浏览器与 Electron 呈现
68
+
69
+ `@deepseek-ai/libreoffice-kit/native-render/browser` 导出 `NativeFrameDisplay`、`createNativeFramePainter` 及其类型。导入此入口不会加载 Electron、Office 或原生 addon,也不会分配图形资源。泛型视图标识保留应用定义的字符串类型。应用负责视图创建、鉴权、生产者控制和输入仲裁。
70
+
71
+ `NativeFrameDisplay.present()` 接管帧租约,在绘制或拒绝后释放。隐藏文档等待恢复可见;代次变化或销毁会取消等待。所属应用另行更新生产者的可见性。移除画布前先销毁 display。
72
+
73
+ `@deepseek-ai/libreoffice-kit/native-render/electron` 为 Electron Main 导出 `detectNativeRenderAdapter` 和 `sendNativeFrame`。适配器探测在同一指定期限内等待 Chromium 完整 GPU 信息,并观察其导出的 Direct3D11 纹理。不支持的后端或软件合成模式会返回 `null`,不创建离屏窗口。取消操作同时覆盖 GPU 初始化和窗口构造。应用验证接收方和帧元数据后,`sendNativeFrame` 接管交付信用,直至提交失败或 Electron 释放最后一个 GPU 引用。其完成不代表 GPU 已释放。必需的失败回调在 Main 释放导入引用或归还交付信用前同步停止生产者 I/O;随后提交 Promise 拒绝。
74
+
75
+ `@deepseek-ai/libreoffice-kit/native-render/electron/preload` 为沙箱 preload 导出 `createNativeTextureReceiver`。打包此入口时将 Electron 保持为外部依赖,并在启动生产前安装文档唯一的接收器。每个视图最多注册一个监听器。取消订阅和撤销只停止未来交付;消费者显式释放前仍持有已交付租约。无消费者、提取帧失败或监听器抛错均会释放导入纹理。调用方负责 IPC 鉴权和应用生命周期。
76
+
77
+ ## 分发
78
+
79
+ 公开 Kit 包独立提供 Node SDK、SDK 元数据、校验器、browser 和 Electron 入口。以 SDK JSON 所在目录为根解析 `header`、`sources` 和 `staticLibraries[target]`。原生渲染无需 LibreOffice 引擎,只使用此功能时可用 `--omit=optional` 安装 Kit。正常安装和运行使用包内插件,不编译或下载额外原生二进制。
80
+
81
+ 浏览器绘制器、display、Electron 适配器探测及通用纹理所有权测试源自 DeepSeek Harness 提交 `21261bee8b9a820c62c9e42cade3ff644b747a29` 的 `packages/client/native-render` 与 `apps/desktop`。单元测试随实现维护;DSH 保留产品集成测试。
82
+
83
+ MIT SDK 来自 DeepSeek Harness 提交 `4438b67c13d529c9882d89893ed5cd610ace11cc`,WebGPU 适配器保留 LibreOffice Kit 提交 `2ae2de8c7e88df00e74ee538ebd5662f47c7a1df` 的 Office 修复。Node 绑定、独立 C SDK 与 Kit 引擎使用同一源码目录。协议版本 1 及引擎 ABI 版本 1、2 保持不变。
@@ -0,0 +1,101 @@
1
+ #ifndef DSH_RENDER_H
2
+ #define DSH_RENDER_H
3
+ #include <stddef.h>
4
+ #include <stdint.h>
5
+ #ifdef __cplusplus
6
+ extern "C" {
7
+ #endif
8
+ #define DSH_RENDER_PROTOCOL_VERSION 1
9
+ #define DSH_RENDER_TEXT_CAPACITY 16384
10
+ /** Opaque connected producer. One thread may poll while another acquires, writes,
11
+ * submits or discards. Callers must serialize use of the same graphics context.
12
+ */
13
+ typedef struct dsh_render_client dsh_render_client;
14
+ /** Pool-owned surface. Borrowed resources and imported objects are usable only
15
+ * during the acquisition; never destroy the SDK-owned resource.
16
+ */
17
+ typedef struct dsh_render_surface dsh_render_surface;
18
+ /** kind: 0 credit/timeout, 1 incoming JSON, -1 closed/error.
19
+ * Terminal events carry diagnostic text when available.
20
+ */
21
+ typedef struct dsh_render_event { int kind; char text[DSH_RENDER_TEXT_CAPACITY]; } dsh_render_event;
22
+ /** Connect to a private receiver. Blocks until the receiver binds this process. */
23
+ dsh_render_client* dsh_render_connect(const char* endpoint, char* error, size_t error_size);
24
+ /** Connect using the application's ID3D11Device on Windows; NULL selects the default
25
+ * device. The client retains a device reference until close. macOS requires NULL.
26
+ * Serialize the device's immediate context with all SDK writes.
27
+ */
28
+ dsh_render_client* dsh_render_connect_with_device(const char* endpoint, void* device, char* error, size_t error_size);
29
+ /** Bounded connection options. cancelled is optional and runs on the connecting
30
+ * thread; its context must remain alive until connect_with_options returns.
31
+ */
32
+ typedef struct dsh_render_connect_options {
33
+ void* device;
34
+ uint32_t timeout_ms;
35
+ void* cancellation_context;
36
+ int (*cancelled)(void*);
37
+ } dsh_render_connect_options;
38
+ /** Connect with a positive timeout and optional cancellation, including PID bind
39
+ * waiting. Device ownership and platform rules match connect_with_device.
40
+ */
41
+ dsh_render_client* dsh_render_connect_with_options(const char* endpoint,
42
+ const dsh_render_connect_options* options, char* error, size_t error_size);
43
+ /** Acquire BGRA8 premultiplied top-left pixels; NULL means allocation pending or no credit; poll reports terminal allocation errors. */
44
+ dsh_render_surface* dsh_render_acquire(dsh_render_client* client, uint32_t width, uint32_t height);
45
+ /** Borrow an IOSurfaceRef (macOS) or ID3D11Texture2D* (Windows) while acquired.
46
+ * Windows external writers acquire/release key 0 around GPU commands (see
47
+ * surface_keyed_mutex); macOS writers complete GPU writes before submit/discard.
48
+ * Release imported objects/views before ending the acquisition.
49
+ */
50
+ void* dsh_render_surface_native(dsh_render_surface* surface);
51
+ /** Borrow the Windows shared NT handle while this surface is acquired; NULL on macOS.
52
+ * Do not close the borrowed handle. External imports must synchronize with key 0
53
+ * and release access and imported objects before submit/discard.
54
+ */
55
+ void* dsh_render_surface_shared_handle(dsh_render_surface* surface);
56
+ /** Return the ID3D11Device* borrowed until client close, or NULL on macOS.
57
+ * External GPU imports must use the same adapter as this device.
58
+ */
59
+ void* dsh_render_device(dsh_render_client* client);
60
+ /** Borrow the acquired Windows surface's IDXGIKeyedMutex, or NULL on macOS.
61
+ * acquire itself never locks. External writers acquire key 0 before issuing GPU
62
+ * commands and release key 0 before submit/discard, without waiting for completion.
63
+ * SDK write_bgra and engine render own this lock; do not lock around those calls.
64
+ * Do not release the borrowed COM reference. AcquireSync may block the CPU.
65
+ */
66
+ void* dsh_render_surface_keyed_mutex(dsh_render_surface* surface);
67
+ /** Copy CPU BGRA rows; return 1 on success, 0 on failure.
68
+ * Windows acquires key 0 with a 1000 ms timeout and releases it after enqueueing
69
+ * the upload. Input memory may be reused on return; GPU completion is asynchronous.
70
+ */
71
+ int dsh_render_write_bgra(dsh_render_surface* surface, const void* pixels, size_t stride);
72
+ /** CPU upload with a positive keyed-mutex acquisition timeout. Failure leaves completion
73
+ * uncertain; close the client without discarding or reusing the acquisition.
74
+ */
75
+ int dsh_render_write_bgra_with_timeout(dsh_render_surface* surface, const void* pixels, size_t stride, uint32_t timeout_ms);
76
+ /** Submit after Windows GPU writes are queued and the writer released key 0;
77
+ * macOS GPU writes must be complete. Release all imported objects/views first.
78
+ * frame_id must be 1..9007199254740991 and unique among outstanding submissions.
79
+ * Return 1 on submission; the surface cannot be reused until it is reacquired.
80
+ * Return 0 on failure; a valid acquisition stays with the caller for retry or discard.
81
+ */
82
+ int dsh_render_submit(dsh_render_client* client, dsh_render_surface* surface, uint64_t frame_id, const char* metadata_json);
83
+ /** Return an acquired, unsubmitted surface under the same GPU ownership rules as
84
+ * submit. If releasing GPU access failed, terminate the connection instead of
85
+ * discarding. The next writer must acquire key 0 even after a discard.
86
+ */
87
+ void dsh_render_discard(dsh_render_client* client, dsh_render_surface* surface);
88
+ /** Poll and apply credits; return event->kind. Only one thread may poll at a time.
89
+ * A negative result ends processing; preserve any diagnostic text before closing.
90
+ */
91
+ int dsh_render_poll(dsh_render_client* client, uint32_t timeout_ms, dsh_render_event* event);
92
+ /** Send application JSON to the receiver; never sends pixel bytes. */
93
+ int dsh_render_send(dsh_render_client* client, const char* json);
94
+ /** Interrupt polling without freeing client. Join polling thread before close. */
95
+ void dsh_render_interrupt(dsh_render_client* client);
96
+ /** Destroy producer after all its API calls have returned. Receiver references stay valid. */
97
+ void dsh_render_close(dsh_render_client* client);
98
+ #ifdef __cplusplus
99
+ }
100
+ #endif
101
+ #endif