@rosepetal/node-red-contrib-image-tools 1.6.4 → 1.8.1

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 (70) hide show
  1. package/.claude/rules/node-implementation-template.md +1 -1
  2. package/.github/workflows/build-prebuild.yml +1 -1
  3. package/README.md +41 -21
  4. package/docs/index.md +156 -0
  5. package/docs/nodes/blend/add-bbs.md +116 -0
  6. package/docs/nodes/blend/add-mask.md +67 -224
  7. package/docs/nodes/blend/add-masks.md +74 -196
  8. package/docs/nodes/blend/blend.md +84 -200
  9. package/docs/nodes/io/folder-in.md +92 -0
  10. package/docs/nodes/io/image-in.md +61 -52
  11. package/docs/nodes/io/image-out.md +114 -93
  12. package/docs/nodes/mix/advanced-mosaic.md +124 -78
  13. package/docs/nodes/mix/concat.md +71 -56
  14. package/docs/nodes/mix/mosaic.md +81 -91
  15. package/docs/nodes/specialized/cropBB.md +76 -214
  16. package/docs/nodes/specialized/heat-diff.md +111 -0
  17. package/docs/nodes/specialized/image-align.md +125 -387
  18. package/docs/nodes/transform/color-convert.md +101 -0
  19. package/docs/nodes/transform/crop.md +56 -58
  20. package/docs/nodes/transform/draw.md +46 -26
  21. package/docs/nodes/transform/filter.md +110 -46
  22. package/docs/nodes/transform/padding.md +55 -55
  23. package/docs/nodes/transform/resize.md +81 -56
  24. package/docs/nodes/transform/rotate.md +67 -50
  25. package/node-red-contrib-image-tools/lib/bmp-decode.js +18 -68
  26. package/node-red-contrib-image-tools/lib/cpp-bridge.js +202 -104
  27. package/node-red-contrib-image-tools/lib/node-utils.js +78 -78
  28. package/node-red-contrib-image-tools/nodes/io/folder-in.js +98 -46
  29. package/node-red-contrib-image-tools/nodes/io/image-in.js +3 -4
  30. package/node-red-contrib-image-tools/nodes/io/image-out.js +93 -146
  31. package/node-red-contrib-image-tools/nodes/specialized/cropBB.js +3 -3
  32. package/node-red-contrib-image-tools/nodes/specialized/heat-diff.js +3 -3
  33. package/node-red-contrib-image-tools/nodes/specialized/image-align.html +11 -4
  34. package/node-red-contrib-image-tools/nodes/specialized/image-align.js +5 -4
  35. package/node-red-contrib-image-tools/nodes/transform/color-convert.js +3 -3
  36. package/node-red-contrib-image-tools/nodes/transform/crop.js +3 -3
  37. package/node-red-contrib-image-tools/nodes/transform/filter.js +3 -3
  38. package/node-red-contrib-image-tools/nodes/transform/padding.js +3 -3
  39. package/node-red-contrib-image-tools/nodes/transform/resize.js +3 -3
  40. package/node-red-contrib-image-tools/nodes/transform/rotate.js +3 -3
  41. package/npm/darwin-arm64/package.json +1 -1
  42. package/npm/darwin-x64/package.json +1 -1
  43. package/npm/linux-arm64/package.json +1 -1
  44. package/npm/linux-x64/package.json +1 -1
  45. package/npm/linuxmusl-x64/package.json +1 -1
  46. package/npm/win32-x64/package.json +1 -1
  47. package/package.json +6 -6
  48. package/rosepetal-image-engine/binding.gyp +2 -1
  49. package/rosepetal-image-engine/src/add-bbs.cpp +123 -123
  50. package/rosepetal-image-engine/src/add-mask.cpp +30 -15
  51. package/rosepetal-image-engine/src/add-masks.cpp +145 -102
  52. package/rosepetal-image-engine/src/advanced-mosaic.cpp +200 -129
  53. package/rosepetal-image-engine/src/blend.cpp +34 -20
  54. package/rosepetal-image-engine/src/codec.cpp +157 -0
  55. package/rosepetal-image-engine/src/color-convert.cpp +22 -19
  56. package/rosepetal-image-engine/src/concat.cpp +38 -43
  57. package/rosepetal-image-engine/src/crop.cpp +23 -26
  58. package/rosepetal-image-engine/src/draw.cpp +33 -10
  59. package/rosepetal-image-engine/src/filter.cpp +22 -26
  60. package/rosepetal-image-engine/src/heat-diff.cpp +35 -8
  61. package/rosepetal-image-engine/src/image-align.cpp +107 -35
  62. package/rosepetal-image-engine/src/main.cpp +4 -0
  63. package/rosepetal-image-engine/src/mosaic.cpp +31 -40
  64. package/rosepetal-image-engine/src/padding.cpp +30 -29
  65. package/rosepetal-image-engine/src/resize.cpp +20 -25
  66. package/rosepetal-image-engine/src/rotate.cpp +22 -23
  67. package/rosepetal-image-engine/src/utils.h +243 -144
  68. package/scripts/build-opencv-static.sh +6 -0
  69. package/scripts/dual-register.js +32 -25
  70. 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
 
@@ -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 {