@rosepetal/node-red-contrib-image-tools 1.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) hide show
  1. package/.gitattributes +6 -0
  2. package/.github/workflows/build-prebuild.yml +326 -0
  3. package/LICENSE +13 -0
  4. package/README.md +161 -0
  5. package/artifacts/darwin-arm64/package.json +25 -0
  6. package/artifacts/linux-arm64/package.json +26 -0
  7. package/artifacts/linux-x64/package.json +26 -0
  8. package/artifacts/linuxmusl-x64/package.json +26 -0
  9. package/assets/flow_time_example.gif +0 -0
  10. package/assets/nodes/io/array-in-demo.gif +0 -0
  11. package/assets/nodes/io/array-out-demo.gif +0 -0
  12. package/assets/nodes/io/array-select-demo.gif +0 -0
  13. package/assets/nodes/io/image-in-demo.gif +0 -0
  14. package/assets/nodes/mix/concat-demo.gif +0 -0
  15. package/assets/nodes/mix/mosaic-demo.gif +0 -0
  16. package/assets/nodes/transform/crop-demo.gif +0 -0
  17. package/assets/nodes/transform/filter-demo.gif +0 -0
  18. package/assets/nodes/transform/padding-demo.gif +0 -0
  19. package/assets/nodes/transform/resize-demo.gif +0 -0
  20. package/assets/nodes/transform/rotate-demo.gif +0 -0
  21. package/docs/nodes/blend/add-mask.md +275 -0
  22. package/docs/nodes/blend/add-masks.md +284 -0
  23. package/docs/nodes/blend/blend.md +248 -0
  24. package/docs/nodes/io/array-in.md +119 -0
  25. package/docs/nodes/io/array-out.md +150 -0
  26. package/docs/nodes/io/array-select.md +157 -0
  27. package/docs/nodes/io/image-in.md +131 -0
  28. package/docs/nodes/io/image-out.md +179 -0
  29. package/docs/nodes/io/queue.md +57 -0
  30. package/docs/nodes/io/save-file.md +30 -0
  31. package/docs/nodes/mix/advanced-mosaic.md +108 -0
  32. package/docs/nodes/mix/concat.md +127 -0
  33. package/docs/nodes/mix/mosaic.md +146 -0
  34. package/docs/nodes/specialized/cropBB.md +271 -0
  35. package/docs/nodes/specialized/image-align.md +426 -0
  36. package/docs/nodes/transform/crop.md +132 -0
  37. package/docs/nodes/transform/draw.md +77 -0
  38. package/docs/nodes/transform/filter.md +84 -0
  39. package/docs/nodes/transform/padding.md +133 -0
  40. package/docs/nodes/transform/resize.md +158 -0
  41. package/docs/nodes/transform/rotate.md +121 -0
  42. package/docs/nodes/util/block-detect.md +46 -0
  43. package/install.sh +144 -0
  44. package/node-red-contrib-image-tools/lib/cpp-bridge.js +224 -0
  45. package/node-red-contrib-image-tools/lib/node-utils.js +529 -0
  46. package/node-red-contrib-image-tools/nodes/blend/add-bbs.html +590 -0
  47. package/node-red-contrib-image-tools/nodes/blend/add-bbs.js +241 -0
  48. package/node-red-contrib-image-tools/nodes/blend/add-mask.html +449 -0
  49. package/node-red-contrib-image-tools/nodes/blend/add-mask.js +170 -0
  50. package/node-red-contrib-image-tools/nodes/blend/add-masks.html +703 -0
  51. package/node-red-contrib-image-tools/nodes/blend/add-masks.js +321 -0
  52. package/node-red-contrib-image-tools/nodes/blend/blend.html +552 -0
  53. package/node-red-contrib-image-tools/nodes/blend/blend.js +124 -0
  54. package/node-red-contrib-image-tools/nodes/io/array-in.html +110 -0
  55. package/node-red-contrib-image-tools/nodes/io/array-in.js +113 -0
  56. package/node-red-contrib-image-tools/nodes/io/array-out.html +125 -0
  57. package/node-red-contrib-image-tools/nodes/io/array-out.js +213 -0
  58. package/node-red-contrib-image-tools/nodes/io/array-select.html +156 -0
  59. package/node-red-contrib-image-tools/nodes/io/array-select.js +187 -0
  60. package/node-red-contrib-image-tools/nodes/io/folder-in.html +248 -0
  61. package/node-red-contrib-image-tools/nodes/io/folder-in.js +335 -0
  62. package/node-red-contrib-image-tools/nodes/io/image-in.html +146 -0
  63. package/node-red-contrib-image-tools/nodes/io/image-in.js +143 -0
  64. package/node-red-contrib-image-tools/nodes/io/image-out.html +506 -0
  65. package/node-red-contrib-image-tools/nodes/io/image-out.js +545 -0
  66. package/node-red-contrib-image-tools/nodes/io/queue.html +119 -0
  67. package/node-red-contrib-image-tools/nodes/io/queue.js +191 -0
  68. package/node-red-contrib-image-tools/nodes/io/save-file.html +243 -0
  69. package/node-red-contrib-image-tools/nodes/io/save-file.js +440 -0
  70. package/node-red-contrib-image-tools/nodes/mix/advanced-mosaic.html +2149 -0
  71. package/node-red-contrib-image-tools/nodes/mix/advanced-mosaic.js +195 -0
  72. package/node-red-contrib-image-tools/nodes/mix/concat.html +390 -0
  73. package/node-red-contrib-image-tools/nodes/mix/concat.js +112 -0
  74. package/node-red-contrib-image-tools/nodes/mix/mosaic.html +550 -0
  75. package/node-red-contrib-image-tools/nodes/mix/mosaic.js +151 -0
  76. package/node-red-contrib-image-tools/nodes/specialized/cropBB.html +268 -0
  77. package/node-red-contrib-image-tools/nodes/specialized/cropBB.js +277 -0
  78. package/node-red-contrib-image-tools/nodes/specialized/image-align.html +528 -0
  79. package/node-red-contrib-image-tools/nodes/specialized/image-align.js +306 -0
  80. package/node-red-contrib-image-tools/nodes/transform/crop.html +410 -0
  81. package/node-red-contrib-image-tools/nodes/transform/crop.js +149 -0
  82. package/node-red-contrib-image-tools/nodes/transform/draw.html +719 -0
  83. package/node-red-contrib-image-tools/nodes/transform/draw.js +509 -0
  84. package/node-red-contrib-image-tools/nodes/transform/filter.html +578 -0
  85. package/node-red-contrib-image-tools/nodes/transform/filter.js +177 -0
  86. package/node-red-contrib-image-tools/nodes/transform/padding.html +475 -0
  87. package/node-red-contrib-image-tools/nodes/transform/padding.js +142 -0
  88. package/node-red-contrib-image-tools/nodes/transform/resize.html +429 -0
  89. package/node-red-contrib-image-tools/nodes/transform/resize.js +162 -0
  90. package/node-red-contrib-image-tools/nodes/transform/rotate.html +299 -0
  91. package/node-red-contrib-image-tools/nodes/transform/rotate.js +141 -0
  92. package/node-red-contrib-image-tools/nodes/util/block-detect.html +85 -0
  93. package/node-red-contrib-image-tools/nodes/util/block-detect.js +136 -0
  94. package/node-red-contrib-image-tools/nodes/util/clean-debug.html +201 -0
  95. package/node-red-contrib-image-tools/nodes/util/clean-debug.js +393 -0
  96. package/node-red-contrib-image-tools/package.json +64 -0
  97. package/npm/darwin-arm64/lib/.gitkeep +1 -0
  98. package/npm/darwin-arm64/package.json +25 -0
  99. package/npm/darwin-x64/lib/.gitkeep +1 -0
  100. package/npm/darwin-x64/package.json +25 -0
  101. package/npm/linux-arm64/lib/.gitkeep +1 -0
  102. package/npm/linux-arm64/package.json +26 -0
  103. package/npm/linux-x64/lib/.gitkeep +1 -0
  104. package/npm/linux-x64/package.json +26 -0
  105. package/npm/linuxmusl-x64/lib/.gitkeep +1 -0
  106. package/npm/linuxmusl-x64/package.json +26 -0
  107. package/npm/win32-x64/lib/.gitkeep +1 -0
  108. package/npm/win32-x64/package.json +25 -0
  109. package/package.json +74 -0
  110. package/rosepetal-image-engine/binding.gyp +153 -0
  111. package/rosepetal-image-engine/package.json +19 -0
  112. package/rosepetal-image-engine/src/add-bbs.cpp +433 -0
  113. package/rosepetal-image-engine/src/add-mask.cpp +240 -0
  114. package/rosepetal-image-engine/src/add-masks.cpp +638 -0
  115. package/rosepetal-image-engine/src/advanced-mosaic.cpp +740 -0
  116. package/rosepetal-image-engine/src/blend.cpp +200 -0
  117. package/rosepetal-image-engine/src/concat.cpp +329 -0
  118. package/rosepetal-image-engine/src/crop.cpp +139 -0
  119. package/rosepetal-image-engine/src/draw.cpp +414 -0
  120. package/rosepetal-image-engine/src/filter.cpp +230 -0
  121. package/rosepetal-image-engine/src/filters/kernels.h +171 -0
  122. package/rosepetal-image-engine/src/image-align.cpp +551 -0
  123. package/rosepetal-image-engine/src/main.cpp +36 -0
  124. package/rosepetal-image-engine/src/mosaic.cpp +373 -0
  125. package/rosepetal-image-engine/src/padding.cpp +124 -0
  126. package/rosepetal-image-engine/src/resize.cpp +210 -0
  127. package/rosepetal-image-engine/src/rotate.cpp +177 -0
  128. package/rosepetal-image-engine/src/utils.h +563 -0
  129. package/rosepetal-image-engine/test-formats.js +119 -0
  130. package/scripts/build-opencv-static.ps1 +166 -0
  131. package/scripts/build-opencv-static.sh +147 -0
