dsh-gallery 0.17.0 → 1.1.0

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.
package/host/protocol.js CHANGED
@@ -1,4 +1,4 @@
1
- // GENERATED from src/shared/protocol.js — 请勿手改
1
+ // GENERATED from src/shared/protocol.js — 请勿手改
2
2
  /**
3
3
  * 协议常量 —— Host 与 Client 的唯一真源。
4
4
  *
@@ -62,6 +62,37 @@ export function clamp01(v) {
62
62
  return n
63
63
  }
64
64
 
65
+ /** 把数夹到 [min, max] 闭区间内。 */
66
+ function clampNum(v, min, max) {
67
+ const n = Number(v)
68
+ if (!Number.isFinite(n)) return min
69
+ if (n < min) return min
70
+ if (n > max) return max
71
+ return n
72
+ }
73
+
74
+ /**
75
+ * v0.16.0 选段播放决策(纯函数,便于单测)。
76
+ *
77
+ * 老板 2026-11-13 11:56 反馈:播放必须跟选段走 —— **从入点起播、到出点结束**,
78
+ * 而不是播放器自己按整段播(截图里选段是 2:16–3:21,播放头却停在 0:29)。
79
+ * 拖动端点 / 点轨道时(scrubbing)不做钳制,否则播放头会被反复拽回,没法目视选帧。
80
+ *
81
+ * @returns {{ action: 'none' | 'stop' | 'seekIn', seekTo?: number }}
82
+ */
83
+ function trimPlaybackDecision(now, inPoint, outPoint, opts) {
84
+ const o = opts || {}
85
+ if (!Number.isFinite(now)) return { action: 'none' }
86
+ // 区间还没初始化(或过短)时不要干预原生播放
87
+ if (!(outPoint > inPoint + 0.05)) return { action: 'none' }
88
+ if (o.scrubbing === true) return { action: 'none' }
89
+ // 到出点:停住,不循环 —— 老板要的是「到出点结束」
90
+ if (now >= outPoint - 0.02) return { action: 'stop', seekTo: Math.min(now, outPoint) }
91
+ // 播放跑到入点之前(例如用原生进度条拖到了区间外)→ 拉回入点
92
+ if (now < inPoint - 0.25 && o.paused !== true) return { action: 'seekIn', seekTo: inPoint }
93
+ return { action: 'none' }
94
+ }
95
+
65
96
  /** 校验并规整一条批注;不合法返回 null。 */
66
97
  export function normalizeAnnotation(a) {
67
98
  if (a === null || typeof a !== "object") return null
@@ -80,3 +111,374 @@ export function normalizeAnnotation(a) {
80
111
  shape, x, y, w, h, note, frameMs,
81
112
  }
82
113
  }
