@rosepetal/node-red-contrib-image-tools 1.6.3 → 1.7.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.
Files changed (60) hide show
  1. package/.claude/rules/node-implementation-template.md +1 -1
  2. package/README.md +2 -0
  3. package/node-red-contrib-image-tools/lib/bmp-decode.js +18 -68
  4. package/node-red-contrib-image-tools/lib/cpp-bridge.js +202 -104
  5. package/node-red-contrib-image-tools/lib/node-utils.js +78 -78
  6. package/node-red-contrib-image-tools/nodes/blend/add-bbs.html +11 -4
  7. package/node-red-contrib-image-tools/nodes/blend/add-mask.html +11 -4
  8. package/node-red-contrib-image-tools/nodes/blend/add-masks.html +11 -4
  9. package/node-red-contrib-image-tools/nodes/blend/blend.html +11 -4
  10. package/node-red-contrib-image-tools/nodes/io/folder-in.js +98 -46
  11. package/node-red-contrib-image-tools/nodes/io/image-in.js +3 -4
  12. package/node-red-contrib-image-tools/nodes/io/image-out.html +11 -4
  13. package/node-red-contrib-image-tools/nodes/io/image-out.js +93 -146
  14. package/node-red-contrib-image-tools/nodes/mix/advanced-mosaic.html +11 -4
  15. package/node-red-contrib-image-tools/nodes/mix/concat.html +11 -4
  16. package/node-red-contrib-image-tools/nodes/mix/mosaic.html +11 -4
  17. package/node-red-contrib-image-tools/nodes/specialized/cropBB.js +3 -3
  18. package/node-red-contrib-image-tools/nodes/specialized/heat-diff.js +3 -3
  19. package/node-red-contrib-image-tools/nodes/specialized/image-align.html +3 -2
  20. package/node-red-contrib-image-tools/nodes/specialized/image-align.js +3 -3
  21. package/node-red-contrib-image-tools/nodes/transform/color-convert.js +3 -3
  22. package/node-red-contrib-image-tools/nodes/transform/crop.html +11 -4
  23. package/node-red-contrib-image-tools/nodes/transform/crop.js +3 -3
  24. package/node-red-contrib-image-tools/nodes/transform/filter.html +11 -4
  25. package/node-red-contrib-image-tools/nodes/transform/filter.js +3 -3
  26. package/node-red-contrib-image-tools/nodes/transform/padding.html +11 -4
  27. package/node-red-contrib-image-tools/nodes/transform/padding.js +3 -3
  28. package/node-red-contrib-image-tools/nodes/transform/resize.html +3 -3
  29. package/node-red-contrib-image-tools/nodes/transform/resize.js +3 -3
  30. package/node-red-contrib-image-tools/nodes/transform/rotate.html +11 -4
  31. package/node-red-contrib-image-tools/nodes/transform/rotate.js +3 -3
  32. package/npm/darwin-arm64/package.json +1 -1
  33. package/npm/darwin-x64/package.json +1 -1
  34. package/npm/linux-arm64/package.json +1 -1
  35. package/npm/linux-x64/package.json +1 -1
  36. package/npm/linuxmusl-x64/package.json +1 -1
  37. package/npm/win32-x64/package.json +1 -1
  38. package/package.json +6 -6
  39. package/rosepetal-image-engine/binding.gyp +2 -1
  40. package/rosepetal-image-engine/src/add-bbs.cpp +123 -123
  41. package/rosepetal-image-engine/src/add-mask.cpp +30 -15
  42. package/rosepetal-image-engine/src/add-masks.cpp +145 -102
  43. package/rosepetal-image-engine/src/advanced-mosaic.cpp +200 -129
  44. package/rosepetal-image-engine/src/blend.cpp +34 -20
  45. package/rosepetal-image-engine/src/codec.cpp +157 -0
  46. package/rosepetal-image-engine/src/color-convert.cpp +22 -19
  47. package/rosepetal-image-engine/src/concat.cpp +38 -43
  48. package/rosepetal-image-engine/src/crop.cpp +23 -26
  49. package/rosepetal-image-engine/src/draw.cpp +33 -10
  50. package/rosepetal-image-engine/src/filter.cpp +22 -26
  51. package/rosepetal-image-engine/src/heat-diff.cpp +31 -8
  52. package/rosepetal-image-engine/src/image-align.cpp +36 -32
  53. package/rosepetal-image-engine/src/main.cpp +4 -0
  54. package/rosepetal-image-engine/src/mosaic.cpp +31 -40
  55. package/rosepetal-image-engine/src/padding.cpp +30 -29
  56. package/rosepetal-image-engine/src/resize.cpp +20 -25
  57. package/rosepetal-image-engine/src/rotate.cpp +22 -23
  58. package/rosepetal-image-engine/src/utils.h +243 -144
  59. package/scripts/dual-register.js +32 -25
  60. package/scripts/sync-version.js +58 -41