@@ -0,0 +1,529 @@
1
+ /**
2
+ * @file Contains generic helper functions for the Node-RED nodes.
3
+ * This module is pure JavaScript and has no dependency on the RED object.
4
+ * @author Rosepetal
5
+ */
6
+
7
+ const sharp = require('sharp'); // Ensure sharp is installed in your project
8
+
9
+
10
+ module.exports = function(RED) {
11
+ const utils = {};
12
+
13
+ // Configuration constants
14
+ const CONSTANTS = {
15
+ DEFAULT_JPEG_QUALITY: 90,
16
+ DEFAULT_ARRAY_POSITION: 0,
17
+ SUPPORTED_DTYPES: ['uint8'],
18
+ SUPPORTED_COLOR_SPACES: ['GRAY', 'RGB', 'RGBA', 'BGR', 'BGRA'],
19
+ CHANNEL_MAP: { 'GRAY': 1, 'RGB': 3, 'RGBA': 4, 'BGR': 3, 'BGRA': 4 }
20
+ };
21
+
22
+ /**
23
+ * Validates and normalizes an image structure
24
+ * Supports structure: {data, width, height, channels, colorSpace, dtype}
25
+ */
26
+ utils.validateImageStructure = function(image, node) {
27
+ if (!image) {
28
+ node.warn("Input is null or undefined");
29
+ return null;
30
+ }
31
+
32
+ switch (true) {
33
+ // New Rosepetal bitmap structure
34
+ case (image.hasOwnProperty('width') &&
35
+ image.hasOwnProperty('height') &&
36
+ image.hasOwnProperty('data')):
37
+
38
+ // Validate dtype (only uint8 supported for now)
39
+ if (image.dtype && !CONSTANTS.SUPPORTED_DTYPES.includes(image.dtype)) {
40
+ node.warn(`Unsupported dtype: ${image.dtype}. Supported values: ${CONSTANTS.SUPPORTED_DTYPES.join(', ')}`);
41
+ return null;
42
+ }
43
+
44
+ // Infer channels if not provided
45
+ let channels = image.channels;
46
+ if (!channels) {
47
+ const calculatedChannels = image.data.length / (image.width * image.height);
48
+ if (!Number.isInteger(calculatedChannels)) {
49
+ node.warn(`Cannot infer channels: data.length (${image.data.length}) is not divisible by width*height (${image.width * image.height})`);
50
+ return null;
51
+ }
52
+ channels = calculatedChannels;
53
+ }
54
+
55
+ // Validate channels is a number
56
+ if (typeof channels !== 'number') {
57
+ node.warn(`Channels must be a number, got: ${typeof channels}`);
58
+ return null;
59
+ }
60
+
61
+ // Validate data length matches dimensions
62
+ if (image.width * image.height * channels !== image.data.length) {
63
+ node.warn(`Data length mismatch: expected ${image.width * image.height * channels} bytes (${image.width}x${image.height}x${channels}), got ${image.data.length} bytes`);
64
+ return null;
65
+ }
66
+
67
+ // Handle colorSpace with defaults
68
+ let colorSpace = image.colorSpace;
69
+ if (!colorSpace) {
70
+ // Default based on channel count
71
+ switch (channels) {
72
+ case 1: colorSpace = "GRAY"; break;
73
+ case 3: colorSpace = "RGB"; break;
74
+ case 4: colorSpace = "RGBA"; break;
75
+ default:
76
+ node.warn(`Cannot determine default colorSpace for ${channels} channels`);
77
+ return null;
78
+ }
79
+ }
80
+
81
+ // Validate colorSpace matches channel count
82
+ if (!CONSTANTS.CHANNEL_MAP.hasOwnProperty(colorSpace)) {
83
+ node.warn(`Unsupported colorSpace: ${colorSpace}. Supported values: ${CONSTANTS.SUPPORTED_COLOR_SPACES.join(', ')}`);
84
+ return null;
85
+ }
86
+
87
+ if (CONSTANTS.CHANNEL_MAP[colorSpace] !== channels) {
88
+ node.warn(`ColorSpace mismatch: ${colorSpace} expects ${CONSTANTS.CHANNEL_MAP[colorSpace]} channels, got ${channels} channels`);
89
+ return null;
90
+ }
91
+
92
+ // Return normalized structure
93
+ return {
94
+ data: image.data,
95
+ width: image.width,
96
+ height: image.height,
97
+ channels: channels,
98
+ colorSpace: colorSpace,
99
+ dtype: image.dtype || 'uint8'
100
+ };
101
+
102
+ default:
103
+ // Not our format? Pass to C++ and let OpenCV handle it
104
+ return image;
105
+ }
106
+ }
107
+
108
+ utils.validateSingleImage = function(image, node) {
109
+ const normalized = utils.validateImageStructure(image, node);
110
+ return normalized !== null;
111
+ }
112
+
113
+ utils.validateListImage = function(list, node) {
114
+ if (!list || !Array.isArray(list) || list.length === 0) {
115
+ node.warn("Input is not a valid image list. Expected a non-empty Array.");
116
+ return false;
117
+ }
118
+ // Validate each item in the list
119
+ for (const image of list) {
120
+ if (!utils.validateSingleImage(image, node)) {
121
+ // The warning message is already sent by validateSingleImage
122
+ return false;
123
+ }
124
+ }
125
+ return true;
126
+ }
127
+
128
+ utils.resolveDimension = function(node, type, value, msg) {
129
+ if (!value || String(value).trim() === '') return null;
130
+ let resolvedValue;
131
+ if (type === 'msg' || type === 'flow' || type === 'global') {
132
+ resolvedValue = RED.util.evaluateNodeProperty(value, type, node, msg);
133
+ } else {
134
+ resolvedValue = value;
135
+ }
136
+ const numericValue = parseFloat(resolvedValue);
137
+ if (numericValue === undefined || isNaN(numericValue)) {
138
+ throw new Error(`Value "${resolvedValue}" from property "${value}" is not a valid number.`);
139
+ }
140
+ return numericValue;
141
+ }
142
+
143
+ /**
144
+ * Resolves array position value from various sources (msg, flow, global, or direct value)
145
+ * @param {Object} node - The Node-RED node instance
146
+ * @param {string} type - The type of source ('msg', 'flow', 'global', or 'num')
147
+ * @param {*} value - The value or property path to resolve
148
+ * @param {Object} msg - The message object for msg property resolution
149
+ * @returns {number} The resolved array position as a non-negative integer
150
+ * @throws {Error} If the resolved value is not a valid non-negative integer
151
+ */
152
+ utils.resolveArrayPosition = function(node, type, value, msg) {
153
+ if (value === null || value === undefined || String(value).trim() === '') {
154
+ return CONSTANTS.DEFAULT_ARRAY_POSITION;
155
+ }
156
+
157
+ let resolvedValue;
158
+ if (type === 'msg' || type === 'flow' || type === 'global') {
159
+ resolvedValue = RED.util.evaluateNodeProperty(value, type, node, msg);
160
+ } else {
161
+ resolvedValue = value;
162
+ }
163
+
164
+ const numericValue = parseInt(resolvedValue);
165
+ if (numericValue === undefined || isNaN(numericValue) || numericValue < 0) {
166
+ throw new Error(`Array position "${resolvedValue}" from property "${value}" must be a non-negative integer.`);
167
+ }
168
+
169
+ return numericValue;
170
+ }
171
+
172
+ utils.rawToJpeg = async function (image, quality = CONSTANTS.DEFAULT_JPEG_QUALITY) {
173
+ const normalized = utils.validateImageStructure(image, { warn: () => {} });
174
+ if (!normalized)
175
+ throw new Error('Invalid raw image object supplied to rawToJpeg');
176
+
177
+ const colorSpace = normalized.colorSpace;
178
+ const channels = normalized.channels;
179
+ let data = normalized.data;
180
+
181
+ // BGR/BGRA → RGB/RGBA for Sharp
182
+ if (colorSpace === 'BGR' || colorSpace === 'BGRA') {
183
+ data = Buffer.from(data); // copy so we don't mutate shared memory
184
+ for (let i = 0; i < data.length; i += channels) {
185
+ const t = data[i];
186
+ data[i] = data[i + 2];
187
+ data[i + 2] = t;
188
+ }
189
+ }
190
+
191
+ const sh = sharp(data, {
192
+ raw: { width: normalized.width, height: normalized.height, channels }
193
+ });
194
+
195
+ if (colorSpace === 'GRAY') sh.toColourspace('b-w');
196
+
197
+ return sh.jpeg({ quality }).toBuffer();
198
+ }
199
+
200
+ /**
201
+ * Standardized error handling for all nodes
202
+ * @param {object} node - Node-RED node instance
203
+ * @param {Error} error - The error that occurred
204
+ * @param {object} msg - The message object
205
+ * @param {function} done - The done callback
206
+ * @param {string} operation - Optional operation name for context
207
+ */
208
+ utils.handleNodeError = function(node, error, msg, done, operation = 'processing') {
209
+ const errorMessage = error.message || `Unknown error during ${operation}.`;
210
+ node.error(errorMessage, msg);
211
+ node.status({ fill: "red", shape: "ring", text: "Error" });
212
+ if (done) {
213
+ done(error);
214
+ }
215
+ }
216
+
217
+ /**
218
+ * Error handling with passthrough - always sends output even on error.
219
+ * Use this to ensure flow continues even when processing fails.
220
+ * @param {object} node - Node-RED node instance
221
+ * @param {Error|string} error - The error that occurred
222
+ * @param {object} msg - The message object
223
+ * @param {function} send - The send callback
224
+ * @param {function} done - The done callback
225
+ * @param {string} operation - Operation name for context
226
+ * @param {object} passthroughOptions - Options for passthrough behavior
227
+ * @param {*} passthroughOptions.originalPayload - The original input payload to pass through
228
+ * @param {string} passthroughOptions.outputPath - Where to write output (default: 'payload')
229
+ * @param {string} passthroughOptions.outputType - 'preserve' | 'array' | 'single' | 'empty-array'
230
+ */
231
+ utils.handleNodeErrorWithPassthrough = function(node, error, msg, send, done, operation, passthroughOptions = {}) {
232
+ const {
233
+ originalPayload,
234
+ outputPath = 'payload',
235
+ outputType = 'preserve'
236
+ } = passthroughOptions;
237
+
238
+ const errorMessage = error instanceof Error ? error.message : String(error);
239
+ const errorStack = error instanceof Error ? error.stack : undefined;
240
+
241
+ // Build error object
242
+ msg.error = {
243
+ message: errorMessage,
244
+ operation: operation,
245
+ timestamp: new Date().toISOString(),
246
+ nodeId: node.id,
247
+ nodeName: node.name || node.type
248
+ };
249
+
250
+ if (errorStack) {
251
+ msg.error.stack = errorStack;
252
+ }
253
+
254
+ // Determine output based on outputType
255
+ let output;
256
+ switch (outputType) {
257
+ case 'preserve':
258
+ output = originalPayload;
259
+ break;
260
+ case 'array':
261
+ output = Array.isArray(originalPayload) ? originalPayload : [originalPayload];
262
+ break;
263
+ case 'single':
264
+ output = Array.isArray(originalPayload) ? originalPayload[0] : originalPayload;
265
+ break;
266
+ case 'empty-array':
267
+ output = [];
268
+ break;
269
+ default:
270
+ output = originalPayload;
271
+ }
272
+
273
+ // Set output
274
+ RED.util.setMessageProperty(msg, outputPath, output);
275
+
276
+ // Log error and set status
277
+ node.warn(errorMessage);
278
+ node.status({ fill: "red", shape: "ring", text: `Error: ${errorMessage.substring(0, 30)}` });
279
+
280
+ // Send message with error info
281
+ send(msg);
282
+
283
+ // Call done without error to prevent flow interruption
284
+ if (done) {
285
+ done();
286
+ }
287
+ }
288
+
289
+ /**
290
+ * Validation error handling with passthrough - for validation failures before try-catch.
291
+ * @param {object} node - Node-RED node instance
292
+ * @param {string} errorMessage - The validation error message
293
+ * @param {object} msg - The message object
294
+ * @param {function} send - The send callback
295
+ * @param {function} done - The done callback
296
+ * @param {object} passthroughOptions - Same options as handleNodeErrorWithPassthrough
297
+ */
298
+ utils.handleValidationErrorWithPassthrough = function(node, errorMessage, msg, send, done, passthroughOptions = {}) {
299
+ const error = new Error(errorMessage);
300
+ error.validationError = true;
301
+
302
+ // Add validationError flag to the options
303
+ const options = { ...passthroughOptions };
304
+
305
+ utils.handleNodeErrorWithPassthrough(
306
+ node, error, msg, send, done,
307
+ 'validation',
308
+ options
309
+ );
310
+
311
+ // Mark the error object with validation flag after it's created
312
+ if (msg.error) {
313
+ msg.error.validationError = true;
314
+ }
315
+ }
316
+
317
+ /**
318
+ * Standardized success status formatting
319
+ * @param {object} node - Node-RED node instance
320
+ * @param {number} count - Number of items processed
321
+ * @param {number} totalTime - Total processing time in ms
322
+ * @param {object} timing - Timing breakdown object
323
+ */
324
+ utils.setSuccessStatus = function(node, count, totalTime, timing = {}) {
325
+ const { convertMs = 0, taskMs = 0, encodeMs = 0 } = timing;
326
+ node.status({
327
+ fill: 'green',
328
+ shape: 'dot',
329
+ text: `OK: ${count} img in ${totalTime.toFixed(2)} ms ` +
330
+ `(conv ${(convertMs + encodeMs).toFixed(2)} ms | ` +
331
+ `task ${taskMs.toFixed(2)} ms)`
332
+ });
333
+ }
334
+
335
+ /**
336
+ * Debug image display utility for inline node debugging
337
+ * Converts images to displayable format and returns data URL with format message
338
+ * @param {object|Buffer} image - Image data (raw image object or encoded buffer)
339
+ * @param {string} outputFormat - The output format selected ('raw', 'jpg', 'png', 'webp')
340
+ * @param {number} quality - JPEG quality for raw conversion (default: 90)
341
+ * @param {object} node - Node-RED node instance for error reporting
342
+ * @param {boolean} debugEnabled - Whether debugging is enabled
343
+ * @param {number} debugWidth - Desired width for debug image display (default: 200)
344
+ * @returns {Promise<object|null>} Debug result object with dataUrl and formatMessage, or null if disabled
345
+ */
346
+ utils.debugImageDisplay = async function(image, outputFormat, quality, node, debugEnabled, debugWidth) {
347
+ if (!debugEnabled) return null;
348
+
349
+ // Validate and set default debug width
350
+ debugWidth = Math.max(1, parseInt(debugWidth) || 200);
351
+
352
+ try {
353
+ let imageBuffer, formatMessage;
354
+
355
+ if (outputFormat === 'raw') {
356
+ // Convert raw image to JPG for display using existing utility
357
+ imageBuffer = await utils.rawToJpeg(image, quality || CONSTANTS.DEFAULT_JPEG_QUALITY);
358
+ formatMessage = 'jpg default';
359
+ } else {
360
+ // Reuse existing converted buffer
361
+ imageBuffer = Buffer.isBuffer(image) ? image : image.data;
362
+ formatMessage = outputFormat; // 'jpg', 'png', 'webp'
363
+ }
364
+
365
+ if (!Buffer.isBuffer(imageBuffer)) {
366
+ node.warn('Debug display: Invalid image buffer format');
367
+ return null;
368
+ }
369
+
370
+ // Resize image for debug display using Sharp
371
+ let actualWidth = debugWidth;
372
+ let actualHeight = debugWidth; // Default fallback
373
+ try {
374
+ let sharpInstance = sharp(imageBuffer)
375
+ .resize(debugWidth, null, {
376
+ withoutEnlargement: false,
377
+ fit: 'inside'
378
+ });
379
+
380
+ // Only convert format if output is raw, otherwise preserve the existing format
381
+ if (outputFormat === 'raw') {
382
+ // For raw format, convert to JPEG for display
383
+ sharpInstance = sharpInstance.jpeg({ quality: quality || 90 });
384
+ formatMessage = 'jpg default';
385
+ } else {
386
+ // For other formats (jpg, png, webp), just resize without format conversion
387
+ // The C++ backend has already converted to the desired format
388
+ formatMessage = outputFormat + ' resized';
389
+ }
390
+
391
+ imageBuffer = await sharpInstance.toBuffer();
392
+
393
+ // Get actual dimensions of resized image
394
+ const metadata = await sharp(imageBuffer).metadata();
395
+ actualWidth = metadata.width || debugWidth;
396
+ actualHeight = metadata.height || debugWidth;
397
+
398
+ } catch (resizeError) {
399
+ node.warn(`Debug image resize error: ${resizeError.message}`);
400
+ // Continue with original image if resize fails
401
+ // Try to get original dimensions as fallback
402
+ try {
403
+ const originalMetadata = await sharp(imageBuffer).metadata();
404
+ actualWidth = originalMetadata.width || debugWidth;
405
+ actualHeight = originalMetadata.height || debugWidth;
406
+ } catch (metadataError) {
407
+ // Use debug width as fallback
408
+ actualWidth = debugWidth;
409
+ actualHeight = debugWidth;
410
+ }
411
+ }
412
+
413
+ // Convert to base64 for WebSocket transmission
414
+ const base64 = imageBuffer.toString('base64');
415
+ const mimeType = formatMessage.replace(' default', '').replace(' resized', '');
416
+ const dataUrl = `data:image/${mimeType};base64,${base64}`;
417
+
418
+ // Send image to frontend via WebSocket for inline display
419
+ try {
420
+ RED.comms.publish("debug-image", {
421
+ id: node.id,
422
+ data: base64,
423
+ format: formatMessage,
424
+ mimeType: mimeType,
425
+ size: imageBuffer.length,
426
+ debugWidth: actualWidth,
427
+ debugHeight: actualHeight
428
+ });
429
+ } catch (wsError) {
430
+ node.warn(`Debug WebSocket error: ${wsError.message}`);
431
+ // Continue anyway - status display will still work
432
+ }
433
+
434
+ return {
435
+ dataUrl: dataUrl,
436
+ formatMessage: formatMessage,
437
+ size: imageBuffer.length
438
+ };
439
+
440
+ } catch (error) {
441
+ node.warn(`Debug display error: ${error.message}`);
442
+ return null;
443
+ }
444
+ }
445
+
446
+ /**
447
+ * Enhanced success status formatting with debug information
448
+ * @param {object} node - Node-RED node instance
449
+ * @param {number} count - Number of items processed
450
+ * @param {number} totalTime - Total processing time in ms
451
+ * @param {object} timing - Timing breakdown object
452
+ * @param {string} debugFormat - Optional debug format message to include in status
453
+ */
454
+ utils.setSuccessStatusWithDebug = function(node, count, totalTime, timing = {}, debugFormat = null) {
455
+ const { convertMs = 0, taskMs = 0, encodeMs = 0 } = timing;
456
+ let statusText = `OK: ${count} img in ${totalTime.toFixed(2)} ms ` +
457
+ `(conv ${(convertMs + encodeMs).toFixed(2)} ms | ` +
458
+ `task ${taskMs.toFixed(2)} ms)`;
459
+
460
+ if (debugFormat) {
461
+ statusText += ` | ${debugFormat}`;
462
+ }
463
+
464
+ node.status({
465
+ fill: 'green',
466
+ shape: 'dot',
467
+ text: statusText
468
+ });
469
+ }
470
+
471
+ /**
472
+ * Normalizes the performance metric key based on the node's display name.
473
+ * Falls back to the node type when the custom name is missing.
474
+ * @param {object} node - Node-RED node instance
475
+ * @returns {string} sanitized key
476
+ */
477
+ utils.getPerformanceKey = function(node) {
478
+ const base = (node && node.name && String(node.name).trim()) ||
479
+ (node && node.type) ||
480
+ 'node';
481
+ return String(base)
482
+ .trim()
483
+ .toLowerCase()
484
+ .replace(/[^a-z0-9]+/g, '_')
485
+ .replace(/^_+|_+$/g, '') || 'node';
486
+ }
487
+
488
+ /**
489
+ * Records performance metrics on the outgoing message under
490
+ * msg.performance.rpimage.{nodeNameKey}.
491
+ * @param {object} node - Node-RED node instance
492
+ * @param {object} msg - The message object being emitted
493
+ * @param {object} timings - Timing breakdown { convertMs, encodeMs, taskMs, conversion, task }
494
+ * @param {number|null} totalTime - Total processing time in ms
495
+ */
496
+ utils.recordPerformanceMetrics = function(node, msg, timings = {}, totalTime = null) {
497
+ if (!msg || !node) {
498
+ return;
499
+ }
500
+
501
+ const key = utils.getPerformanceKey(node);
502
+ const path = `performance.rpimage.${key}`;
503
+
504
+ const convertMs = typeof timings.conversion === 'number'
505
+ ? timings.conversion
506
+ : (typeof timings.convertMs === 'number' ? timings.convertMs : 0) +
507
+ (typeof timings.encodeMs === 'number' ? timings.encodeMs : 0);
508
+ const taskMs = typeof timings.task === 'number'
509
+ ? timings.task
510
+ : (typeof timings.taskMs === 'number' ? timings.taskMs : null);
511
+ const totalMs = typeof totalTime === 'number'
512
+ ? totalTime
513
+ : (typeof timings.total === 'number' ? timings.total : null);
514
+
515
+ const payload = {
516
+ conversion: Number.isFinite(convertMs) ? convertMs : null,
517
+ task: Number.isFinite(taskMs) ? taskMs : null,
518
+ total: Number.isFinite(totalMs) ? totalMs : null
519
+ };
520
+
521
+ try {
522
+ RED.util.setMessageProperty(msg, path, payload, true);
523
+ } catch (err) {
524
+ node.warn(`Failed to record performance metrics: ${err.message}`);
525
+ }
526
+ }
527
+
528
+ return utils;
529
+ }