114
+
115
+ /**
116
+ * 批注层几何(v0.14.4):SVG 与 <img> 共用同一布局盒、同一组 translate/scale。
117
+ * 图片按 object-fit:contain 居中后,实际显示盒往往小于预览容器;旧版 SVG 覆盖整个
118
+ * 容器且不带变换,1:1 就可能错位,放大后更彻底脱框。抽成纯函数便于离线钉死契约。
119
+ */
120
+ function annotationSvgStyle(imgBox, pan, zoom, transition) {
121
+ return {
122
+ position: 'absolute',
123
+ left: `${imgBox.left}px`,
124
+ top: `${imgBox.top}px`,
125
+ width: `${imgBox.width}px`,
126
+ height: `${imgBox.height}px`,
127
+ transform: `translate(${pan.x}px, ${pan.y}px) scale(${zoom})`,
128
+ transformOrigin: '50% 50%',
129
+ transition,
130
+ }
131
+ }
132
+
133
+ /**
134
+ * 标注态「按下要不要拦冒泡 / 交给谁」的判定(v0.14.4)。
135
+ * 查看器本身就支持中键拖拽平移;标注层过去对所有按键一律 stopPropagation,
136
+ * 把中键吞掉,导致标注时挪不动图。现在:中键放行给查看器平移,左键留给画框。
137
+ */
138
+ function annotationPointerRouting(active, button) {
139
+ // 未激活:不拦(图片 pointerEvents:none,事件本就落到查看器)
140
+ if (!active) return 'pass'
141
+ // 中键(1):放行给查看器的中键拖拽平移,框跟着图走(已画框与图共用 pan/zoom)
142
+ if (button === 1) return 'pan'
143
+ // 左键(0)及其余:拦住,交给标注层画框;顺带防止弹窗输入被查看器拖图抢走
144
+ return 'draw'
145
+ }
146
+
147
+ /** 标注层 SVG 的光标:中键平移进行中显示抓握,否则画框态为十字。 */
148
+ function annotationSvgCursor(active, dragging, zoom) {
149
+ if (!active) return 'default'
150
+ if (dragging && zoom > 1) return 'grabbing'
151
+ return 'crosshair'
152
+ }
153
+
154
+ /**
155
+ * 遮罩编码契约(v0.14.5 本机 MVP)—— 本机实证,不是推测:
156
+ * ComfyUI 官方 LoadImage 与本机孤海 LoadImageGoohai 的 MASK 输出都是 `1 - alpha/255`。
157
+ * 所以「框内 alpha=0、框外 alpha=255」的普通 RGBA PNG 直接就是可用遮罩,
158
+ * RGB 必须保留原图像素(LoadImage 的 IMAGE 输出仍拿它做局部重绘)。
159
+ * 这与 clipspace-painted-* 涂鸦遮罩等价,但不必复刻 ComfyUI 画布交互。
160
+ *
161
+ * 注意:遮罩是**新资产**(同视频截帧,落盘并登记到当前对话),不是批注;
162
+ * 批注依旧只存内存。导出的路径只进反馈草稿,零自动发送、插件零外部请求。
163
+ */
164
+
165
+ /** 原图像素上限:超过拒绝生成,避免超大图卡死前端(host 另有 24 MB 兜底)。 */
166
+ const MASK_MAX_PIXELS = 24000000
167
+
168
+ /** 归一化框选批注 → 原图像素矩形(clamp + 至少 1px,不越界)。 */
169
+ function maskPixelRect(annotation, width, height) {
170
+ const w = Math.max(1, Math.round(Number(width) || 0))
171
+ const h = Math.max(1, Math.round(Number(height) || 0))
172
+ const x = clamp01(annotation?.x)
173
+ const y = clamp01(annotation?.y)
174
+ let nw = clamp01(annotation?.w)
175
+ let nh = clamp01(annotation?.h)
176
+ if (nw > 0 && x + nw > 1) nw = 1 - x
177
+ if (nh > 0 && y + nh > 1) nh = 1 - y
178
+ const x0 = Math.min(w - 1, Math.max(0, Math.round(x * w)))
179
+ const y0 = Math.min(h - 1, Math.max(0, Math.round(y * h)))
180
+ const x1 = Math.min(w, Math.max(x0 + 1, Math.round((x + nw) * w)))
181
+ const y1 = Math.min(h, Math.max(y0 + 1, Math.round((y + nh) * h)))
182
+ return { x: x0, y: y0, w: x1 - x0, h: y1 - y0, width: w, height: h }
183
+ }
184
+
185
+ /** 单像素 alpha:框内 0(mask=1 待重绘),框外 255(mask=0 保留)。 */
186
+ function maskAlphaAt(px, py, rect) {
187
+ const inside = px >= rect.x && px < rect.x + rect.w && py >= rect.y && py < rect.y + rect.h
188
+ return inside ? 0 : 255
189
+ }
190
+
191
+ /* ------------------------------------------------------------------ *
192
+ * v0.14.6 右键多点选区(老板 2026-11-12 拍板):
193
+ * 标记态下左键仍是矩形批注,右键逐点点击 4–20 个顶点,闭合成实心多边形。
194
+ * 实测口径(见验证报告第九节):必须是「实心、贴合目标外接框」的块,
195
+ * 描笔画的镂空线框 / 椭圆 / 大矩形都会出白底;多边形天然实心且面积可量。
196
+ * ------------------------------------------------------------------ */
197
+ const POLYGON_LIMITS = { min: 4, max: 20, closeRadius: 0.02, minArea: 0.0001 }
198
+
199
+ /* ------------------------------------------------------------------ *
200
+ * 选区纯色半透明填充(v0.14.7 引入;老板 2026-11-12 20:22 再定版):
201
+ * 填充 0.4 / 轮廓 0.7,界面选区与「填充预览图」共用红 / 绿 / 蓝三色;
202
+ * 导出的主 alpha 遮罩仍是「RGB 原图 + alpha 二值」,ComfyUI 链路一点不动。
203
+ * 轮廓视觉宽度统一 1.5px:界面 SVG 用 non-scaling-stroke 直接画 1.5px;
204
+ * 导出预览图按「DSH 缩到 200px 长边后仍留 1.5px」反推线宽 —— 固定 2px
205
+ * 描边缩完会消失,过宽的边线又会糊住选区,两端共用同一个基准常量。
206
+ * ------------------------------------------------------------------ */
207
+ const MASK_FILL_COLORS = Object.freeze({
208
+ green: { rgb: [94, 214, 150], label: '绿' },
209
+ red: { rgb: [239, 68, 68], label: '红' },
210
+ blue: { rgb: [59, 130, 246], label: '蓝' },
211
+ })
212
+ const MASK_FILL_KEYS = Object.keys(MASK_FILL_COLORS)
213
+ const MASK_FILL_ALPHA = 0.4
214
+ const MASK_STROKE_ALPHA = 0.7
215
+ /** 轮廓视觉宽度基准(px):界面直接画,导出预览图按缩略图比例反推。 */
216
+ const MASK_STROKE_PX = 1.5
217
+
218
+ /** 未知颜色一律回落绿色,避免脏值写进文件名 / 元数据。 */
219
+ function maskFillColor(key) {
220
+ return Object.prototype.hasOwnProperty.call(MASK_FILL_COLORS, key)
221
+ ? MASK_FILL_COLORS[key] : MASK_FILL_COLORS.green
222
+ }
223
+
224
+ function maskFillRgba(key, alpha = MASK_FILL_ALPHA) {
225
+ const [r, g, b] = maskFillColor(key).rgb
226
+ return `rgba(${r}, ${g}, ${b}, ${alpha})`
227
+ }
228
+
229
+ /**
230
+ * 预览图轮廓线宽:以「DSH 缩略图长边 200px 时描边仍约 1.5px」反推,
231
+ * 夹在 6–40px,避免小图线条消失、超大图线条糊成一片。纯函数,测试跑真身。
232
+ */
233
+ function maskStrokeWidth(width, height) {
234
+ const w = Math.max(1, Number(width) || 0)
235
+ const h = Math.max(1, Number(height) || 0)
236
+ const scale = Math.max(w, h) / 200
237
+ return Math.max(6, Math.min(40, Math.round(MASK_STROKE_PX * scale)))
238
+ }
239
+
240
+ /** 预览层的填充 / 轮廓描述(纯函数,测试直接跑真身):多边形优先,矩形回落。 */
241
+ function maskOverlayPath(rect, polygonPx, colorKey) {
242
+ const hasPolygon = Array.isArray(polygonPx) && polygonPx.length >= 3
243
+ return {
244
+ key: Object.prototype.hasOwnProperty.call(MASK_FILL_COLORS, colorKey) ? colorKey : 'green',
245
+ label: maskFillColor(colorKey).label,
246
+ rgba: maskFillRgba(colorKey, MASK_FILL_ALPHA),
247
+ strokeRgba: maskFillRgba(colorKey, MASK_STROKE_ALPHA),
248
+ strokeWidth: maskStrokeWidth(rect?.width, rect?.height),
249
+ points: hasPolygon ? polygonPx : null,
250
+ rect: hasPolygon ? null : { x: rect.x, y: rect.y, w: rect.w, h: rect.h },
251
+ }
252
+ }
253
+
254
+ /** 顶点数组的归一外接框;points 既接受 [{x,y}] 也接受 [[x,y]]。 */
255
+ function polygonBBox(points) {
256
+ const xs = points.map((p) => clamp01(Array.isArray(p) ? p[0] : p?.x))
257
+ const ys = points.map((p) => clamp01(Array.isArray(p) ? p[1] : p?.y))
258
+ const x0 = Math.min(...xs)
259
+ const y0 = Math.min(...ys)
260
+ const x1 = Math.max(...xs)
261
+ const y1 = Math.max(...ys)
262
+ return { x: x0, y: y0, w: clamp01(x1 - x0), h: clamp01(y1 - y0) }
263
+ }
264
+
265
+ /** 鞋带公式:归一化面积,用来挡掉「点成一条线」的退化选区。 */
266
+ function polygonArea(points) {
267
+ let sum = 0
268
+ for (let i = 0, j = points.length - 1; i < points.length; j = i, i += 1) {
269
+ const xi = Array.isArray(points[i]) ? points[i][0] : points[i].x
270
+ const yi = Array.isArray(points[i]) ? points[i][1] : points[i].y
271
+ const xj = Array.isArray(points[j]) ? points[j][0] : points[j].x
272
+ const yj = Array.isArray(points[j]) ? points[j][1] : points[j].y
273
+ sum += (xj * yi) - (xi * yj)
274
+ }
275
+ return Math.abs(sum) / 2
276
+ }
277
+
278
+ /** 射线法(无 canvas 环境兜底,也用于离线断言钉死「多边形内 alpha=0」)。 */
279
+ function pointInPolygon(px, py, points) {
280
+ let inside = false
281
+ for (let i = 0, j = points.length - 1; i < points.length; j = i, i += 1) {
282
+ const xi = points[i][0]
283
+ const yi = points[i][1]
284
+ const xj = points[j][0]
285
+ const yj = points[j][1]
286
+ const hit = ((yi > py) !== (yj > py))
287
+ && (px < (((xj - xi) * (py - yi)) / (yj - yi)) + xi)
288
+ if (hit) inside = !inside
289
+ }
290
+ return inside
291
+ }
292
+
293
+ /** 归一化顶点 → 原图像素顶点;点不合法或数量越界一律返回 null。 */
294
+ function normalizePolygon(value, width, height) {
295
+ if (!Array.isArray(value) || value.length < POLYGON_LIMITS.min || value.length > POLYGON_LIMITS.max) return null
296
+ const w = Math.max(1, Math.round(Number(width) || 0))
297
+ const h = Math.max(1, Math.round(Number(height) || 0))
298
+ const pts = []
299
+ for (const p of value) {
300
+ const nx = Number(Array.isArray(p) ? p[0] : p?.x)
301
+ const ny = Number(Array.isArray(p) ? p[1] : p?.y)
302
+ if (!Number.isFinite(nx) || !Number.isFinite(ny)) return null
303
+ pts.push([clamp01(nx) * w, clamp01(ny) * h])
304
+ }
305
+ return pts
306
+ }
307
+
308
+ /**
309
+ * 多边形 → 全尺寸二值 alpha 层(0 = 待重绘,255 = 保留)。
310
+ * 优先用离屏 canvas 填充(浏览器自动处理自交、抗锯齿与非零环绕),
311
+ * 只在 bbox 子画布上读一次像素,避免全图再开一份 ImageData;
312
+ * 读回后按 >127 强制二值,保持与 ComfyUI `MASK = 1 - alpha/255` 的实证契约一致。
313
+ * Node / 无 canvas 环境退化为射线法,测试可直接跑真身。
314
+ */
315
+ function polygonAlphaLayer(points, width, height) {
316
+ const w = Math.max(1, Math.round(Number(width) || 0))
317
+ const h = Math.max(1, Math.round(Number(height) || 0))
318
+ const out = new Uint8Array(w * h).fill(255)
319
+ const xs = points.map((p) => p[0])
320
+ const ys = points.map((p) => p[1])
321
+ const x0 = Math.max(0, Math.min(w - 1, Math.floor(Math.min(...xs))))
322
+ const y0 = Math.max(0, Math.min(h - 1, Math.floor(Math.min(...ys))))
323
+ const x1 = Math.min(w, Math.max(x0 + 1, Math.ceil(Math.max(...xs))))
324
+ const y1 = Math.min(h, Math.max(y0 + 1, Math.ceil(Math.max(...ys))))
325
+ const bw = x1 - x0
326
+ const bh = y1 - y0
327
+ let ctx = null
328
+ try {
329
+ if (typeof OffscreenCanvas === 'function') {
330
+ const canvas = new OffscreenCanvas(bw, bh)
331
+ ctx = canvas.getContext('2d', { willReadFrequently: true })
332
+ } else if (typeof document !== 'undefined') {
333
+ const canvas = document.createElement('canvas')
334
+ canvas.width = bw
335
+ canvas.height = bh
336
+ ctx = canvas.getContext('2d', { willReadFrequently: true })
337
+ }
338
+ } catch { ctx = null }
339
+ if (ctx !== null) {
340
+ ctx.fillStyle = '#000'
341
+ ctx.fillRect(0, 0, bw, bh)
342
+ ctx.fillStyle = '#fff'
343
+ ctx.beginPath()
344
+ ctx.moveTo(points[0][0] - x0, points[0][1] - y0)
345
+ for (let i = 1; i < points.length; i += 1) ctx.lineTo(points[i][0] - x0, points[i][1] - y0)
346
+ ctx.closePath()
347
+ ctx.fill()
348
+ const sub = ctx.getImageData(0, 0, bw, bh).data
349
+ for (let py = 0; py < bh; py += 1) {
350
+ for (let px = 0; px < bw; px += 1) {
351
+ if (sub[((py * bw) + px) * 4] > 127) out[((py + y0) * w) + (px + x0)] = 0
352
+ }
353
+ }
354
+ } else {
355
+ for (let py = y0; py < y1; py += 1) {
356
+ for (let px = x0; px < x1; px += 1) {
357
+ if (pointInPolygon(px + 0.5, py + 0.5, points)) out[(py * w) + px] = 0
358
+ }
359
+ }
360
+ }
361
+ return out
362
+ }
363
+
364
+ /* ------------------------------------------------------------------ *
365
+ * RGBA 主遮罩 PNG 编码器(v0.14.9 修复 canvas 预乘 alpha 丢 RGB)
366
+ *
367
+ * 本机实证:canvas 内部是预乘 alpha 存储,putImageData → convertToBlob 往返后,
368
+ * alpha=0 的选区内 RGB 会被清零(区内均值差 147.39),而 ComfyUI
369
+ * #369 LoadImageGoohai 的 IMAGE 输出需要原图 RGB。主遮罩必须直接从
370
+ * 「RGB 原图 + 只改过 alpha」的 ImageData 编 PNG,一次也不回写 canvas。
371
+ * ------------------------------------------------------------------ */
372
+
373
+ /** CRC-32(IEEE 802.3),PNG chunk 校验用。 */
374
+ function pngCrc32(bytes) {
375
+ let c = 0xffffffff
376
+ for (let i = 0; i < bytes.length; i += 1) {
377
+ c ^= bytes[i]
378
+ for (let k = 0; k < 8; k += 1) c = (c >>> 1) ^ (0xedb88320 & -(c & 1))
379
+ }
380
+ return (c ^ 0xffffffff) >>> 0
381
+ }
382
+
383
+ /** 组装一个 PNG chunk:长度 + 类型 + 数据 + CRC。 */
384
+ function pngChunk(type, data) {
385
+ const out = new Uint8Array(12 + data.length)
386
+ const view = new DataView(out.buffer)
387
+ view.setUint32(0, data.length)
388
+ for (let i = 0; i < 4; i += 1) out[4 + i] = type.charCodeAt(i)
389
+ out.set(data, 8)
390
+ view.setUint32(8 + data.length, pngCrc32(out.subarray(4, 8 + data.length)))
391
+ return out
392
+ }
393
+
394
+ /** ImageData → PNG 扫描线:每行前置 filter=0,RGBA 四通道原样搬运。 */
395
+ function pngScanlines(imageData, width, height) {
396
+ const src = imageData.data
397
+ const stride = width * 4
398
+ const out = new Uint8Array((stride + 1) * height)
399
+ let p = 0
400
+ for (let y = 0; y < height; y += 1) {
401
+ out[p] = 0
402
+ p += 1
403
+ out.set(src.subarray(y * stride, (y + 1) * stride), p)
404
+ p += stride
405
+ }
406
+ return out
407
+ }
408
+
409
+ /** Adler-32,zlib 尾部校验。 */
410
+ function pngAdler32(bytes) {
411
+ let a = 1
412
+ let b = 0
413
+ for (let i = 0; i < bytes.length; i += 1) {
414
+ a = (a + bytes[i]) % 65521
415
+ b = (b + a) % 65521
416
+ }
417
+ return ((b << 16) | a) >>> 0
418
+ }
419
+
420
+ /** 拼接若干 Uint8Array。 */
421
+ function pngConcat(parts) {
422
+ const out = new Uint8Array(parts.reduce((s, p) => s + p.length, 0))
423
+ let p = 0
424
+ for (const part of parts) { out.set(part, p); p += part.length }
425
+ return out
426
+ }
427
+
428
+ /** zlib「stored」无压缩流,同步兜底(CompressionStream 不可用时)。 */
429
+ function pngZlibStored(bytes) {
430
+ const parts = [new Uint8Array([0x78, 0x01])]
431
+ let off = 0
432
+ while (off < bytes.length) {
433
+ const len = Math.min(65535, bytes.length - off)
434
+ const last = off + len >= bytes.length ? 1 : 0
435
+ const blk = new Uint8Array(5 + len)
436
+ blk[0] = last
437
+ blk[1] = len & 0xff
438
+ blk[2] = (len >> 8) & 0xff
439
+ blk[3] = (~len) & 0xff
440
+ blk[4] = ((~len) >> 8) & 0xff
441
+ blk.set(bytes.subarray(off, off + len), 5)
442
+ parts.push(blk)
443
+ off += len
444
+ }
445
+ const tail = new Uint8Array(4)
446
+ new DataView(tail.buffer).setUint32(0, pngAdler32(bytes))
447
+ parts.push(tail)
448
+ return pngConcat(parts)
449
+ }
450
+
451
+ /**
452
+ * ImageData → RGBA PNG 字节。优先 CompressionStream('deflate') 出标准 zlib 流,
453
+ * 不可用则退回同步 stored 流;两条路都不经过 canvas,RGB 一像素不丢。
454
+ */
455
+ async function encodeMaskPngBytes(imageData, width, height) {
456
+ const w = Math.max(1, Math.round(Number(width) || 0))
457
+ const h = Math.max(1, Math.round(Number(height) || 0))
458
+ const ihdr = new Uint8Array(13)
459
+ const iv = new DataView(ihdr.buffer)
460
+ iv.setUint32(0, w)
461
+ iv.setUint32(4, h)
462
+ ihdr[8] = 8
463
+ ihdr[9] = 6
464
+ const raw = pngScanlines(imageData, w, h)
465
+ let idat = null
466
+ if (typeof CompressionStream === 'function' && typeof Blob === 'function' && typeof Response === 'function') {
467
+ try {
468
+ const stream = new Blob([raw]).stream().pipeThrough(new CompressionStream('deflate'))
469
+ idat = new Uint8Array(await new Response(stream).arrayBuffer())
470
+ } catch {
471
+ idat = null
472
+ }
473
+ }
474
+ if (idat === null) idat = pngZlibStored(raw)
475
+ return pngConcat([
476
+ new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10]),
477
+ pngChunk('IHDR', ihdr),
478
+ pngChunk('IDAT', idat),
479
+ pngChunk('IEND', new Uint8Array(0)),
480
+ ])
481
+ }
482
+
483
+
484
+ /** tab 类型的身份;也是正文与标题在 keyed slot 里的 key。 */