@@ -10,6 +10,7 @@ try {
10
10
  } catch (err) {
11
11
  sharp = null;
12
12
  }
13
+ const Cpp = require('./cpp-bridge.js');
13
14
 
14
15
 
15
16
  module.exports = function(RED) {
@@ -372,6 +373,20 @@ module.exports = function(RED) {
372
373
  return opts;
373
374
  }
374
375
 
376
+ /**
377
+ * Returns a Sharp-compatible raw image (GRAY / RGB / RGBA) for a normalized
378
+ * raw image object. BGR/BGRA inputs are converted by the native engine on
379
+ * the libuv thread pool — never with a pixel loop on the event loop.
380
+ * @returns {Promise<{data: Buffer, width: number, height: number, channels: number, colorSpace: string}>}
381
+ */
382
+ utils.toSharpRaw = async function(normalized) {
383
+ const colorSpace = normalized.colorSpace;
384
+ if (colorSpace !== 'BGR' && colorSpace !== 'BGRA') return normalized;
385
+ const target = colorSpace === 'BGR' ? 'RGB' : 'RGBA';
386
+ const { image } = await Cpp.colorConvert(normalized, target, 'raw');
387
+ return image;
388
+ }
389
+
375
390
  /**
376
391
  * Encodes a raw image object to WebP via Sharp with advanced options.
377
392
  * Modeled on rawToJpeg() — performs BGR→RGB swap and feeds Sharp.
@@ -385,21 +400,10 @@ module.exports = function(RED) {
385
400
  throw new Error('Invalid raw image object supplied to encodeWebpAdvanced');
386
401
 
387
402
  const colorSpace = normalized.colorSpace;
388
- const channels = normalized.channels;
389
- let data = normalized.data;
390
-
391
- // BGR/BGRA → RGB/RGBA for Sharp
392
- if (colorSpace === 'BGR' || colorSpace === 'BGRA') {
393
- data = Buffer.from(data);
394
- for (let i = 0; i < data.length; i += channels) {
395
- const t = data[i];
396
- data[i] = data[i + 2];
397
- data[i + 2] = t;
398
- }
399
- }
403
+ const rgb = await utils.toSharpRaw(normalized);
400
404
 
401
- const sh = sharp(data, {
402
- raw: { width: normalized.width, height: normalized.height, channels }
405
+ const sh = sharp(rgb.data, {
406
+ raw: { width: rgb.width, height: rgb.height, channels: rgb.channels }
403
407
  });
404
408
 
405
409
  if (colorSpace === 'GRAY') sh.toColourspace('b-w');
@@ -417,21 +421,10 @@ module.exports = function(RED) {
417
421
  throw new Error('Invalid raw image object supplied to rawToJpeg');
418
422
 
419
423
  const colorSpace = normalized.colorSpace;
420
- const channels = normalized.channels;
421
- let data = normalized.data;
422
-
423
- // BGR/BGRA → RGB/RGBA for Sharp
424
- if (colorSpace === 'BGR' || colorSpace === 'BGRA') {
425
- data = Buffer.from(data); // copy so we don't mutate shared memory
426
- for (let i = 0; i < data.length; i += channels) {
427
- const t = data[i];
428
- data[i] = data[i + 2];
429
- data[i + 2] = t;
430
- }
431
- }
424
+ const rgb = await utils.toSharpRaw(normalized);
432
425
 
433
- const sh = sharp(data, {
434
- raw: { width: normalized.width, height: normalized.height, channels }
426
+ const sh = sharp(rgb.data, {
427
+ raw: { width: rgb.width, height: rgb.height, channels: rgb.channels }
435
428
  });
436
429
 
437
430
  if (colorSpace === 'GRAY') sh.toColourspace('b-w');
@@ -616,62 +609,69 @@ module.exports = function(RED) {
616
609
 
617
610
  try {
618
611
  let imageBuffer, formatMessage;
619
-
612
+ let actualWidth = debugWidth;
613
+ let actualHeight = debugWidth; // Default fallback
614
+ const resizeOpts = { withoutEnlargement: false, fit: 'inside' };
615
+
620
616
  if (outputFormat === 'raw') {
621
- // Convert raw image to JPG for display using existing utility
622
- imageBuffer = await utils.rawToJpeg(image, quality || CONSTANTS.DEFAULT_JPEG_QUALITY);
617
+ // Raw pixels: resize + JPEG-encode in ONE Sharp pass (previously the
618
+ // full-size image was JPEG-encoded, decoded again and resized).
619
+ const normalized = utils.validateImageStructure(image, { warn: () => {} });
620
+ if (!normalized || Buffer.isBuffer(normalized)) {
621
+ node.warn('Debug display: Invalid image buffer format');
622
+ return null;
623
+ }
623
624
  formatMessage = 'jpg default';
625
+ const rgb = await utils.toSharpRaw(normalized);
626
+ try {
627
+ const sh = sharp(rgb.data, {
628
+ raw: { width: rgb.width, height: rgb.height, channels: rgb.channels }
629
+ });
630
+ if (normalized.colorSpace === 'GRAY') sh.toColourspace('b-w');
631
+ const { data, info } = await sh
632
+ .resize(debugWidth, null, resizeOpts)
633
+ .jpeg({ quality: quality || 90 })
634
+ .toBuffer({ resolveWithObject: true });
635
+ imageBuffer = data;
636
+ actualWidth = info.width || debugWidth;
637
+ actualHeight = info.height || debugWidth;
638
+ } catch (resizeError) {
639
+ node.warn(`Debug image resize error: ${resizeError.message}`);
640
+ // Fall back to the full-size JPEG (still encoded off the event loop)
641
+ imageBuffer = await utils.rawToJpeg(normalized, quality || CONSTANTS.DEFAULT_JPEG_QUALITY);
642
+ actualWidth = normalized.width;
643
+ actualHeight = normalized.height;
644
+ }
624
645
  } else {
625
- // Reuse existing converted buffer
646
+ // Reuse existing encoded buffer ('jpg', 'png', 'webp')
626
647
  imageBuffer = Buffer.isBuffer(image) ? image : image.data;
627
- formatMessage = outputFormat; // 'jpg', 'png', 'webp'
628
- }
629
-
630
- if (!Buffer.isBuffer(imageBuffer)) {
631
- node.warn('Debug display: Invalid image buffer format');
632
- return null;
633
- }
634
-
635
- // Resize image for debug display using Sharp
636
- let actualWidth = debugWidth;
637
- let actualHeight = debugWidth; // Default fallback
638
- try {
639
- let sharpInstance = sharp(imageBuffer)
640
- .resize(debugWidth, null, {
641
- withoutEnlargement: false,
642
- fit: 'inside'
643
- });
644
-
645
- // Only convert format if output is raw, otherwise preserve the existing format
646
- if (outputFormat === 'raw') {
647
- // For raw format, convert to JPEG for display
648
- sharpInstance = sharpInstance.jpeg({ quality: quality || 90 });
649
- formatMessage = 'jpg default';
650
- } else {
651
- // For other formats (jpg, png, webp), just resize without format conversion
652
- // The C++ backend has already converted to the desired format
653
- formatMessage = outputFormat + ' resized';
648
+ formatMessage = outputFormat;
649
+ if (!Buffer.isBuffer(imageBuffer)) {
650
+ node.warn('Debug display: Invalid image buffer format');
651
+ return null;
654
652
  }
655
-
656
- imageBuffer = await sharpInstance.toBuffer();
657
-
658
- // Get actual dimensions of resized image
659
- const metadata = await sharp(imageBuffer).metadata();
660
- actualWidth = metadata.width || debugWidth;
661
- actualHeight = metadata.height || debugWidth;
662
-
663
- } catch (resizeError) {
664
- node.warn(`Debug image resize error: ${resizeError.message}`);
665
- // Continue with original image if resize fails
666
- // Try to get original dimensions as fallback
667
653
  try {
668
- const originalMetadata = await sharp(imageBuffer).metadata();
669
- actualWidth = originalMetadata.width || debugWidth;
670
- actualHeight = originalMetadata.height || debugWidth;
671
- } catch (metadataError) {
672
- // Use debug width as fallback
673
- actualWidth = debugWidth;
674
- actualHeight = debugWidth;
654
+ // Decode → resize → re-encode (same format) in one pass. JPEG input
655
+ // uses libjpeg shrink-on-load; the output dimensions come from the
656
+ // same pass instead of a second decode via metadata().
657
+ const { data, info } = await sharp(imageBuffer)
658
+ .resize(debugWidth, null, resizeOpts)
659
+ .toBuffer({ resolveWithObject: true });
660
+ imageBuffer = data;
661
+ actualWidth = info.width || debugWidth;
662
+ actualHeight = info.height || debugWidth;
663
+ formatMessage = outputFormat + ' resized';
664
+ } catch (resizeError) {
665
+ node.warn(`Debug image resize error: ${resizeError.message}`);
666
+ // Continue with original image if resize fails; read its header for the size
667
+ try {
668
+ const originalMetadata = await sharp(imageBuffer).metadata();
669
+ actualWidth = originalMetadata.width || debugWidth;
670
+ actualHeight = originalMetadata.height || debugWidth;
671
+ } catch (metadataError) {
672
+ actualWidth = debugWidth;
673
+ actualHeight = debugWidth;
674
+ }
675
675
  }
676
676
  }
677
677
 
@@ -326,6 +326,10 @@
326
326
  const nodeElement = document.getElementById(nodeId);
327
327
  if (!nodeElement) return;
328
328
 
329
+ // Size to the server-resized debug image (no display cap)
330
+ var debugWidth = data.debugWidth || 200;
331
+ var debugHeight = data.debugHeight || 200;
332
+
329
333
  let debugContainer = document.getElementById('debug-img-container-' + nodeId);
330
334
 
331
335
  if (!debugContainer) {
@@ -334,8 +338,8 @@
334
338
  debugContainer.id = 'debug-img-container-' + nodeId;
335
339
  debugContainer.setAttribute('x', '70');
336
340
  debugContainer.setAttribute('y', '5');
337
- debugContainer.setAttribute('width', '120');
338
- debugContainer.setAttribute('height', '120');
341
+ debugContainer.setAttribute('width', debugWidth.toString());
342
+ debugContainer.setAttribute('height', debugHeight.toString());
339
343
  debugContainer.style.overflow = 'visible';
340
344
 
341
345
  // Create simple image directly inside foreignObject
@@ -345,8 +349,8 @@
345
349
  img.style.height = 'auto';
346
350
  img.style.display = 'block';
347
351
  img.style.cursor = 'pointer';
348
- img.style.maxHeight = '100px';
349
- img.style.maxWidth = '100px';
352
+ img.style.maxHeight = 'none';
353
+ img.style.maxWidth = 'none';
350
354
 
351
355
  img.onclick = function() {
352
356
  removeDebugImage(nodeId);
@@ -354,6 +358,9 @@
354
358
 
355
359
  debugContainer.appendChild(img);
356
360
  nodeElement.appendChild(debugContainer);
361
+ } else {
362
+ debugContainer.setAttribute('width', debugWidth.toString());
363
+ debugContainer.setAttribute('height', debugHeight.toString());
357
364
  }
358
365
 
359
366
  const img = document.getElementById('debug-img-' + nodeId);
@@ -145,6 +145,10 @@
145
145
 
146
146
  const nodeElement = document.getElementById(nodeId);
147
147
  if (!nodeElement) return;
148
+
149
+ // Size to the server-resized debug image (no display cap)
150
+ var debugWidth = data.debugWidth || 200;
151
+ var debugHeight = data.debugHeight || 200;
148
152
 
149
153
  let debugContainer = document.getElementById('debug-img-container-' + nodeId);
150
154
 
@@ -154,8 +158,8 @@
154
158
  debugContainer.id = 'debug-img-container-' + nodeId;
155
159
  debugContainer.setAttribute('x', '70');
156
160
  debugContainer.setAttribute('y', '5');
157
- debugContainer.setAttribute('width', '120');
158
- debugContainer.setAttribute('height', '120');
161
+ debugContainer.setAttribute('width', debugWidth.toString());
162
+ debugContainer.setAttribute('height', debugHeight.toString());
159
163
  debugContainer.style.overflow = 'visible';
160
164
 
161
165
  // Create simple image directly inside foreignObject
@@ -165,8 +169,8 @@
165
169
  img.style.height = 'auto';
166
170
  img.style.display = 'block';
167
171
  img.style.cursor = 'pointer';
168
- img.style.maxHeight = '100px';
169
- img.style.maxWidth = '100px';
172
+ img.style.maxHeight = 'none';
173
+ img.style.maxWidth = 'none';
170
174
 
171
175
  img.onclick = function() {
172
176
  removeDebugImage(nodeId);
@@ -174,6 +178,9 @@
174
178
 
175
179
  debugContainer.appendChild(img);
176
180
  nodeElement.appendChild(debugContainer);
181
+ } else {
182
+ debugContainer.setAttribute('width', debugWidth.toString());
183
+ debugContainer.setAttribute('height', debugHeight.toString());
177
184
  }
178
185
 
179
186
  const img = document.getElementById('debug-img-' + nodeId);
@@ -475,6 +475,10 @@
475
475
  const nodeElement = document.getElementById(nodeId);
476
476
  if (!nodeElement) return;
477
477
 
478
+ // Size to the server-resized debug image (no display cap)
479
+ var debugWidth = data.debugWidth || 200;
480
+ var debugHeight = data.debugHeight || 200;
481
+
478
482
  let debugContainer = document.getElementById('debug-img-container-' + nodeId);
479
483
 
480
484
  if (!debugContainer) {
@@ -483,8 +487,8 @@
483
487
  debugContainer.id = 'debug-img-container-' + nodeId;
484
488
  debugContainer.setAttribute('x', '70');
485
489
  debugContainer.setAttribute('y', '5');
486
- debugContainer.setAttribute('width', '120');
487
- debugContainer.setAttribute('height', '120');
490
+ debugContainer.setAttribute('width', debugWidth.toString());
491
+ debugContainer.setAttribute('height', debugHeight.toString());
488
492
  debugContainer.style.overflow = 'visible';
489
493
 
490
494
  // Create simple image directly inside foreignObject
@@ -494,8 +498,8 @@
494
498
  img.style.height = 'auto';
495
499
  img.style.display = 'block';
496
500
  img.style.cursor = 'pointer';
497
- img.style.maxHeight = '100px';
498
- img.style.maxWidth = '100px';
501
+ img.style.maxHeight = 'none';
502
+ img.style.maxWidth = 'none';
499
503
 
500
504
  img.onclick = function() {
501
505
  removeDebugImage(nodeId);
@@ -503,6 +507,9 @@
503
507
 
504
508
  debugContainer.appendChild(img);
505
509
  nodeElement.appendChild(debugContainer);
510
+ } else {
511
+ debugContainer.setAttribute('width', debugWidth.toString());
512
+ debugContainer.setAttribute('height', debugHeight.toString());
506
513
  }
507
514
 
508
515
  const img = document.getElementById('debug-img-' + nodeId);
@@ -198,6 +198,10 @@
198
198
 
199
199
  const nodeElement = document.getElementById(nodeId);
200
200
  if (!nodeElement) return;
201
+
202
+ // Size to the server-resized debug image (no display cap)
203
+ var debugWidth = data.debugWidth || 200;
204
+ var debugHeight = data.debugHeight || 200;
201
205
 
202
206
  let debugContainer = document.getElementById('debug-img-container-' + nodeId);
203
207
 
@@ -207,8 +211,8 @@
207
211
  debugContainer.id = 'debug-img-container-' + nodeId;
208
212
  debugContainer.setAttribute('x', '70');
209
213
  debugContainer.setAttribute('y', '5');
210
- debugContainer.setAttribute('width', '120');
211
- debugContainer.setAttribute('height', '120');
214
+ debugContainer.setAttribute('width', debugWidth.toString());
215
+ debugContainer.setAttribute('height', debugHeight.toString());
212
216
  debugContainer.style.overflow = 'visible';
213
217
 
214
218
  // Create simple image directly inside foreignObject
@@ -218,8 +222,8 @@
218
222
  img.style.height = 'auto';
219
223
  img.style.display = 'block';
220
224
  img.style.cursor = 'pointer';
221
- img.style.maxHeight = '100px';
222
- img.style.maxWidth = '100px';
225
+ img.style.maxHeight = 'none';
226
+ img.style.maxWidth = 'none';
223
227
 
224
228
  img.onclick = function() {
225
229
  removeDebugImage(nodeId);
@@ -227,6 +231,9 @@
227
231
 
228
232
  debugContainer.appendChild(img);
229
233
  nodeElement.appendChild(debugContainer);
234
+ } else {
235
+ debugContainer.setAttribute('width', debugWidth.toString());
236
+ debugContainer.setAttribute('height', debugHeight.toString());
230
237
  }
231
238
 
232
239
  const img = document.getElementById('debug-img-' + nodeId);
@@ -25,11 +25,26 @@ module.exports = function(RED) {
25
25
 
26
26
  // Node state
27
27
  let running = false;
28
- let intervalTimer = null;
28
+ let starting = false;
29
+ let sleepTimer = null; // pending setTimeout of the emission loop
30
+ let sleepResolve = null; // resolver of the pending sleep (so stop() can wake the loop)
29
31
  let imageFiles = [];
30
32
  let currentIndex = 0;
31
33
  let folderPath = null;
32
34
 
35
+ /**
36
+ * Detects the container format from the file header so the debug preview
37
+ * can be produced straight from the encoded file (Sharp shrink-on-load)
38
+ * instead of re-encoding the decoded raw pixels.
39
+ */
40
+ function sniffEncodedFormat(buf) {
41
+ if (!Buffer.isBuffer(buf) || buf.length < 12) return null;
42
+ if (buf[0] === 0xFF && buf[1] === 0xD8 && buf[2] === 0xFF) return 'jpg';
43
+ if (buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4E && buf[3] === 0x47) return 'png';
44
+ if (buf.toString('ascii', 0, 4) === 'RIFF' && buf.toString('ascii', 8, 12) === 'WEBP') return 'webp';
45
+ return null;
46
+ }
47
+
33
48
  // Supported image extensions
34
49
  const IMAGE_EXTENSIONS = ['.jpg', '.jpeg', '.png', '.webp', '.bmp', '.gif', '.tiff'];
35
50
 
@@ -108,7 +123,7 @@ module.exports = function(RED) {
108
123
  const decodeStart = performance.now();
109
124
  let data, info;
110
125
  if (BmpDecode.isBmp(fileBuffer)) {
111
- const decoded = BmpDecode.decodeBmp(fileBuffer);
126
+ const decoded = await BmpDecode.decodeBmp(fileBuffer);
112
127
  data = decoded.data;
113
128
  info = { width: decoded.width, height: decoded.height, channels: decoded.channels };
114
129
  } else {
@@ -177,22 +192,14 @@ module.exports = function(RED) {
177
192
 
178
193
  const debugWidth = Math.max(1, parseInt(debugWidthRaw, 10) || 200);
179
194
 
180
- // Prefer sending the original encoded buffer when format is supported
195
+ // Prefer the original encoded file when its format is supported by
196
+ // the editor preview: Sharp then decodes at reduced size directly.
181
197
  let debugSource = outputImageObject;
182
198
  let debugFormatHint = 'raw';
183
-
184
- if (info && info.format) {
185
- const normalizedFormat = info.format.toLowerCase();
186
- if (normalizedFormat === 'jpeg' || normalizedFormat === 'jpg') {
187
- debugSource = fileBuffer;
188
- debugFormatHint = 'jpg';
189
- } else if (normalizedFormat === 'png') {
190
- debugSource = fileBuffer;
191
- debugFormatHint = 'png';
192
- } else if (normalizedFormat === 'webp') {
193
- debugSource = fileBuffer;
194
- debugFormatHint = 'webp';
195
- }
199
+ const encodedFormat = sniffEncodedFormat(fileBuffer);
200
+ if (encodedFormat) {
201
+ debugSource = fileBuffer;
202
+ debugFormatHint = encodedFormat;
196
203
  }
197
204
 
198
205
  const debugResult = await NodeUtils.debugImageDisplay(
@@ -227,6 +234,9 @@ module.exports = function(RED) {
227
234
  taskMs: taskMs
228
235
  }, totalTime);
229
236
 
237
+ // Stopped while this image was being decoded: discard it
238
+ if (!running) return;
239
+
230
240
  // Send message
231
241
  node.send(msg);
232
242
 
@@ -251,56 +261,98 @@ module.exports = function(RED) {
251
261
  }
252
262
  }
253
263
 
264
+ /** Async sleep that stopEmission() can interrupt. */
265
+ function sleep(ms) {
266
+ return new Promise((resolve) => {
267
+ sleepResolve = resolve;
268
+ sleepTimer = setTimeout(() => {
269
+ sleepTimer = null;
270
+ sleepResolve = null;
271
+ resolve();
272
+ }, ms);
273
+ });
274
+ }
275
+
276
+ function wakeLoop() {
277
+ if (sleepTimer) {
278
+ clearTimeout(sleepTimer);
279
+ sleepTimer = null;
280
+ }
281
+ if (sleepResolve) {
282
+ const resolve = sleepResolve;
283
+ sleepResolve = null;
284
+ resolve();
285
+ }
286
+ }
287
+
288
+ /**
289
+ * Emission loop. Unlike setInterval, the next emission is scheduled only
290
+ * after the previous one has finished, so a slow decode can never overlap
291
+ * with the next tick; the cadence is kept whenever decoding is faster than
292
+ * the interval.
293
+ */
294
+ async function runEmissionLoop(intervalMs) {
295
+ while (running) {
296
+ const started = performance.now();
297
+ await emitNextImage();
298
+ if (!running) break;
299
+ const delay = Math.max(0, intervalMs - (performance.now() - started));
300
+ await sleep(delay);
301
+ }
302
+ }
303
+
254
304
  /**
255
305
  * Starts the interval-based emission
256
306
  */
257
307
  async function startEmission() {
258
- if (running) return;
308
+ if (running || starting) return;
309
+ starting = true;
259
310
 
260
- node.status({ fill: "yellow", shape: "dot", text: "Scanning folder..." });
311
+ let intervalMs;
312
+ try {
313
+ node.status({ fill: "yellow", shape: "dot", text: "Scanning folder..." });
261
314
 
262
- // Scan folder for images
263
- imageFiles = await scanFolder();
315
+ // Scan folder for images
316
+ imageFiles = await scanFolder();
264
317
 
265
- if (imageFiles.length === 0) {
266
- node.status({ fill: "red", shape: "ring", text: "No images found" });
267
- return;
268
- }
318
+ if (imageFiles.length === 0) {
319
+ node.status({ fill: "red", shape: "ring", text: "No images found" });
320
+ return;
321
+ }
269
322
 
270
- // Reset index
271
- currentIndex = 0;
272
- running = true;
323
+ // Reset index
324
+ currentIndex = 0;
325
+ running = true;
273
326
 
274
- // Get interval value
275
- let intervalMs = config.interval || 1000;
276
- if (config.intervalType === 'msg' || config.intervalType === 'flow' || config.intervalType === 'global') {
277
- // For dynamic intervals, use default for now - can be enhanced with message input
327
+ // Get interval value
278
328
  intervalMs = config.interval || 1000;
279
- }
280
- intervalMs = parseInt(intervalMs);
281
-
282
- node.status({ fill: "green", shape: "dot", text: `Started (${imageFiles.length} images, ${intervalMs}ms)` });
283
-
284
- // Emit first image immediately
285
- await emitNextImage();
329
+ if (config.intervalType === 'msg' || config.intervalType === 'flow' || config.intervalType === 'global') {
330
+ // For dynamic intervals, use default for now - can be enhanced with message input
331
+ intervalMs = config.interval || 1000;
332
+ }
333
+ intervalMs = parseInt(intervalMs);
334
+ if (!Number.isFinite(intervalMs) || intervalMs < 0) intervalMs = 1000;
286
335
 
287
- // Start interval timer for subsequent images
288
- if (running) { // Check if still running after first emit
289
- intervalTimer = setInterval(emitNextImage, intervalMs);
336
+ node.status({ fill: "green", shape: "dot", text: `Started (${imageFiles.length} images, ${intervalMs}ms)` });
337
+ } finally {
338
+ starting = false;
290
339
  }
340
+
341
+ // Emits the first image immediately, then one every intervalMs
342
+ runEmissionLoop(intervalMs).catch((err) => {
343
+ node.error(`Emission loop failed: ${err.message}`);
344
+ stopEmission();
345
+ });
291
346
  }
292
347
 
293
348
  /**
294
- * Stops the interval-based emission
349
+ * Stops the emission loop
295
350
  */
296
351
  function stopEmission() {
297
352
  if (!running) return;
298
353
 
299
354
  running = false;
300
- if (intervalTimer) {
301
- clearInterval(intervalTimer);
302
- intervalTimer = null;
303
- }
355
+ wakeLoop();
304
356
 
305
357
  node.status({ fill: "grey", shape: "ring", text: "Stopped" });
306
358
  }
@@ -51,7 +51,7 @@ module.exports = function(RED) {
51
51
  const fileBuffer = await fs.readFile(filePath);
52
52
  let data, info;
53
53
  if (BmpDecode.isBmp(fileBuffer)) {
54
- const decoded = BmpDecode.decodeBmp(fileBuffer);
54
+ const decoded = await BmpDecode.decodeBmp(fileBuffer);
55
55
  data = decoded.data;
56
56
  info = { width: decoded.width, height: decoded.height, channels: decoded.channels };
57
57
  } else {
@@ -91,7 +91,7 @@ module.exports = function(RED) {
91
91
 
92
92
  // Since we already have the image loaded, reuse it for debug display
93
93
  // Convert to JPEG buffer for debug display using the Sharp instance
94
- const debugBuffer = await sharp(data, {
94
+ const { data: debugBuffer, info: debugMetadata } = await sharp(data, {
95
95
  raw: { width: info.width, height: info.height, channels: info.channels }
96
96
  })
97
97
  .resize(debugWidth, null, {
@@ -99,11 +99,10 @@ module.exports = function(RED) {
99
99
  fit: 'inside'
100
100
  })
101
101
  .jpeg({ quality: 90 })
102
- .toBuffer();
102
+ .toBuffer({ resolveWithObject: true }); // dimensions come from the same pass
103
103
 
104
104
  // Create debug result manually since we're using Sharp directly
105
105
  const base64 = debugBuffer.toString('base64');
106
- const debugMetadata = await sharp(debugBuffer).metadata();
107
106
 
108
107
  // Send image to frontend via WebSocket for inline display
109
108
  try {
@@ -288,6 +288,10 @@
288
288
  var nodeElement = document.getElementById(nodeId);
289
289
  if (!nodeElement) return;
290
290
 
291
+ // Size to the server-resized debug image (no display cap)
292
+ var debugWidth = data.debugWidth || 200;
293
+ var debugHeight = data.debugHeight || 200;
294
+
291
295
  var debugContainer = document.getElementById('debug-img-container-' + nodeId);
292
296
 
293
297
  if (!debugContainer) {
@@ -295,8 +299,8 @@
295
299
  debugContainer.id = 'debug-img-container-' + nodeId;
296
300
  debugContainer.setAttribute('x', '70');
297
301
  debugContainer.setAttribute('y', '5');
298
- debugContainer.setAttribute('width', '120');
299
- debugContainer.setAttribute('height', '120');
302
+ debugContainer.setAttribute('width', debugWidth.toString());
303
+ debugContainer.setAttribute('height', debugHeight.toString());
300
304
  debugContainer.style.overflow = 'visible';
301
305
 
302
306
  var img = document.createElement('img');
@@ -305,8 +309,8 @@
305
309
  img.style.height = 'auto';
306
310
  img.style.display = 'block';
307
311
  img.style.cursor = 'pointer';
308
- img.style.maxHeight = '100px';
309
- img.style.maxWidth = '100px';
312
+ img.style.maxHeight = 'none';
313
+ img.style.maxWidth = 'none';
310
314
 
311
315
  img.onclick = function() {
312
316
  removeDebugImage(nodeId);
@@ -314,6 +318,9 @@
314
318
 
315
319
  debugContainer.appendChild(img);
316
320
  nodeElement.appendChild(debugContainer);
321
+ } else {
322
+ debugContainer.setAttribute('width', debugWidth.toString());
323
+ debugContainer.setAttribute('height', debugHeight.toString());
317
324
  }
318
325
 
319
326
  var imgEl = document.getElementById('debug-img-' + nodeId);