@seekskyworld/ai-modeling 0.1.0 → 0.1.2

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 (108) hide show
  1. package/CHANGELOG.md +23 -1
  2. package/README.md +24 -6
  3. package/README.zh-CN.md +24 -6
  4. package/dist/cli/artifacts/glb-jpeg.js +1 -1
  5. package/dist/cli/artifacts/glb-jpeg.js.map +1 -1
  6. package/dist/cli/artifacts/image-background-output.js +4 -2
  7. package/dist/cli/artifacts/image-background-output.js.map +1 -1
  8. package/dist/cli/artifacts/image-encoding.js +4 -2
  9. package/dist/cli/artifacts/image-encoding.js.map +1 -1
  10. package/dist/cli/artifacts/image-size-output.js +4 -2
  11. package/dist/cli/artifacts/image-size-output.js.map +1 -1
  12. package/dist/cli/artifacts/studio-fbx-texture.js +5 -2
  13. package/dist/cli/artifacts/studio-fbx-texture.js.map +1 -1
  14. package/dist/cli/auth/coordinator.js +3 -0
  15. package/dist/cli/auth/coordinator.js.map +1 -1
  16. package/dist/cli/auth/state.js +3 -0
  17. package/dist/cli/auth/state.js.map +1 -1
  18. package/dist/cli/auth/tools.js +2 -2
  19. package/dist/cli/auth/tools.js.map +1 -1
  20. package/dist/cli/auth/types.d.ts +4 -0
  21. package/dist/cli/auth/types.js.map +1 -1
  22. package/dist/cli/compat/frontend-convert-validation.js +1 -1
  23. package/dist/cli/compat/frontend-convert-validation.js.map +1 -1
  24. package/dist/cli/compat/frontend-static-convert-validation.js +1 -1
  25. package/dist/cli/compat/frontend-static-convert-validation.js.map +1 -1
  26. package/dist/cli/compat/lab-projected-segment-geometry.js +1 -1
  27. package/dist/cli/compat/lab-projected-segment-geometry.js.map +1 -1
  28. package/dist/cli/local/brush-model.js +1 -1
  29. package/dist/cli/local/brush-model.js.map +1 -1
  30. package/dist/cli/local/brush-paint.js +1 -1
  31. package/dist/cli/local/brush-paint.js.map +1 -1
  32. package/dist/cli/local/brush.js +1 -1
  33. package/dist/cli/local/brush.js.map +1 -1
  34. package/dist/cli/local/operations.js +1 -1
  35. package/dist/cli/local/operations.js.map +1 -1
  36. package/dist/cli/local/preview-render.js +1 -1
  37. package/dist/cli/local/preview-render.js.map +1 -1
  38. package/dist/cli/local/uv-raster.js +1 -1
  39. package/dist/cli/local/uv-raster.js.map +1 -1
  40. package/dist/cli/runtime/sharp.d.ts +5 -0
  41. package/dist/cli/runtime/sharp.js +21 -0
  42. package/dist/cli/runtime/sharp.js.map +1 -0
  43. package/dist/mcp/server.js +2 -2
  44. package/dist/mcp/server.js.map +1 -1
  45. package/docs/commands.md +5 -3
  46. package/docs/development.md +6 -4
  47. package/docs/usage.md +13 -9
  48. package/examples/README.md +2 -2
  49. package/examples/mcp-npx.json +1 -1
  50. package/npm-shrinkwrap.json +8 -4
  51. package/package.json +7 -3
  52. package/skills/ai-modeling/SKILL.md +1 -1
  53. package/skills/ai-modeling/references/pipelines.md +2 -2
  54. package/skills/ai-modeling/references/usage.md +6 -4
  55. package/node_modules/@napi-rs/keyring/LICENSE +0 -21
  56. package/node_modules/@napi-rs/keyring/README.md +0 -70
  57. package/node_modules/@napi-rs/keyring/index.d.ts +0 -232
  58. package/node_modules/@napi-rs/keyring/index.js +0 -706
  59. package/node_modules/@napi-rs/keyring/keytar.d.ts +0 -53
  60. package/node_modules/@napi-rs/keyring/keytar.js +0 -26
  61. package/node_modules/@napi-rs/keyring/package.json +0 -127
  62. package/node_modules/sharp/LICENSE +0 -191
  63. package/node_modules/sharp/README.md +0 -112
  64. package/node_modules/sharp/dist/channel.cjs +0 -177
  65. package/node_modules/sharp/dist/channel.mjs +0 -177
  66. package/node_modules/sharp/dist/colour.cjs +0 -199
  67. package/node_modules/sharp/dist/colour.mjs +0 -199
  68. package/node_modules/sharp/dist/composite.cjs +0 -213
  69. package/node_modules/sharp/dist/composite.mjs +0 -213
  70. package/node_modules/sharp/dist/constructor.cjs +0 -511
  71. package/node_modules/sharp/dist/constructor.mjs +0 -511
  72. package/node_modules/sharp/dist/index.cjs +0 -25
  73. package/node_modules/sharp/dist/index.d.cts +0 -1999
  74. package/node_modules/sharp/dist/index.d.mts +0 -2046
  75. package/node_modules/sharp/dist/index.mjs +0 -25
  76. package/node_modules/sharp/dist/input.cjs +0 -819
  77. package/node_modules/sharp/dist/input.mjs +0 -819
  78. package/node_modules/sharp/dist/is.cjs +0 -149
  79. package/node_modules/sharp/dist/is.mjs +0 -149
  80. package/node_modules/sharp/dist/libvips.cjs +0 -212
  81. package/node_modules/sharp/dist/libvips.mjs +0 -212
  82. package/node_modules/sharp/dist/operation.cjs +0 -1002
  83. package/node_modules/sharp/dist/operation.mjs +0 -1002
  84. package/node_modules/sharp/dist/output.cjs +0 -1786
  85. package/node_modules/sharp/dist/output.mjs +0 -1786
  86. package/node_modules/sharp/dist/resize.cjs +0 -617
  87. package/node_modules/sharp/dist/resize.mjs +0 -617
  88. package/node_modules/sharp/dist/sharp.cjs +0 -174
  89. package/node_modules/sharp/dist/sharp.mjs +0 -174
  90. package/node_modules/sharp/dist/utility.cjs +0 -301
  91. package/node_modules/sharp/dist/utility.mjs +0 -301
  92. package/node_modules/sharp/install/build.js +0 -38
  93. package/node_modules/sharp/lib/index.d.ts +0 -1999
  94. package/node_modules/sharp/package.json +0 -227
  95. package/node_modules/sharp/src/binding.gyp +0 -303
  96. package/node_modules/sharp/src/common.cc +0 -1186
  97. package/node_modules/sharp/src/common.h +0 -421
  98. package/node_modules/sharp/src/metadata.cc +0 -404
  99. package/node_modules/sharp/src/metadata.h +0 -95
  100. package/node_modules/sharp/src/operations.cc +0 -516
  101. package/node_modules/sharp/src/operations.h +0 -137
  102. package/node_modules/sharp/src/pipeline.cc +0 -1973
  103. package/node_modules/sharp/src/pipeline.h +0 -422
  104. package/node_modules/sharp/src/sharp.cc +0 -43
  105. package/node_modules/sharp/src/stats.cc +0 -186
  106. package/node_modules/sharp/src/stats.h +0 -62
  107. package/node_modules/sharp/src/utilities.cc +0 -289
  108. package/node_modules/sharp/src/utilities.h +0 -22
@@ -1,1973 +0,0 @@
1
- /*!
2
- Copyright 2013 Lovell Fuller and others.
3
- SPDX-License-Identifier: Apache-2.0
4
- */
5
-
6
- #include <algorithm>
7
- #include <cmath>
8
- #include <filesystem> // NOLINT(build/c++17)
9
- #include <map>
10
- #include <memory>
11
- #include <numeric>
12
- #include <string>
13
- #include <tuple>
14
- #include <utility>
15
- #include <vector>
16
- #include <sys/types.h>
17
- #include <sys/stat.h>
18
-
19
- #include <vips/vips8>
20
- #include <napi.h>
21
-
22
- #include "./common.h"
23
- #include "./operations.h"
24
- #include "./pipeline.h"
25
-
26
- class PipelineWorker : public Napi::AsyncWorker {
27
- public:
28
- PipelineWorker(Napi::Function callback, PipelineBaton *baton,
29
- Napi::Function debuglog, Napi::Function queueListener) :
30
- Napi::AsyncWorker(callback),
31
- baton(baton),
32
- debuglog(Napi::Persistent(debuglog)),
33
- queueListener(Napi::Persistent(queueListener)) {}
34
- ~PipelineWorker() {}
35
-
36
- // libuv worker
37
- void Execute() {
38
- // Decrement queued task counter
39
- sharp::counterQueue--;
40
- // Increment processing task counter
41
- sharp::counterProcess++;
42
-
43
- try {
44
- // Open input
45
- vips::VImage image;
46
- sharp::ImageType inputImageType;
47
- if (baton->join.empty()) {
48
- std::tie(image, inputImageType) = sharp::OpenInput(baton->input);
49
- } else {
50
- std::vector<VImage> images;
51
- bool hasAlpha = false;
52
- for (auto &join : baton->join) {
53
- std::tie(image, inputImageType) = sharp::OpenInput(join);
54
- image = sharp::EnsureColourspace(image, baton->colourspacePipeline);
55
- images.push_back(image);
56
- hasAlpha |= image.has_alpha();
57
- }
58
- if (hasAlpha) {
59
- for (size_t i = 0; i < images.size(); i++) {
60
- if (!images[i].has_alpha()) {
61
- images[i] = sharp::EnsureAlpha(images[i], 1);
62
- }
63
- }
64
- } else {
65
- baton->input->joinBackground.pop_back();
66
- }
67
- inputImageType = sharp::ImageType::PNG;
68
- image = VImage::arrayjoin(images, VImage::option()
69
- ->set("across", baton->input->joinAcross)
70
- ->set("shim", baton->input->joinShim)
71
- ->set("background", baton->input->joinBackground)
72
- ->set("halign", baton->input->joinHalign)
73
- ->set("valign", baton->input->joinValign));
74
- if (baton->input->joinAnimated) {
75
- image = image.copy();
76
- image.set(VIPS_META_N_PAGES, static_cast<int>(images.size()));
77
- image.set(VIPS_META_PAGE_HEIGHT, static_cast<int>(image.height() / images.size()));
78
- }
79
- }
80
- VipsAccess access = baton->input->access;
81
- image = sharp::EnsureColourspace(image, baton->colourspacePipeline);
82
-
83
- int nPages = baton->input->pages;
84
- if (nPages == -1) {
85
- // Resolve the number of pages if we need to render until the end of the document
86
- nPages = image.get_typeof(VIPS_META_N_PAGES) != 0
87
- ? image.get_int(VIPS_META_N_PAGES) - std::max(0, baton->input->page)
88
- : 1;
89
- }
90
-
91
- // Get pre-resize page height
92
- int pageHeight = sharp::GetPageHeight(image);
93
-
94
- // Calculate angle of rotation
95
- VipsAngle rotation = VIPS_ANGLE_D0;
96
- VipsAngle autoRotation = VIPS_ANGLE_D0;
97
- VipsAngle gainMapRotation = VIPS_ANGLE_D0;
98
- bool autoFlop = false;
99
- bool gainMapFlip = false;
100
- bool gainMapFlop = false;
101
-
102
- if (baton->input->autoOrient) {
103
- // Rotate and flip image according to Exif orientation
104
- std::tie(autoRotation, autoFlop) = CalculateExifRotationAndFlop(sharp::ExifOrientation(image));
105
- }
106
-
107
- rotation = CalculateAngleRotation(baton->angle);
108
-
109
- bool const shouldRotateBefore = baton->rotateBefore &&
110
- (rotation != VIPS_ANGLE_D0 || baton->flip || baton->flop || baton->rotationAngle != 0.0);
111
- bool const shouldOrientBefore = (shouldRotateBefore || baton->orientBefore) &&
112
- (autoRotation != VIPS_ANGLE_D0 || autoFlop);
113
-
114
- if (shouldOrientBefore) {
115
- image = sharp::StaySequential(image, autoRotation != VIPS_ANGLE_D0);
116
- if (autoRotation != VIPS_ANGLE_D0) {
117
- if (autoRotation != VIPS_ANGLE_D180) {
118
- MultiPageUnsupported(nPages, "Rotate");
119
- }
120
- image = image.rot(autoRotation);
121
- gainMapRotation = autoRotation;
122
- autoRotation = VIPS_ANGLE_D0;
123
- }
124
- if (autoFlop) {
125
- image = image.flip(VIPS_DIRECTION_HORIZONTAL);
126
- autoFlop = false;
127
- gainMapFlop = true;
128
- }
129
- }
130
-
131
- if (shouldRotateBefore) {
132
- image = sharp::StaySequential(image, rotation != VIPS_ANGLE_D0 || baton->flip || baton->rotationAngle != 0.0);
133
- if (baton->flip) {
134
- image = image.flip(VIPS_DIRECTION_VERTICAL);
135
- baton->flip = false;
136
- gainMapFlip = true;
137
- }
138
- if (baton->flop) {
139
- image = image.flip(VIPS_DIRECTION_HORIZONTAL);
140
- baton->flop = false;
141
- gainMapFlop = true;
142
- }
143
- if (rotation != VIPS_ANGLE_D0) {
144
- if (rotation != VIPS_ANGLE_D180) {
145
- MultiPageUnsupported(nPages, "Rotate");
146
- }
147
- image = image.rot(rotation);
148
- gainMapRotation = rotation;
149
- rotation = VIPS_ANGLE_D0;
150
- }
151
- if (baton->rotationAngle != 0.0) {
152
- MultiPageUnsupported(nPages, "Rotate");
153
- KeepGainMapUnsupported(baton->keepGainMap, "Rotate");
154
- std::vector<double> background;
155
- std::tie(image, background) = sharp::ApplyAlpha(image, baton->rotationBackground, false);
156
- image = image.rotate(baton->rotationAngle, VImage::option()->set("background", background)).copy_memory();
157
- baton->rotationAngle = 0.0;
158
- }
159
- }
160
-
161
- // Trim
162
- if (baton->trimThreshold >= 0.0) {
163
- MultiPageUnsupported(nPages, "Trim");
164
- KeepGainMapUnsupported(baton->keepGainMap, "Trim");
165
- image = sharp::StaySequential(image);
166
- image = sharp::Trim(image, baton->trimBackground, baton->trimThreshold, baton->trimLineArt, baton->trimMargin);
167
- baton->trimOffsetLeft = image.xoffset();
168
- baton->trimOffsetTop = image.yoffset();
169
- }
170
-
171
- // Pre extraction
172
- if (baton->topOffsetPre != -1) {
173
- image = nPages > 1
174
- ? sharp::CropMultiPage(image,
175
- baton->leftOffsetPre, baton->topOffsetPre, baton->widthPre, baton->heightPre, nPages, &pageHeight)
176
- : image.extract_area(baton->leftOffsetPre, baton->topOffsetPre, baton->widthPre, baton->heightPre);
177
- }
178
-
179
- // Get pre-resize image width and height
180
- int inputWidth = image.width();
181
- int inputHeight = image.height();
182
-
183
- // Is there just one page? Shrink to inputHeight instead
184
- if (nPages == 1) {
185
- pageHeight = inputHeight;
186
- }
187
-
188
- // Scaling calculations
189
- double hshrink;
190
- double vshrink;
191
- int targetResizeWidth = baton->width;
192
- int targetResizeHeight = baton->height;
193
-
194
- // When auto-rotating by 90 or 270 degrees, swap the target width and
195
- // height to ensure the behavior aligns with how it would have been if
196
- // the rotation had taken place *before* resizing.
197
- if (autoRotation == VIPS_ANGLE_D90 || autoRotation == VIPS_ANGLE_D270) {
198
- std::swap(targetResizeWidth, targetResizeHeight);
199
- }
200
-
201
- // Shrink to pageHeight, so we work for multi-page images
202
- std::tie(hshrink, vshrink) = sharp::ResolveShrink(
203
- inputWidth, pageHeight, targetResizeWidth, targetResizeHeight,
204
- baton->canvas, baton->withoutEnlargement, baton->withoutReduction);
205
-
206
- // The jpeg preload shrink.
207
- int jpegShrinkOnLoad = 1;
208
-
209
- // WebP, PDF, SVG scale
210
- double scale = 1.0;
211
-
212
- // Try to reload input using shrink-on-load for JPEG, WebP, SVG and PDF, when:
213
- // - the width or height parameters are specified;
214
- // - gamma correction doesn't need to be applied;
215
- // - trimming or pre-resize extract isn't required;
216
- // - gain map processing is not required;
217
- // - input colourspace is not specified;
218
- bool const shouldPreShrink = (targetResizeWidth > 0 || targetResizeHeight > 0) &&
219
- baton->gamma == 0 && baton->topOffsetPre == -1 && baton->trimThreshold < 0.0 &&
220
- !baton->keepGainMap && !baton->withGainMap &&
221
- baton->colourspacePipeline == VIPS_INTERPRETATION_LAST && !(shouldOrientBefore || shouldRotateBefore);
222
-
223
- if (shouldPreShrink) {
224
- // The common part of the shrink: the bit by which both axes must be shrunk
225
- double shrink = std::min(hshrink, vshrink);
226
-
227
- if (inputImageType == sharp::ImageType::JPEG) {
228
- // Leave at least a factor of two for the final resize step, when fastShrinkOnLoad: false
229
- // for more consistent results and to avoid extra sharpness to the image
230
- int factor = baton->fastShrinkOnLoad ? 1 : 2;
231
- if (shrink >= 8 * factor) {
232
- jpegShrinkOnLoad = 8;
233
- } else if (shrink >= 4 * factor) {
234
- jpegShrinkOnLoad = 4;
235
- } else if (shrink >= 2 * factor) {
236
- jpegShrinkOnLoad = 2;
237
- }
238
- // Lower shrink-on-load for known libjpeg rounding errors
239
- if (jpegShrinkOnLoad > 1 && static_cast<int>(shrink) == jpegShrinkOnLoad) {
240
- jpegShrinkOnLoad /= 2;
241
- }
242
- } else if (inputImageType == sharp::ImageType::WEBP && baton->fastShrinkOnLoad && shrink > 1.0) {
243
- // Avoid upscaling via webp
244
- scale = 1.0 / shrink;
245
- } else if (inputImageType == sharp::ImageType::SVG ||
246
- inputImageType == sharp::ImageType::PDF) {
247
- scale = 1.0 / shrink;
248
- }
249
- }
250
-
251
- // Reload input using shrink-on-load, it'll be an integer shrink
252
- // factor for jpegload*, a double scale factor for webpload*,
253
- // pdfload* and svgload*
254
- if (jpegShrinkOnLoad > 1) {
255
- vips::VOption *option = GetOptionsForImageType(inputImageType, baton->input)->set("shrink", jpegShrinkOnLoad);
256
- if (baton->input->buffer != nullptr) {
257
- // Reload JPEG buffer
258
- VipsBlob *blob = vips_blob_new(nullptr, baton->input->buffer, baton->input->bufferLength);
259
- image = VImage::jpegload_buffer(blob, option);
260
- vips_area_unref(reinterpret_cast<VipsArea*>(blob));
261
- } else {
262
- // Reload JPEG file
263
- image = VImage::jpegload(const_cast<char*>(baton->input->file.data()), option);
264
- }
265
- } else if (scale != 1.0) {
266
- vips::VOption *option = GetOptionsForImageType(inputImageType, baton->input)->set("scale", scale);
267
- if (inputImageType == sharp::ImageType::WEBP) {
268
- if (baton->input->buffer != nullptr) {
269
- // Reload WebP buffer
270
- VipsBlob *blob = vips_blob_new(nullptr, baton->input->buffer, baton->input->bufferLength);
271
- image = VImage::webpload_buffer(blob, option);
272
- vips_area_unref(reinterpret_cast<VipsArea*>(blob));
273
- } else {
274
- // Reload WebP file
275
- image = VImage::webpload(const_cast<char*>(baton->input->file.data()), option);
276
- }
277
- } else if (inputImageType == sharp::ImageType::SVG) {
278
- if (baton->input->buffer != nullptr) {
279
- // Reload SVG buffer
280
- VipsBlob *blob = vips_blob_new(nullptr, baton->input->buffer, baton->input->bufferLength);
281
- image = VImage::svgload_buffer(blob, option);
282
- vips_area_unref(reinterpret_cast<VipsArea*>(blob));
283
- } else {
284
- // Reload SVG file
285
- image = VImage::svgload(const_cast<char*>(baton->input->file.data()), option);
286
- }
287
- sharp::SetDensity(image, baton->input->density);
288
- if (image.width() > 32767 || image.height() > 32767) {
289
- throw std::runtime_error("Input SVG image will exceed 32767x32767 pixel limit when scaled");
290
- }
291
- } else if (inputImageType == sharp::ImageType::PDF) {
292
- if (baton->input->buffer != nullptr) {
293
- // Reload PDF buffer
294
- VipsBlob *blob = vips_blob_new(nullptr, baton->input->buffer, baton->input->bufferLength);
295
- image = VImage::pdfload_buffer(blob, option);
296
- vips_area_unref(reinterpret_cast<VipsArea*>(blob));
297
- } else {
298
- // Reload PDF file
299
- image = VImage::pdfload(const_cast<char*>(baton->input->file.data()), option);
300
- }
301
- sharp::SetDensity(image, baton->input->density);
302
- }
303
- } else {
304
- if (inputImageType == sharp::ImageType::SVG && (image.width() > 32767 || image.height() > 32767)) {
305
- throw std::runtime_error("Input SVG image exceeds 32767x32767 pixel limit");
306
- }
307
- }
308
- if (baton->input->autoOrient) {
309
- image = sharp::RemoveExifOrientation(image);
310
- }
311
- VImage gainMap;
312
- int gainMapScaleFactor = 1;
313
- if (sharp::HasGainMap(image)) {
314
- if (baton->keepGainMap) {
315
- gainMap = image.gainmap();
316
- if (image.get_typeof("gainmap-scale-factor") == G_TYPE_INT) {
317
- gainMapScaleFactor = image.get_int("gainmap-scale-factor");
318
- }
319
- if (gainMapFlip) {
320
- gainMap = gainMap.flip(VIPS_DIRECTION_VERTICAL);
321
- }
322
- if (gainMapFlop) {
323
- gainMap = gainMap.flip(VIPS_DIRECTION_HORIZONTAL);
324
- }
325
- if (gainMapRotation != VIPS_ANGLE_D0) {
326
- gainMap = gainMap.rot(gainMapRotation);
327
- }
328
- if (baton->topOffsetPre != -1) {
329
- gainMap = gainMap.extract_area(
330
- baton->leftOffsetPre / gainMapScaleFactor, baton->topOffsetPre / gainMapScaleFactor,
331
- baton->widthPre / gainMapScaleFactor, baton->heightPre / gainMapScaleFactor);
332
- }
333
- } else if (baton->withGainMap) {
334
- image = image.uhdr2scRGB();
335
- }
336
- image = sharp::RemoveGainMap(image);
337
- } else {
338
- baton->keepGainMap = false;
339
- baton->withGainMap = false;
340
- }
341
-
342
- // Any pre-shrinking may already have been done
343
- inputWidth = image.width();
344
- inputHeight = image.height();
345
-
346
- // After pre-shrink, but before the main shrink stage
347
- // Reuse the initial pageHeight if we didn't pre-shrink
348
- if (shouldPreShrink) {
349
- pageHeight = sharp::GetPageHeight(image);
350
- }
351
-
352
- // Shrink to pageHeight, so we work for multi-page images
353
- std::tie(hshrink, vshrink) = sharp::ResolveShrink(
354
- inputWidth, pageHeight, targetResizeWidth, targetResizeHeight,
355
- baton->canvas, baton->withoutEnlargement, baton->withoutReduction);
356
-
357
- int targetHeight = static_cast<int>(std::rint(static_cast<double>(pageHeight) / vshrink));
358
- int targetPageHeight = targetHeight;
359
-
360
- // In toilet-roll mode, we must adjust vshrink so that we exactly hit
361
- // pageHeight or we'll have pixels straddling pixel boundaries
362
- if (inputHeight > pageHeight) {
363
- targetHeight *= nPages;
364
- vshrink = static_cast<double>(inputHeight) / targetHeight;
365
- }
366
-
367
- // Ensure we're using a device-independent colour space
368
- std::pair<char*, size_t> inputProfile(nullptr, 0);
369
- if ((baton->keepMetadata & VIPS_FOREIGN_KEEP_ICC) && baton->withIccProfile.empty()) {
370
- // Cache input profile for use with output
371
- inputProfile = sharp::GetProfile(image);
372
- baton->input->ignoreIcc = true;
373
- }
374
- char const *processingProfile = image.interpretation() == VIPS_INTERPRETATION_RGB16 ? "p3" : "srgb";
375
- if (
376
- sharp::HasProfile(image) &&
377
- image.interpretation() != VIPS_INTERPRETATION_LABS &&
378
- image.interpretation() != VIPS_INTERPRETATION_GREY16 &&
379
- baton->colourspacePipeline != VIPS_INTERPRETATION_CMYK &&
380
- !baton->input->ignoreIcc && !baton->withGainMap
381
- ) {
382
- // Convert to sRGB/P3 using embedded profile
383
- try {
384
- image = image.icc_transform(processingProfile, VImage::option()
385
- ->set("embedded", true)
386
- ->set("depth", sharp::Is16Bit(image.interpretation()) ? 16 : 8)
387
- ->set("intent", VIPS_INTENT_PERCEPTUAL));
388
- } catch(...) {
389
- sharp::VipsWarningCallback(nullptr, G_LOG_LEVEL_WARNING, "Invalid embedded profile", nullptr);
390
- }
391
- } else if (
392
- image.interpretation() == VIPS_INTERPRETATION_CMYK &&
393
- baton->colourspacePipeline != VIPS_INTERPRETATION_CMYK
394
- ) {
395
- image = image.icc_transform(processingProfile, VImage::option()
396
- ->set("input_profile", "cmyk")
397
- ->set("intent", VIPS_INTENT_PERCEPTUAL));
398
- }
399
-
400
- // Flatten image to remove alpha channel
401
- if (baton->flatten && image.has_alpha()) {
402
- image = sharp::Flatten(image, baton->flattenBackground);
403
- }
404
-
405
- // Gamma encoding (darken)
406
- if (baton->gamma >= 1 && baton->gamma <= 3) {
407
- image = sharp::Gamma(image, 1.0 / baton->gamma);
408
- }
409
-
410
- // Convert to greyscale (linear, therefore after gamma encoding, if any)
411
- if (baton->greyscale) {
412
- image = image.colourspace(VIPS_INTERPRETATION_B_W);
413
- }
414
-
415
- bool const shouldResize = hshrink != 1.0 || vshrink != 1.0;
416
- bool const shouldBlur = baton->blurSigma != 0.0;
417
- bool const shouldConv = baton->convKernelWidth * baton->convKernelHeight > 0;
418
- bool const shouldSharpen = baton->sharpenSigma != 0.0;
419
- bool const shouldComposite = !baton->composite.empty();
420
-
421
- if (shouldComposite && !image.has_alpha()) {
422
- image = sharp::EnsureAlpha(image, 1);
423
- }
424
-
425
- VipsBandFormat premultiplyFormat = image.format();
426
- bool const shouldPremultiplyAlpha = image.has_alpha() &&
427
- (shouldResize || shouldBlur || shouldConv || shouldSharpen);
428
-
429
- if (shouldPremultiplyAlpha) {
430
- image = image.premultiply().cast(premultiplyFormat);
431
- }
432
-
433
- // Resize
434
- if (shouldResize) {
435
- image = image.resize(1.0 / hshrink, VImage::option()
436
- ->set("vscale", 1.0 / vshrink)
437
- ->set("kernel", baton->kernel));
438
- if (baton->keepGainMap) {
439
- gainMap = gainMap.resize(1.0 / hshrink, VImage::option()
440
- ->set("vscale", 1.0 / vshrink)
441
- ->set("kernel", baton->kernel));
442
- }
443
- }
444
-
445
- image = sharp::StaySequential(image,
446
- autoRotation != VIPS_ANGLE_D0 ||
447
- baton->flip ||
448
- rotation != VIPS_ANGLE_D0);
449
- // Auto-rotate post-extract
450
- if (autoRotation != VIPS_ANGLE_D0) {
451
- if (autoRotation != VIPS_ANGLE_D180) {
452
- MultiPageUnsupported(nPages, "Rotate");
453
- }
454
- image = image.rot(autoRotation);
455
- if (baton->keepGainMap) {
456
- gainMap = sharp::StaySequential(gainMap).rot(autoRotation);
457
- }
458
- }
459
- // Mirror vertically (up-down) about the x-axis
460
- if (baton->flip) {
461
- image = image.flip(VIPS_DIRECTION_VERTICAL);
462
- if (baton->keepGainMap) {
463
- gainMap = sharp::StaySequential(gainMap).flip(VIPS_DIRECTION_VERTICAL);
464
- }
465
- }
466
- // Mirror horizontally (left-right) about the y-axis
467
- if (baton->flop != autoFlop) {
468
- image = image.flip(VIPS_DIRECTION_HORIZONTAL);
469
- if (baton->keepGainMap) {
470
- gainMap = gainMap.flip(VIPS_DIRECTION_HORIZONTAL);
471
- }
472
- }
473
- // Rotate post-extract 90-angle
474
- if (rotation != VIPS_ANGLE_D0) {
475
- if (rotation != VIPS_ANGLE_D180) {
476
- MultiPageUnsupported(nPages, "Rotate");
477
- }
478
- image = image.rot(rotation);
479
- if (baton->keepGainMap) {
480
- gainMap = sharp::StaySequential(gainMap).rot(rotation);
481
- }
482
- }
483
-
484
- // Join additional color channels to the image
485
- if (!baton->joinChannelIn.empty()) {
486
- VImage joinImage;
487
- sharp::ImageType joinImageType = sharp::ImageType::UNKNOWN;
488
-
489
- for (unsigned int i = 0; i < baton->joinChannelIn.size(); i++) {
490
- baton->joinChannelIn[i]->access = access;
491
- std::tie(joinImage, joinImageType) = sharp::OpenInput(baton->joinChannelIn[i]);
492
- joinImage = sharp::EnsureColourspace(joinImage, baton->colourspacePipeline);
493
- image = image.bandjoin(joinImage);
494
- }
495
- image = image.copy(VImage::option()->set("interpretation", baton->colourspace));
496
- image = sharp::RemoveGifPalette(image);
497
- }
498
-
499
- inputWidth = image.width();
500
- inputHeight = nPages > 1 ? targetPageHeight : image.height();
501
-
502
- // Resolve dimensions
503
- if (baton->width <= 0) {
504
- baton->width = inputWidth;
505
- }
506
- if (baton->height <= 0) {
507
- baton->height = inputHeight;
508
- }
509
-
510
- // Crop/embed
511
- if (inputWidth != baton->width || inputHeight != baton->height) {
512
- if (baton->canvas == sharp::Canvas::EMBED) {
513
- std::vector<double> background;
514
- std::tie(image, background) = sharp::ApplyAlpha(image, baton->resizeBackground, shouldPremultiplyAlpha);
515
-
516
- // Embed
517
- const auto& [left, top] = sharp::CalculateEmbedPosition(
518
- inputWidth, inputHeight, baton->width, baton->height, baton->position);
519
- const int width = std::max(inputWidth, baton->width);
520
- const int height = std::max(inputHeight, baton->height);
521
-
522
- image = nPages > 1
523
- ? sharp::EmbedMultiPage(image,
524
- left, top, width, height, VIPS_EXTEND_BACKGROUND, background, nPages, &targetPageHeight)
525
- : image.embed(left, top, width, height, VImage::option()
526
- ->set("extend", VIPS_EXTEND_BACKGROUND)
527
- ->set("background", background));
528
- if (baton->keepGainMap) {
529
- gainMap = gainMap.embed(left / gainMapScaleFactor, top / gainMapScaleFactor,
530
- width / gainMapScaleFactor, height / gainMapScaleFactor, VImage::option()
531
- ->set("extend", VIPS_EXTEND_BACKGROUND)
532
- ->set("background", 0));
533
- }
534
- } else if (baton->canvas == sharp::Canvas::CROP) {
535
- if (baton->width > inputWidth) {
536
- baton->width = inputWidth;
537
- }
538
- if (baton->height > inputHeight) {
539
- baton->height = inputHeight;
540
- }
541
-
542
- // Crop
543
- if (baton->position < 9) {
544
- // Gravity-based crop
545
- const auto& [left, top] = sharp::CalculateCrop(
546
- inputWidth, inputHeight, baton->width, baton->height, baton->position);
547
- const int width = std::min(inputWidth, baton->width);
548
- const int height = std::min(inputHeight, baton->height);
549
-
550
- image = nPages > 1
551
- ? sharp::CropMultiPage(image,
552
- left, top, width, height, nPages, &targetPageHeight)
553
- : image.extract_area(left, top, width, height);
554
- if (baton->keepGainMap) {
555
- gainMap = gainMap.extract_area(left / gainMapScaleFactor, top / gainMapScaleFactor,
556
- width / gainMapScaleFactor, height / gainMapScaleFactor);
557
- }
558
- } else {
559
- int attention_x;
560
- int attention_y;
561
-
562
- // Attention-based or Entropy-based crop
563
- MultiPageUnsupported(nPages, "Resize strategy");
564
- KeepGainMapUnsupported(baton->keepGainMap, "Resize strategy");
565
- image = sharp::StaySequential(image);
566
- image = image.smartcrop(baton->width, baton->height, VImage::option()
567
- ->set("interesting", baton->position == 16 ? VIPS_INTERESTING_ENTROPY : VIPS_INTERESTING_ATTENTION)
568
- ->set("premultiplied", shouldPremultiplyAlpha)
569
- ->set("attention_x", &attention_x)
570
- ->set("attention_y", &attention_y));
571
- baton->hasCropOffset = true;
572
- baton->cropOffsetLeft = static_cast<int>(image.xoffset());
573
- baton->cropOffsetTop = static_cast<int>(image.yoffset());
574
- baton->hasAttentionCenter = true;
575
- baton->attentionX = static_cast<int>(attention_x * jpegShrinkOnLoad / scale);
576
- baton->attentionY = static_cast<int>(attention_y * jpegShrinkOnLoad / scale);
577
- }
578
- }
579
- }
580
-
581
- // Rotate post-extract non-90 angle
582
- if (!baton->rotateBefore && baton->rotationAngle != 0.0) {
583
- MultiPageUnsupported(nPages, "Rotate");
584
- KeepGainMapUnsupported(baton->keepGainMap, "Rotate");
585
- image = sharp::StaySequential(image);
586
- std::vector<double> background;
587
- std::tie(image, background) = sharp::ApplyAlpha(image, baton->rotationBackground, shouldPremultiplyAlpha);
588
- image = image.rotate(baton->rotationAngle, VImage::option()->set("background", background));
589
- if (baton->keepGainMap) {
590
- gainMap = gainMap.rotate(baton->rotationAngle, VImage::option()->set("background", 0));
591
- }
592
- }
593
-
594
- // Post extraction
595
- if (baton->topOffsetPost != -1) {
596
- if (nPages > 1) {
597
- image = sharp::CropMultiPage(image,
598
- baton->leftOffsetPost, baton->topOffsetPost, baton->widthPost, baton->heightPost,
599
- nPages, &targetPageHeight);
600
- // heightPost is used in the info object, so update to reflect the number of pages
601
- baton->heightPost *= nPages;
602
- } else {
603
- image = image.extract_area(
604
- baton->leftOffsetPost, baton->topOffsetPost, baton->widthPost, baton->heightPost);
605
- if (baton->keepGainMap) {
606
- gainMap = gainMap.extract_area(baton->leftOffsetPost / gainMapScaleFactor,
607
- baton->topOffsetPost / gainMapScaleFactor, baton->widthPost / gainMapScaleFactor,
608
- baton->heightPost / gainMapScaleFactor);
609
- }
610
- }
611
- }
612
-
613
- // Affine transform
614
- if (!baton->affineMatrix.empty()) {
615
- MultiPageUnsupported(nPages, "Affine");
616
- KeepGainMapUnsupported(baton->keepGainMap, "Affine");
617
- image = sharp::StaySequential(image);
618
- std::vector<double> background;
619
- std::tie(image, background) = sharp::ApplyAlpha(image, baton->affineBackground, shouldPremultiplyAlpha);
620
- vips::VInterpolate interp = vips::VInterpolate::new_from_name(
621
- const_cast<char*>(baton->affineInterpolator.data()));
622
- image = image.affine(baton->affineMatrix, VImage::option()->set("background", background)
623
- ->set("idx", baton->affineIdx)
624
- ->set("idy", baton->affineIdy)
625
- ->set("odx", baton->affineOdx)
626
- ->set("ody", baton->affineOdy)
627
- ->set("interpolate", interp));
628
- }
629
-
630
- // Extend edges
631
- if (baton->extendTop > 0 || baton->extendBottom > 0 || baton->extendLeft > 0 || baton->extendRight > 0) {
632
- // Embed
633
- baton->width = image.width() + baton->extendLeft + baton->extendRight;
634
- baton->height = (nPages > 1 ? targetPageHeight : image.height()) + baton->extendTop + baton->extendBottom;
635
-
636
- std::vector<double> background;
637
- if (baton->extendWith == VIPS_EXTEND_BACKGROUND) {
638
- std::tie(image, background) = sharp::ApplyAlpha(image, baton->extendBackground, shouldPremultiplyAlpha);
639
- }
640
- image = sharp::StaySequential(image, nPages > 1 || baton->extendWith != VIPS_EXTEND_BACKGROUND);
641
- auto options = VImage::option()->set("extend", baton->extendWith);
642
- if (baton->extendWith == VIPS_EXTEND_BACKGROUND) {
643
- options->set("background", background);
644
- }
645
- image = nPages > 1
646
- ? sharp::EmbedMultiPage(image,
647
- baton->extendLeft, baton->extendTop, baton->width, baton->height,
648
- baton->extendWith, background, nPages, &targetPageHeight)
649
- : image.embed(baton->extendLeft, baton->extendTop, baton->width, baton->height, options);
650
- if (baton->keepGainMap) {
651
- gainMap = gainMap.embed(baton->extendLeft / gainMapScaleFactor, baton->extendTop / gainMapScaleFactor,
652
- baton->width / gainMapScaleFactor, baton->height / gainMapScaleFactor, VImage::option()
653
- ->set("extend", baton->extendWith)
654
- ->set("background", 0));
655
- }
656
- }
657
- // Median - must happen before blurring, due to the utility of blurring after thresholding
658
- if (baton->medianSize > 0) {
659
- image = image.median(baton->medianSize);
660
- }
661
-
662
- // Threshold - must happen before blurring, due to the utility of blurring after thresholding
663
- // Threshold - must happen before unflatten to enable non-white unflattening
664
- if (baton->threshold != 0) {
665
- image = sharp::Threshold(image, baton->threshold, baton->thresholdGrayscale);
666
- }
667
-
668
- // Dilate - must happen before blurring, due to the utility of dilating after thresholding
669
- if (baton->dilateWidth != 0) {
670
- image = sharp::Dilate(image, baton->dilateWidth);
671
- }
672
-
673
- // Erode - must happen before blurring, due to the utility of eroding after thresholding
674
- if (baton->erodeWidth != 0) {
675
- image = sharp::Erode(image, baton->erodeWidth);
676
- }
677
-
678
- // Blur
679
- if (shouldBlur) {
680
- image = sharp::Blur(image, baton->blurSigma, baton->precision, baton->minAmpl);
681
- if (baton->keepGainMap) {
682
- gainMap = sharp::Blur(gainMap, baton->blurSigma, baton->precision, baton->minAmpl);
683
- }
684
- }
685
-
686
- // Unflatten the image
687
- if (baton->unflatten) {
688
- image = sharp::Unflatten(image);
689
- }
690
-
691
- // Convolve
692
- if (shouldConv) {
693
- KeepGainMapUnsupported(baton->keepGainMap, "Convolve");
694
- image = sharp::Convolve(image,
695
- baton->convKernelWidth, baton->convKernelHeight,
696
- baton->convKernelScale, baton->convKernelOffset,
697
- baton->convKernel);
698
- }
699
-
700
- // Recomb
701
- if (!baton->recombMatrix.empty()) {
702
- KeepGainMapUnsupported(baton->keepGainMap, "Recomb");
703
- image = sharp::Recomb(image, baton->recombMatrix);
704
- }
705
-
706
- // Modulate
707
- if (baton->brightness != 1.0 || baton->saturation != 1.0 || baton->hue != 0.0 || baton->lightness != 0.0) {
708
- KeepGainMapUnsupported(baton->keepGainMap, "Modulate");
709
- image = sharp::Modulate(image, baton->brightness, baton->saturation, baton->hue, baton->lightness);
710
- }
711
-
712
- // Sharpen
713
- if (shouldSharpen) {
714
- image = sharp::Sharpen(image, baton->sharpenSigma, baton->sharpenM1, baton->sharpenM2,
715
- baton->sharpenX1, baton->sharpenY2, baton->sharpenY3);
716
- }
717
-
718
- // Reverse premultiplication after all transformations
719
- if (shouldPremultiplyAlpha) {
720
- image = image.unpremultiply().cast(premultiplyFormat);
721
- }
722
- baton->premultiplied = shouldPremultiplyAlpha;
723
-
724
- // Composite
725
- if (shouldComposite) {
726
- KeepGainMapUnsupported(baton->keepGainMap, "Composite");
727
- std::vector<VImage> images = { image };
728
- std::vector<int> modes, xs, ys;
729
- for (Composite *composite : baton->composite) {
730
- VImage compositeImage;
731
- sharp::ImageType compositeImageType = sharp::ImageType::UNKNOWN;
732
- composite->input->access = access;
733
- std::tie(compositeImage, compositeImageType) = sharp::OpenInput(composite->input);
734
-
735
- if (composite->input->autoOrient) {
736
- // Respect EXIF Orientation
737
- VipsAngle compositeAutoRotation = VIPS_ANGLE_D0;
738
- bool compositeAutoFlop = false;
739
- std::tie(compositeAutoRotation, compositeAutoFlop) =
740
- CalculateExifRotationAndFlop(sharp::ExifOrientation(compositeImage));
741
-
742
- compositeImage = sharp::RemoveExifOrientation(compositeImage);
743
- compositeImage = sharp::StaySequential(compositeImage, compositeAutoRotation != VIPS_ANGLE_D0);
744
-
745
- if (compositeAutoRotation != VIPS_ANGLE_D0) {
746
- compositeImage = compositeImage.rot(compositeAutoRotation);
747
- }
748
- if (compositeAutoFlop) {
749
- compositeImage = compositeImage.flip(VIPS_DIRECTION_HORIZONTAL);
750
- }
751
- }
752
-
753
- // Verify within current dimensions
754
- if (compositeImage.width() > image.width() || compositeImage.height() > image.height()) {
755
- throw std::runtime_error("Image to composite must have same dimensions or smaller");
756
- }
757
- // Check if overlay is tiled
758
- if (composite->tile) {
759
- int across = 0;
760
- int down = 0;
761
- // Use gravity in overlay
762
- if (compositeImage.width() <= image.width()) {
763
- across = static_cast<int>(ceil(static_cast<double>(image.width()) / compositeImage.width()));
764
- // Ensure odd number of tiles across when gravity is centre, north or south
765
- if (composite->gravity == 0 || composite->gravity == 1 || composite->gravity == 3) {
766
- across |= 1;
767
- }
768
- }
769
- if (compositeImage.height() <= image.height()) {
770
- down = static_cast<int>(ceil(static_cast<double>(image.height()) / compositeImage.height()));
771
- // Ensure odd number of tiles down when gravity is centre, east or west
772
- if (composite->gravity == 0 || composite->gravity == 2 || composite->gravity == 4) {
773
- down |= 1;
774
- }
775
- }
776
- if (across != 0 || down != 0) {
777
- int left;
778
- int top;
779
- compositeImage = sharp::StaySequential(compositeImage).replicate(across, down);
780
- if (composite->hasOffset) {
781
- std::tie(left, top) = sharp::CalculateCrop(
782
- compositeImage.width(), compositeImage.height(), image.width(), image.height(),
783
- composite->left, composite->top);
784
- } else {
785
- std::tie(left, top) = sharp::CalculateCrop(
786
- compositeImage.width(), compositeImage.height(), image.width(), image.height(), composite->gravity);
787
- }
788
- compositeImage = compositeImage.extract_area(left, top, image.width(), image.height());
789
- }
790
- // gravity was used for extract_area, set it back to its default value of 0
791
- composite->gravity = 0;
792
- }
793
- // Ensure image to composite is with unpremultiplied alpha
794
- compositeImage = sharp::EnsureAlpha(compositeImage, 1);
795
- if (composite->premultiplied) compositeImage = compositeImage.unpremultiply();
796
- // Calculate position
797
- int left;
798
- int top;
799
- if (composite->hasOffset) {
800
- // Composite image at given offsets
801
- if (composite->tile) {
802
- std::tie(left, top) = sharp::CalculateCrop(image.width(), image.height(),
803
- compositeImage.width(), compositeImage.height(), composite->left, composite->top);
804
- } else {
805
- left = composite->left;
806
- top = composite->top;
807
- }
808
- } else {
809
- // Composite image with given gravity
810
- std::tie(left, top) = sharp::CalculateCrop(image.width(), image.height(),
811
- compositeImage.width(), compositeImage.height(), composite->gravity);
812
- }
813
- images.push_back(compositeImage);
814
- modes.push_back(composite->mode);
815
- xs.push_back(left);
816
- ys.push_back(top);
817
- }
818
- image = VImage::composite(images, modes, VImage::option()
819
- ->set("compositing_space", baton->colourspacePipeline == VIPS_INTERPRETATION_LAST
820
- ? VIPS_INTERPRETATION_sRGB
821
- : baton->colourspacePipeline)
822
- ->set("x", xs)
823
- ->set("y", ys));
824
- image = sharp::RemoveGifPalette(image);
825
- }
826
-
827
- // Gamma decoding (brighten)
828
- if (baton->gammaOut >= 1 && baton->gammaOut <= 3) {
829
- image = sharp::Gamma(image, baton->gammaOut);
830
- }
831
-
832
- // Linear adjustment (a * in + b)
833
- if (!baton->linearA.empty()) {
834
- image = sharp::Linear(image, baton->linearA, baton->linearB);
835
- }
836
-
837
- // Apply normalisation - stretch luminance to cover full dynamic range
838
- if (baton->normalise) {
839
- KeepGainMapUnsupported(baton->keepGainMap, "Normalise");
840
- image = sharp::StaySequential(image);
841
- image = sharp::Normalise(image, baton->normaliseLower, baton->normaliseUpper);
842
- }
843
-
844
- // Apply contrast limiting adaptive histogram equalization (CLAHE)
845
- if (baton->claheWidth != 0 && baton->claheHeight != 0) {
846
- KeepGainMapUnsupported(baton->keepGainMap, "Clahe");
847
- image = sharp::StaySequential(image);
848
- image = sharp::Clahe(image, baton->claheWidth, baton->claheHeight, baton->claheMaxSlope);
849
- }
850
-
851
- // Apply bitwise boolean operation between images
852
- if (baton->boolean != nullptr) {
853
- KeepGainMapUnsupported(baton->keepGainMap, "Boolean");
854
- VImage booleanImage;
855
- sharp::ImageType booleanImageType = sharp::ImageType::UNKNOWN;
856
- baton->boolean->access = access;
857
- std::tie(booleanImage, booleanImageType) = sharp::OpenInput(baton->boolean);
858
- booleanImage = sharp::EnsureColourspace(booleanImage, baton->colourspacePipeline);
859
- image = sharp::Boolean(image, booleanImage, baton->booleanOp);
860
- image = sharp::RemoveGifPalette(image);
861
- }
862
-
863
- // Apply per-channel Bandbool bitwise operations after all other operations
864
- if (baton->bandBoolOp >= VIPS_OPERATION_BOOLEAN_AND && baton->bandBoolOp < VIPS_OPERATION_BOOLEAN_LAST) {
865
- image = sharp::Bandbool(image, baton->bandBoolOp);
866
- }
867
-
868
- // Tint the image
869
- if (baton->tint[0] >= 0.0) {
870
- image = sharp::Tint(image, baton->tint);
871
- }
872
-
873
- // Remove alpha channel, if any
874
- if (baton->removeAlpha) {
875
- image = sharp::RemoveAlpha(image);
876
- }
877
-
878
- // Ensure alpha channel, if missing
879
- if (baton->ensureAlpha != -1) {
880
- image = sharp::EnsureAlpha(image, baton->ensureAlpha);
881
- }
882
-
883
- // Ensure output colour space
884
- if (sharp::Is16Bit(image.interpretation())) {
885
- image = image.cast(VIPS_FORMAT_USHORT);
886
- }
887
- if (image.interpretation() != baton->colourspace) {
888
- image = image.colourspace(baton->colourspace, VImage::option()->set("source_space", image.interpretation()));
889
- if (inputProfile.first != nullptr && baton->withIccProfile.empty()) {
890
- image = sharp::SetProfile(image, inputProfile);
891
- }
892
- }
893
-
894
- // Extract channel
895
- if (baton->extractChannel > -1) {
896
- KeepGainMapUnsupported(baton->keepGainMap, "Extract channel");
897
- if (baton->extractChannel >= image.bands()) {
898
- if (baton->extractChannel == 3 && image.has_alpha()) {
899
- baton->extractChannel = image.bands() - 1;
900
- } else {
901
- (baton->err)
902
- .append("Cannot extract channel ").append(std::to_string(baton->extractChannel))
903
- .append(" from image with channels 0-").append(std::to_string(image.bands() - 1));
904
- return Error();
905
- }
906
- }
907
- VipsInterpretation colourspace = sharp::Is16Bit(image.interpretation())
908
- ? VIPS_INTERPRETATION_GREY16
909
- : VIPS_INTERPRETATION_B_W;
910
- image = image
911
- .extract_band(baton->extractChannel)
912
- .copy(VImage::option()->set("interpretation", colourspace));
913
- }
914
-
915
- // Apply output ICC profile
916
- if (!baton->withIccProfile.empty()) {
917
- try {
918
- image = image.icc_transform(const_cast<char*>(baton->withIccProfile.data()), VImage::option()
919
- ->set("input_profile", processingProfile)
920
- ->set("embedded", true)
921
- ->set("depth", sharp::Is16Bit(image.interpretation()) ? 16 : 8)
922
- ->set("intent", VIPS_INTENT_PERCEPTUAL));
923
- } catch(...) {
924
- sharp::VipsWarningCallback(nullptr, G_LOG_LEVEL_WARNING, "Invalid profile", nullptr);
925
- }
926
- }
927
-
928
- // Negate the colours in the image
929
- if (baton->negate) {
930
- image = sharp::Negate(image, baton->negateAlpha);
931
- if (baton->keepGainMap) {
932
- gainMap = sharp::Negate(gainMap, false);
933
- }
934
- }
935
-
936
- // Override EXIF Orientation tag
937
- if (baton->withMetadataOrientation != -1) {
938
- image = sharp::SetExifOrientation(image, baton->withMetadataOrientation);
939
- }
940
- // Override pixel density
941
- if (baton->withMetadataDensity > 0) {
942
- image = sharp::SetDensity(image, baton->withMetadataDensity);
943
- }
944
- // EXIF key/value pairs
945
- if (baton->keepMetadata & VIPS_FOREIGN_KEEP_EXIF) {
946
- image = image.copy();
947
- if (!baton->withExifMerge) {
948
- image = sharp::RemoveExif(image);
949
- }
950
- for (const auto& [key, value] : baton->withExif) {
951
- image.set(key.c_str(), value.c_str());
952
- }
953
- }
954
- // XMP buffer
955
- if ((baton->keepMetadata & VIPS_FOREIGN_KEEP_XMP) && !baton->withXmp.empty()) {
956
- image = image.copy();
957
- image.set(VIPS_META_XMP_NAME, nullptr,
958
- const_cast<void*>(static_cast<void const*>(baton->withXmp.c_str())), baton->withXmp.size());
959
- }
960
- // Number of channels used in output image
961
- baton->channels = image.bands();
962
- baton->width = image.width();
963
- baton->height = image.height();
964
-
965
- image = sharp::SetAnimationProperties(
966
- image, nPages, targetPageHeight, baton->delay, baton->loop);
967
-
968
- if (image.get_typeof(VIPS_META_PAGE_HEIGHT) == G_TYPE_INT) {
969
- baton->pageHeightOut = image.get_int(VIPS_META_PAGE_HEIGHT);
970
- baton->pagesOut = image.get_int(VIPS_META_N_PAGES);
971
- }
972
- baton->hasAlphaOut = image.has_alpha();
973
-
974
- // Output
975
- sharp::SetTimeout(image, baton->timeoutSeconds);
976
- if (baton->fileOut.empty()) {
977
- // Buffer output
978
- if (baton->formatOut == "jpeg" || (baton->formatOut == "input" && inputImageType == sharp::ImageType::JPEG)) {
979
- // Write JPEG to buffer
980
- sharp::AssertImageTypeDimensions(image, sharp::ImageType::JPEG);
981
- VipsArea *area;
982
- if (baton->keepGainMap) {
983
- image = ReattachGainMap(image, gainMap, baton);
984
- area = reinterpret_cast<VipsArea*>(image.uhdrsave_buffer(VImage::option()
985
- ->set("keep", baton->keepMetadata)
986
- ->set("Q", baton->jpegQuality)
987
- ->set("gainmap_scale_factor", gainMapScaleFactor)));
988
- } else {
989
- area = reinterpret_cast<VipsArea*>(image.jpegsave_buffer(VImage::option()
990
- ->set("keep", baton->keepMetadata)
991
- ->set("Q", baton->jpegQuality)
992
- ->set("interlace", baton->jpegProgressive)
993
- ->set("subsample_mode", baton->jpegChromaSubsampling == "4:4:4"
994
- ? VIPS_FOREIGN_SUBSAMPLE_OFF
995
- : VIPS_FOREIGN_SUBSAMPLE_ON)
996
- ->set("trellis_quant", baton->jpegTrellisQuantisation)
997
- ->set("quant_table", baton->jpegQuantisationTable)
998
- ->set("overshoot_deringing", baton->jpegOvershootDeringing)
999
- ->set("optimize_scans", baton->jpegOptimiseScans)
1000
- ->set("optimize_coding", baton->jpegOptimiseCoding)));
1001
- }
1002
- baton->bufferOut = static_cast<char*>(area->data);
1003
- baton->bufferOutLength = area->length;
1004
- area->free_fn = nullptr;
1005
- vips_area_unref(area);
1006
- baton->formatOut = "jpeg";
1007
- if (baton->colourspace == VIPS_INTERPRETATION_CMYK) {
1008
- baton->channels = std::min(baton->channels, 4);
1009
- } else {
1010
- baton->channels = std::min(baton->channels, 3);
1011
- }
1012
- baton->hasAlphaOut = false;
1013
- } else if (baton->formatOut == "jp2" || (baton->formatOut == "input"
1014
- && inputImageType == sharp::ImageType::JP2)) {
1015
- // Write JP2 to Buffer
1016
- sharp::AssertImageTypeDimensions(image, sharp::ImageType::JP2);
1017
- VipsArea *area = reinterpret_cast<VipsArea*>(image.jp2ksave_buffer(VImage::option()
1018
- ->set("Q", baton->jp2Quality)
1019
- ->set("lossless", baton->jp2Lossless)
1020
- ->set("subsample_mode", baton->jp2ChromaSubsampling == "4:4:4"
1021
- ? VIPS_FOREIGN_SUBSAMPLE_OFF : VIPS_FOREIGN_SUBSAMPLE_ON)
1022
- ->set("tile_height", baton->jp2TileHeight)
1023
- ->set("tile_width", baton->jp2TileWidth)));
1024
- baton->bufferOut = static_cast<char*>(area->data);
1025
- baton->bufferOutLength = area->length;
1026
- area->free_fn = nullptr;
1027
- vips_area_unref(area);
1028
- baton->formatOut = "jp2";
1029
- } else if (baton->formatOut == "png" || (baton->formatOut == "input" &&
1030
- (inputImageType == sharp::ImageType::PNG || inputImageType == sharp::ImageType::SVG))) {
1031
- // Write PNG to buffer
1032
- sharp::AssertImageTypeDimensions(image, sharp::ImageType::PNG);
1033
- VipsArea *area = reinterpret_cast<VipsArea*>(image.pngsave_buffer(VImage::option()
1034
- ->set("keep", baton->keepMetadata)
1035
- ->set("interlace", baton->pngProgressive)
1036
- ->set("compression", baton->pngCompressionLevel)
1037
- ->set("filter", baton->pngAdaptiveFiltering ? VIPS_FOREIGN_PNG_FILTER_ALL : VIPS_FOREIGN_PNG_FILTER_NONE)
1038
- ->set("palette", baton->pngPalette)
1039
- ->set("Q", baton->pngQuality)
1040
- ->set("effort", baton->pngEffort)
1041
- ->set("bitdepth", sharp::Is16Bit(image.interpretation()) ? 16 : baton->pngBitdepth)
1042
- ->set("dither", baton->pngDither)));
1043
- baton->bufferOut = static_cast<char*>(area->data);
1044
- baton->bufferOutLength = area->length;
1045
- area->free_fn = nullptr;
1046
- vips_area_unref(area);
1047
- baton->formatOut = "png";
1048
- } else if (baton->formatOut == "webp" ||
1049
- (baton->formatOut == "input" && inputImageType == sharp::ImageType::WEBP)) {
1050
- // Write WEBP to buffer
1051
- sharp::AssertImageTypeDimensions(image, sharp::ImageType::WEBP);
1052
- VipsArea *area = reinterpret_cast<VipsArea*>(image.webpsave_buffer(VImage::option()
1053
- ->set("keep", baton->keepMetadata)
1054
- ->set("Q", baton->webpQuality)
1055
- ->set("lossless", baton->webpLossless)
1056
- ->set("near_lossless", baton->webpNearLossless)
1057
- ->set("smart_subsample", baton->webpSmartSubsample)
1058
- ->set("smart_deblock", baton->webpSmartDeblock)
1059
- ->set("preset", baton->webpPreset)
1060
- ->set("effort", baton->webpEffort)
1061
- ->set("min_size", baton->webpMinSize)
1062
- ->set("mixed", baton->webpMixed)
1063
- ->set("exact", baton->webpExact)
1064
- ->set("alpha_q", baton->webpAlphaQuality)));
1065
- baton->bufferOut = static_cast<char*>(area->data);
1066
- baton->bufferOutLength = area->length;
1067
- area->free_fn = nullptr;
1068
- vips_area_unref(area);
1069
- baton->formatOut = "webp";
1070
- } else if (baton->formatOut == "gif" ||
1071
- (baton->formatOut == "input" && inputImageType == sharp::ImageType::GIF)) {
1072
- // Write GIF to buffer
1073
- sharp::AssertImageTypeDimensions(image, sharp::ImageType::GIF);
1074
- VipsArea *area = reinterpret_cast<VipsArea*>(image.gifsave_buffer(VImage::option()
1075
- ->set("keep", baton->keepMetadata)
1076
- ->set("bitdepth", baton->gifBitdepth)
1077
- ->set("effort", baton->gifEffort)
1078
- ->set("reuse", baton->gifReuse)
1079
- ->set("interlace", baton->gifProgressive)
1080
- ->set("interframe_maxerror", baton->gifInterFrameMaxError)
1081
- ->set("interpalette_maxerror", baton->gifInterPaletteMaxError)
1082
- ->set("keep_duplicate_frames", baton->gifKeepDuplicateFrames)
1083
- ->set("dither", baton->gifDither)));
1084
- baton->bufferOut = static_cast<char*>(area->data);
1085
- baton->bufferOutLength = area->length;
1086
- area->free_fn = nullptr;
1087
- vips_area_unref(area);
1088
- baton->formatOut = "gif";
1089
- } else if (baton->formatOut == "tiff" ||
1090
- (baton->formatOut == "input" && inputImageType == sharp::ImageType::TIFF)) {
1091
- // Write TIFF to buffer
1092
- if (baton->tiffCompression == VIPS_FOREIGN_TIFF_COMPRESSION_JPEG) {
1093
- sharp::AssertImageTypeDimensions(image, sharp::ImageType::JPEG);
1094
- baton->channels = std::min(baton->channels, 3);
1095
- baton->hasAlphaOut = false;
1096
- }
1097
- // Cast pixel values to float, if required
1098
- if (baton->tiffPredictor == VIPS_FOREIGN_TIFF_PREDICTOR_FLOAT) {
1099
- image = image.cast(VIPS_FORMAT_FLOAT);
1100
- }
1101
- VipsArea *area = reinterpret_cast<VipsArea*>(image.tiffsave_buffer(VImage::option()
1102
- ->set("keep", baton->keepMetadata)
1103
- ->set("Q", baton->tiffQuality)
1104
- ->set("bitdepth", baton->tiffBitdepth)
1105
- ->set("compression", baton->tiffCompression)
1106
- ->set("bigtiff", baton->tiffBigtiff)
1107
- ->set("miniswhite", baton->tiffMiniswhite)
1108
- ->set("predictor", baton->tiffPredictor)
1109
- ->set("pyramid", baton->tiffPyramid)
1110
- ->set("tile", baton->tiffTile)
1111
- ->set("tile_height", baton->tiffTileHeight)
1112
- ->set("tile_width", baton->tiffTileWidth)
1113
- ->set("xres", baton->tiffXres)
1114
- ->set("yres", baton->tiffYres)
1115
- ->set("resunit", baton->tiffResolutionUnit)));
1116
- baton->bufferOut = static_cast<char*>(area->data);
1117
- baton->bufferOutLength = area->length;
1118
- area->free_fn = nullptr;
1119
- vips_area_unref(area);
1120
- baton->formatOut = "tiff";
1121
- } else if (baton->formatOut == "heif" ||
1122
- (baton->formatOut == "input" && inputImageType == sharp::ImageType::HEIF)) {
1123
- // Write HEIF to buffer
1124
- sharp::AssertImageTypeDimensions(image, sharp::ImageType::HEIF);
1125
- image = sharp::RemoveAnimationProperties(image);
1126
- VipsArea *area = reinterpret_cast<VipsArea*>(image.heifsave_buffer(VImage::option()
1127
- ->set("keep", baton->keepMetadata)
1128
- ->set("Q", baton->heifQuality)
1129
- ->set("compression", baton->heifCompression)
1130
- ->set("effort", baton->heifEffort)
1131
- ->set("bitdepth", baton->heifBitdepth)
1132
- ->set("tune", baton->heifTune.c_str())
1133
- ->set("subsample_mode", baton->heifChromaSubsampling == "4:4:4"
1134
- ? VIPS_FOREIGN_SUBSAMPLE_OFF : VIPS_FOREIGN_SUBSAMPLE_ON)
1135
- ->set("lossless", baton->heifLossless)));
1136
- baton->bufferOut = static_cast<char*>(area->data);
1137
- baton->bufferOutLength = area->length;
1138
- area->free_fn = nullptr;
1139
- vips_area_unref(area);
1140
- baton->formatOut = "heif";
1141
- } else if (baton->formatOut == "dz") {
1142
- // Write DZ to buffer
1143
- baton->tileContainer = VIPS_FOREIGN_DZ_CONTAINER_ZIP;
1144
- if (!image.has_alpha()) {
1145
- baton->tileBackground.pop_back();
1146
- }
1147
- image = sharp::StaySequential(image, baton->tileAngle != 0);
1148
- vips::VOption *options = BuildOptionsDZ(baton);
1149
- VipsArea *area = reinterpret_cast<VipsArea*>(image.dzsave_buffer(options));
1150
- baton->bufferOut = static_cast<char*>(area->data);
1151
- baton->bufferOutLength = area->length;
1152
- area->free_fn = nullptr;
1153
- vips_area_unref(area);
1154
- baton->formatOut = "dz";
1155
- if (baton->tileFormat == "jpeg") {
1156
- baton->hasAlphaOut = false;
1157
- }
1158
- } else if (baton->formatOut == "jxl" ||
1159
- (baton->formatOut == "input" && inputImageType == sharp::ImageType::JXL)) {
1160
- // Write JXL to buffer
1161
- image = sharp::RemoveAnimationProperties(image);
1162
- VipsArea *area = reinterpret_cast<VipsArea*>(image.jxlsave_buffer(VImage::option()
1163
- ->set("keep", baton->keepMetadata)
1164
- ->set("distance", baton->jxlDistance)
1165
- ->set("tier", baton->jxlDecodingTier)
1166
- ->set("effort", baton->jxlEffort)
1167
- ->set("lossless", baton->jxlLossless)));
1168
- baton->bufferOut = static_cast<char*>(area->data);
1169
- baton->bufferOutLength = area->length;
1170
- area->free_fn = nullptr;
1171
- vips_area_unref(area);
1172
- baton->formatOut = "jxl";
1173
- } else if (baton->formatOut == "raw" ||
1174
- (baton->formatOut == "input" && inputImageType == sharp::ImageType::RAW)) {
1175
- // Write raw, uncompressed image data to buffer
1176
- if (baton->greyscale || image.interpretation() == VIPS_INTERPRETATION_B_W) {
1177
- // Extract first band for greyscale image
1178
- image = image[0];
1179
- baton->channels = 1;
1180
- }
1181
- if (image.format() != baton->rawDepth) {
1182
- // Cast pixels to requested format
1183
- image = image.cast(baton->rawDepth);
1184
- }
1185
- // Get raw image data
1186
- baton->bufferOut = static_cast<char*>(image.write_to_memory(&baton->bufferOutLength));
1187
- if (baton->bufferOut == nullptr) {
1188
- throw std::runtime_error("Could not allocate enough memory for raw output");
1189
- }
1190
- baton->formatOut = "raw";
1191
- } else {
1192
- // Unsupported output format
1193
- auto unsupported = std::string("Unsupported output format ");
1194
- if (baton->formatOut == "input") {
1195
- unsupported.append("when trying to match input format of ");
1196
- unsupported.append(ImageTypeId(inputImageType));
1197
- } else {
1198
- unsupported.append(baton->formatOut);
1199
- }
1200
- throw std::runtime_error(unsupported);
1201
- }
1202
- } else {
1203
- // File output
1204
- bool const isJpeg = sharp::IsJpeg(baton->fileOut);
1205
- bool const isPng = sharp::IsPng(baton->fileOut);
1206
- bool const isWebp = sharp::IsWebp(baton->fileOut);
1207
- bool const isGif = sharp::IsGif(baton->fileOut);
1208
- bool const isTiff = sharp::IsTiff(baton->fileOut);
1209
- bool const isJp2 = sharp::IsJp2(baton->fileOut);
1210
- bool const isHeif = sharp::IsHeif(baton->fileOut);
1211
- bool const isJxl = sharp::IsJxl(baton->fileOut);
1212
- bool const isDz = sharp::IsDz(baton->fileOut);
1213
- bool const isDzZip = sharp::IsDzZip(baton->fileOut);
1214
- bool const isV = sharp::IsV(baton->fileOut);
1215
- bool const mightMatchInput = baton->formatOut == "input";
1216
- bool const willMatchInput = mightMatchInput &&
1217
- !(isJpeg || isPng || isWebp || isGif || isTiff || isJp2 || isHeif || isDz || isDzZip || isV);
1218
-
1219
- if (baton->formatOut == "jpeg" || (mightMatchInput && isJpeg) ||
1220
- (willMatchInput && inputImageType == sharp::ImageType::JPEG)) {
1221
- // Write JPEG to file
1222
- sharp::AssertImageTypeDimensions(image, sharp::ImageType::JPEG);
1223
- if (baton->keepGainMap) {
1224
- image = ReattachGainMap(image, gainMap, baton);
1225
- image.uhdrsave(const_cast<char*>(baton->fileOut.data()), VImage::option()
1226
- ->set("keep", baton->keepMetadata)
1227
- ->set("Q", baton->jpegQuality)
1228
- ->set("gainmap_scale_factor", gainMapScaleFactor));
1229
- } else {
1230
- image.jpegsave(const_cast<char*>(baton->fileOut.data()), VImage::option()
1231
- ->set("keep", baton->keepMetadata)
1232
- ->set("Q", baton->jpegQuality)
1233
- ->set("interlace", baton->jpegProgressive)
1234
- ->set("subsample_mode", baton->jpegChromaSubsampling == "4:4:4"
1235
- ? VIPS_FOREIGN_SUBSAMPLE_OFF
1236
- : VIPS_FOREIGN_SUBSAMPLE_ON)
1237
- ->set("trellis_quant", baton->jpegTrellisQuantisation)
1238
- ->set("quant_table", baton->jpegQuantisationTable)
1239
- ->set("overshoot_deringing", baton->jpegOvershootDeringing)
1240
- ->set("optimize_scans", baton->jpegOptimiseScans)
1241
- ->set("optimize_coding", baton->jpegOptimiseCoding));
1242
- }
1243
- baton->formatOut = "jpeg";
1244
- baton->channels = std::min(baton->channels, 3);
1245
- baton->hasAlphaOut = false;
1246
- } else if (baton->formatOut == "jp2" || (mightMatchInput && isJp2) ||
1247
- (willMatchInput && (inputImageType == sharp::ImageType::JP2))) {
1248
- // Write JP2 to file
1249
- sharp::AssertImageTypeDimensions(image, sharp::ImageType::JP2);
1250
- image.jp2ksave(const_cast<char*>(baton->fileOut.data()), VImage::option()
1251
- ->set("Q", baton->jp2Quality)
1252
- ->set("lossless", baton->jp2Lossless)
1253
- ->set("subsample_mode", baton->jp2ChromaSubsampling == "4:4:4"
1254
- ? VIPS_FOREIGN_SUBSAMPLE_OFF : VIPS_FOREIGN_SUBSAMPLE_ON)
1255
- ->set("tile_height", baton->jp2TileHeight)
1256
- ->set("tile_width", baton->jp2TileWidth));
1257
- baton->formatOut = "jp2";
1258
- } else if (baton->formatOut == "png" || (mightMatchInput && isPng) || (willMatchInput &&
1259
- (inputImageType == sharp::ImageType::PNG || inputImageType == sharp::ImageType::SVG))) {
1260
- // Write PNG to file
1261
- sharp::AssertImageTypeDimensions(image, sharp::ImageType::PNG);
1262
- image.pngsave(const_cast<char*>(baton->fileOut.data()), VImage::option()
1263
- ->set("keep", baton->keepMetadata)
1264
- ->set("interlace", baton->pngProgressive)
1265
- ->set("compression", baton->pngCompressionLevel)
1266
- ->set("filter", baton->pngAdaptiveFiltering ? VIPS_FOREIGN_PNG_FILTER_ALL : VIPS_FOREIGN_PNG_FILTER_NONE)
1267
- ->set("palette", baton->pngPalette)
1268
- ->set("Q", baton->pngQuality)
1269
- ->set("bitdepth", sharp::Is16Bit(image.interpretation()) ? 16 : baton->pngBitdepth)
1270
- ->set("effort", baton->pngEffort)
1271
- ->set("dither", baton->pngDither));
1272
- baton->formatOut = "png";
1273
- } else if (baton->formatOut == "webp" || (mightMatchInput && isWebp) ||
1274
- (willMatchInput && inputImageType == sharp::ImageType::WEBP)) {
1275
- // Write WEBP to file
1276
- sharp::AssertImageTypeDimensions(image, sharp::ImageType::WEBP);
1277
- image.webpsave(const_cast<char*>(baton->fileOut.data()), VImage::option()
1278
- ->set("keep", baton->keepMetadata)
1279
- ->set("Q", baton->webpQuality)
1280
- ->set("lossless", baton->webpLossless)
1281
- ->set("near_lossless", baton->webpNearLossless)
1282
- ->set("smart_subsample", baton->webpSmartSubsample)
1283
- ->set("smart_deblock", baton->webpSmartDeblock)
1284
- ->set("preset", baton->webpPreset)
1285
- ->set("effort", baton->webpEffort)
1286
- ->set("min_size", baton->webpMinSize)
1287
- ->set("mixed", baton->webpMixed)
1288
- ->set("exact", baton->webpExact)
1289
- ->set("alpha_q", baton->webpAlphaQuality));
1290
- baton->formatOut = "webp";
1291
- } else if (baton->formatOut == "gif" || (mightMatchInput && isGif) ||
1292
- (willMatchInput && inputImageType == sharp::ImageType::GIF)) {
1293
- // Write GIF to file
1294
- sharp::AssertImageTypeDimensions(image, sharp::ImageType::GIF);
1295
- image.gifsave(const_cast<char*>(baton->fileOut.data()), VImage::option()
1296
- ->set("keep", baton->keepMetadata)
1297
- ->set("bitdepth", baton->gifBitdepth)
1298
- ->set("effort", baton->gifEffort)
1299
- ->set("reuse", baton->gifReuse)
1300
- ->set("interlace", baton->gifProgressive)
1301
- ->set("interframe_maxerror", baton->gifInterFrameMaxError)
1302
- ->set("interpalette_maxerror", baton->gifInterPaletteMaxError)
1303
- ->set("keep_duplicate_frames", baton->gifKeepDuplicateFrames)
1304
- ->set("dither", baton->gifDither));
1305
- baton->formatOut = "gif";
1306
- } else if (baton->formatOut == "tiff" || (mightMatchInput && isTiff) ||
1307
- (willMatchInput && inputImageType == sharp::ImageType::TIFF)) {
1308
- // Write TIFF to file
1309
- if (baton->tiffCompression == VIPS_FOREIGN_TIFF_COMPRESSION_JPEG) {
1310
- sharp::AssertImageTypeDimensions(image, sharp::ImageType::JPEG);
1311
- baton->channels = std::min(baton->channels, 3);
1312
- baton->hasAlphaOut = false;
1313
- }
1314
- // Cast pixel values to float, if required
1315
- if (baton->tiffPredictor == VIPS_FOREIGN_TIFF_PREDICTOR_FLOAT) {
1316
- image = image.cast(VIPS_FORMAT_FLOAT);
1317
- }
1318
- image.tiffsave(const_cast<char*>(baton->fileOut.data()), VImage::option()
1319
- ->set("keep", baton->keepMetadata)
1320
- ->set("Q", baton->tiffQuality)
1321
- ->set("bitdepth", baton->tiffBitdepth)
1322
- ->set("compression", baton->tiffCompression)
1323
- ->set("bigtiff", baton->tiffBigtiff)
1324
- ->set("miniswhite", baton->tiffMiniswhite)
1325
- ->set("predictor", baton->tiffPredictor)
1326
- ->set("pyramid", baton->tiffPyramid)
1327
- ->set("tile", baton->tiffTile)
1328
- ->set("tile_height", baton->tiffTileHeight)
1329
- ->set("tile_width", baton->tiffTileWidth)
1330
- ->set("xres", baton->tiffXres)
1331
- ->set("yres", baton->tiffYres)
1332
- ->set("resunit", baton->tiffResolutionUnit));
1333
- baton->formatOut = "tiff";
1334
- } else if (baton->formatOut == "heif" || (mightMatchInput && isHeif) ||
1335
- (willMatchInput && inputImageType == sharp::ImageType::HEIF)) {
1336
- // Write HEIF to file
1337
- sharp::AssertImageTypeDimensions(image, sharp::ImageType::HEIF);
1338
- image = sharp::RemoveAnimationProperties(image);
1339
- image.heifsave(const_cast<char*>(baton->fileOut.data()), VImage::option()
1340
- ->set("keep", baton->keepMetadata)
1341
- ->set("Q", baton->heifQuality)
1342
- ->set("compression", baton->heifCompression)
1343
- ->set("effort", baton->heifEffort)
1344
- ->set("bitdepth", baton->heifBitdepth)
1345
- ->set("tune", baton->heifTune.c_str())
1346
- ->set("subsample_mode", baton->heifChromaSubsampling == "4:4:4"
1347
- ? VIPS_FOREIGN_SUBSAMPLE_OFF : VIPS_FOREIGN_SUBSAMPLE_ON)
1348
- ->set("lossless", baton->heifLossless));
1349
- baton->formatOut = "heif";
1350
- } else if (baton->formatOut == "jxl" || (mightMatchInput && isJxl) ||
1351
- (willMatchInput && inputImageType == sharp::ImageType::JXL)) {
1352
- // Write JXL to file
1353
- image = sharp::RemoveAnimationProperties(image);
1354
- image.jxlsave(const_cast<char*>(baton->fileOut.data()), VImage::option()
1355
- ->set("keep", baton->keepMetadata)
1356
- ->set("distance", baton->jxlDistance)
1357
- ->set("tier", baton->jxlDecodingTier)
1358
- ->set("effort", baton->jxlEffort)
1359
- ->set("lossless", baton->jxlLossless));
1360
- baton->formatOut = "jxl";
1361
- } else if (baton->formatOut == "dz" || isDz || isDzZip) {
1362
- // Write DZ to file
1363
- if (isDzZip) {
1364
- baton->tileContainer = VIPS_FOREIGN_DZ_CONTAINER_ZIP;
1365
- }
1366
- if (!image.has_alpha()) {
1367
- baton->tileBackground.pop_back();
1368
- }
1369
- image = sharp::StaySequential(image, baton->tileAngle != 0);
1370
- vips::VOption *options = BuildOptionsDZ(baton);
1371
- image.dzsave(const_cast<char*>(baton->fileOut.data()), options);
1372
- baton->formatOut = "dz";
1373
- if (baton->tileFormat == "jpeg") {
1374
- baton->hasAlphaOut = false;
1375
- }
1376
- } else if (baton->formatOut == "v" || (mightMatchInput && isV) ||
1377
- (willMatchInput && inputImageType == sharp::ImageType::VIPS)) {
1378
- // Write V to file
1379
- image.vipssave(const_cast<char*>(baton->fileOut.data()), VImage::option()
1380
- ->set("keep", baton->keepMetadata));
1381
- baton->formatOut = "v";
1382
- } else {
1383
- // Unsupported output format
1384
- (baton->err).append("Unsupported output format " + baton->fileOut);
1385
- return Error();
1386
- }
1387
- }
1388
- } catch (std::runtime_error const &err) {
1389
- char const *what = err.what();
1390
- if (what && what[0]) {
1391
- (baton->err).append(what);
1392
- } else {
1393
- if (baton->input->failOn == VIPS_FAIL_ON_WARNING) {
1394
- (baton->err).append("Warning treated as error due to failOn setting");
1395
- baton->errUseWarning = true;
1396
- } else {
1397
- (baton->err).append("Unknown error");
1398
- }
1399
- }
1400
- }
1401
- // Clean up libvips' per-request data and threads
1402
- vips_error_clear();
1403
- vips_thread_shutdown();
1404
- }
1405
-
1406
- void OnOK() {
1407
- Napi::Env env = Env();
1408
- Napi::HandleScope scope(env);
1409
-
1410
- // Handle warnings
1411
- std::string warning = sharp::VipsWarningPop();
1412
- while (!warning.empty()) {
1413
- if (baton->errUseWarning) {
1414
- (baton->err).append("\n").append(warning);
1415
- } else {
1416
- debuglog.SHARP_CALLBACK_FN_NAME(Receiver().Value(), { Napi::String::New(env, warning) });
1417
- }
1418
- warning = sharp::VipsWarningPop();
1419
- }
1420
- if (baton->err.empty()) {
1421
- int width = baton->width;
1422
- int height = baton->height;
1423
- if (baton->topOffsetPre != -1 && (baton->width == -1 || baton->height == -1)) {
1424
- width = baton->widthPre;
1425
- height = baton->heightPre;
1426
- }
1427
- if (baton->topOffsetPost != -1) {
1428
- width = baton->widthPost;
1429
- height = baton->heightPost;
1430
- }
1431
- // Info Object
1432
- Napi::Object info = Napi::Object::New(env);
1433
- info.Set("format", baton->formatOut);
1434
- info.Set("width", static_cast<uint32_t>(width));
1435
- info.Set("height", static_cast<uint32_t>(height));
1436
- info.Set("channels", static_cast<uint32_t>(baton->channels));
1437
- if (baton->formatOut == "raw") {
1438
- info.Set("depth", vips_enum_nick(VIPS_TYPE_BAND_FORMAT, baton->rawDepth));
1439
- }
1440
- info.Set("premultiplied", baton->premultiplied);
1441
- if (baton->hasCropOffset) {
1442
- info.Set("cropOffsetLeft", static_cast<int32_t>(baton->cropOffsetLeft));
1443
- info.Set("cropOffsetTop", static_cast<int32_t>(baton->cropOffsetTop));
1444
- }
1445
- if (baton->hasAttentionCenter) {
1446
- info.Set("attentionX", static_cast<int32_t>(baton->attentionX));
1447
- info.Set("attentionY", static_cast<int32_t>(baton->attentionY));
1448
- }
1449
- if (baton->trimThreshold >= 0.0) {
1450
- info.Set("trimOffsetLeft", static_cast<int32_t>(baton->trimOffsetLeft));
1451
- info.Set("trimOffsetTop", static_cast<int32_t>(baton->trimOffsetTop));
1452
- }
1453
- if (baton->input->textAutofitDpi) {
1454
- info.Set("textAutofitDpi", static_cast<uint32_t>(baton->input->textAutofitDpi));
1455
- }
1456
- if (baton->pageHeightOut) {
1457
- info.Set("pageHeight", static_cast<int32_t>(baton->pageHeightOut));
1458
- info.Set("pages", static_cast<int32_t>(baton->pagesOut));
1459
- }
1460
- info.Set("hasAlpha", baton->hasAlphaOut);
1461
-
1462
- if (baton->bufferOutLength > 0) {
1463
- info.Set("size", static_cast<uint32_t>(baton->bufferOutLength));
1464
- if (baton->typedArrayOut) {
1465
- // ECMAScript ArrayBuffer with Uint8Array view
1466
- Napi::TypedArrayOf<uint8_t> data = Napi::Buffer<char>::Copy(env,
1467
- static_cast<char*>(baton->bufferOut), baton->bufferOutLength);
1468
- sharp::FreeCallback(static_cast<char*>(baton->bufferOut), nullptr);
1469
- Callback().SHARP_CALLBACK_FN_NAME(Receiver().Value(), { env.Null(), data, info });
1470
- } else {
1471
- // Node.js Buffer
1472
- Napi::Buffer<char> data = Napi::Buffer<char>::NewOrCopy(env, static_cast<char*>(baton->bufferOut),
1473
- baton->bufferOutLength, sharp::FreeCallback);
1474
- Callback().SHARP_CALLBACK_FN_NAME(Receiver().Value(), { env.Null(), data, info });
1475
- }
1476
- } else {
1477
- // Add file size to info
1478
- if (baton->formatOut != "dz" || sharp::IsDzZip(baton->fileOut)) {
1479
- try {
1480
- uint32_t const size = static_cast<uint32_t>(
1481
- std::filesystem::file_size(std::filesystem::u8path(baton->fileOut)));
1482
- info.Set("size", size);
1483
- } catch (...) {}
1484
- }
1485
- Callback().SHARP_CALLBACK_FN_NAME(Receiver().Value(), { env.Null(), info });
1486
- }
1487
- } else {
1488
- Callback().SHARP_CALLBACK_FN_NAME(Receiver().Value(),
1489
- { Napi::Error::New(env, sharp::TrimEnd(baton->err)).Value() });
1490
- }
1491
-
1492
- // Delete baton
1493
- delete baton->input;
1494
- delete baton->boolean;
1495
- for (Composite *composite : baton->composite) {
1496
- delete composite->input;
1497
- delete composite;
1498
- }
1499
- for (sharp::InputDescriptor *input : baton->joinChannelIn) {
1500
- delete input;
1501
- }
1502
- for (sharp::InputDescriptor *input : baton->join) {
1503
- delete input;
1504
- }
1505
- delete baton;
1506
-
1507
- // Decrement processing task counter
1508
- sharp::counterProcess--;
1509
- Napi::Number queueLength = Napi::Number::New(env, static_cast<int>(sharp::counterQueue));
1510
- queueListener.SHARP_CALLBACK_FN_NAME(Receiver().Value(), { queueLength });
1511
- }
1512
-
1513
- private:
1514
- PipelineBaton *baton;
1515
- Napi::FunctionReference debuglog;
1516
- Napi::FunctionReference queueListener;
1517
-
1518
- void MultiPageUnsupported(int const pages, std::string op) {
1519
- if (pages > 1) {
1520
- throw std::runtime_error(op + " is not supported for multi-page images");
1521
- }
1522
- }
1523
-
1524
- void KeepGainMapUnsupported(bool const keepGainMap, std::string op) {
1525
- if (keepGainMap) {
1526
- throw std::runtime_error(op + " is not supported when keeping gain maps");
1527
- }
1528
- }
1529
-
1530
- /*
1531
- Calculate the angle of rotation and need-to-flip for the given Exif orientation
1532
- By default, returns zero, i.e. no rotation.
1533
- */
1534
- std::tuple<VipsAngle, bool>
1535
- CalculateExifRotationAndFlop(int const exifOrientation) {
1536
- VipsAngle rotate = VIPS_ANGLE_D0;
1537
- bool flop = false;
1538
- switch (exifOrientation) {
1539
- case 6: rotate = VIPS_ANGLE_D90; break;
1540
- case 3: rotate = VIPS_ANGLE_D180; break;
1541
- case 8: rotate = VIPS_ANGLE_D270; break;
1542
- case 2: flop = true; break;
1543
- case 7: flop = true; rotate = VIPS_ANGLE_D270; break;
1544
- case 4: flop = true; rotate = VIPS_ANGLE_D180; break;
1545
- case 5: flop = true; rotate = VIPS_ANGLE_D90; break;
1546
- }
1547
- return std::make_tuple(rotate, flop);
1548
- }
1549
-
1550
- /*
1551
- Calculate the rotation for the given angle.
1552
- Supports any positive or negative angle that is a multiple of 90.
1553
- */
1554
- VipsAngle
1555
- CalculateAngleRotation(int angle) {
1556
- angle = angle % 360;
1557
- if (angle < 0)
1558
- angle = 360 + angle;
1559
- switch (angle) {
1560
- case 90: return VIPS_ANGLE_D90;
1561
- case 180: return VIPS_ANGLE_D180;
1562
- case 270: return VIPS_ANGLE_D270;
1563
- }
1564
- return VIPS_ANGLE_D0;
1565
- }
1566
-
1567
- /*
1568
- Assemble the suffix argument to dzsave, which is the format (by extname)
1569
- alongside comma-separated arguments to the corresponding `formatsave` vips
1570
- action.
1571
- */
1572
- std::string
1573
- AssembleSuffixString(std::string extname, std::vector<std::pair<std::string, std::string>> options) {
1574
- std::string argument;
1575
- for (const auto& [key, value] : options) {
1576
- if (!argument.empty()) {
1577
- argument += ",";
1578
- }
1579
- argument += key + "=" + value;
1580
- }
1581
- return extname + "[" + argument + "]";
1582
- }
1583
-
1584
- /*
1585
- Build VOption for dzsave
1586
- */
1587
- vips::VOption*
1588
- BuildOptionsDZ(PipelineBaton *baton) {
1589
- // Forward format options through suffix
1590
- std::string suffix;
1591
- if (baton->tileFormat == "png") {
1592
- std::vector<std::pair<std::string, std::string>> options {
1593
- {"interlace", baton->pngProgressive ? "true" : "false"},
1594
- {"compression", std::to_string(baton->pngCompressionLevel)},
1595
- {"filter", baton->pngAdaptiveFiltering ? "all" : "none"}
1596
- };
1597
- suffix = AssembleSuffixString(".png", options);
1598
- } else if (baton->tileFormat == "webp") {
1599
- std::vector<std::pair<std::string, std::string>> options {
1600
- {"Q", std::to_string(baton->webpQuality)},
1601
- {"alpha_q", std::to_string(baton->webpAlphaQuality)},
1602
- {"lossless", baton->webpLossless ? "true" : "false"},
1603
- {"near_lossless", baton->webpNearLossless ? "true" : "false"},
1604
- {"smart_subsample", baton->webpSmartSubsample ? "true" : "false"},
1605
- {"smart_deblock", baton->webpSmartDeblock ? "true" : "false"},
1606
- {"preset", vips_enum_nick(VIPS_TYPE_FOREIGN_WEBP_PRESET, baton->webpPreset)},
1607
- {"min_size", baton->webpMinSize ? "true" : "false"},
1608
- {"mixed", baton->webpMixed ? "true" : "false"},
1609
- {"exact", baton->webpExact ? "true" : "false"},
1610
- {"effort", std::to_string(baton->webpEffort)}
1611
- };
1612
- suffix = AssembleSuffixString(".webp", options);
1613
- } else {
1614
- std::vector<std::pair<std::string, std::string>> options {
1615
- {"Q", std::to_string(baton->jpegQuality)},
1616
- {"interlace", baton->jpegProgressive ? "true" : "false"},
1617
- {"subsample_mode", baton->jpegChromaSubsampling == "4:4:4" ? "off" : "on"},
1618
- {"trellis_quant", baton->jpegTrellisQuantisation ? "true" : "false"},
1619
- {"quant_table", std::to_string(baton->jpegQuantisationTable)},
1620
- {"overshoot_deringing", baton->jpegOvershootDeringing ? "true": "false"},
1621
- {"optimize_scans", baton->jpegOptimiseScans ? "true": "false"},
1622
- {"optimize_coding", baton->jpegOptimiseCoding ? "true": "false"}
1623
- };
1624
- std::string extname = baton->tileLayout == VIPS_FOREIGN_DZ_LAYOUT_DZ ? ".jpeg" : ".jpg";
1625
- suffix = AssembleSuffixString(extname, options);
1626
- }
1627
- vips::VOption *options = VImage::option()
1628
- ->set("keep", baton->keepMetadata)
1629
- ->set("tile_size", baton->tileSize)
1630
- ->set("overlap", baton->tileOverlap)
1631
- ->set("container", baton->tileContainer)
1632
- ->set("layout", baton->tileLayout)
1633
- ->set("suffix", const_cast<char*>(suffix.data()))
1634
- ->set("angle", CalculateAngleRotation(baton->tileAngle))
1635
- ->set("background", baton->tileBackground)
1636
- ->set("centre", baton->tileCentre)
1637
- ->set("id", const_cast<char*>(baton->tileId.data()))
1638
- ->set("skip_blanks", baton->tileSkipBlanks);
1639
- if (baton->tileDepth < VIPS_FOREIGN_DZ_DEPTH_LAST) {
1640
- options->set("depth", baton->tileDepth);
1641
- }
1642
- if (!baton->tileBasename.empty()) {
1643
- options->set("basename", const_cast<char*>(baton->tileBasename.data()));
1644
- }
1645
- return options;
1646
- }
1647
-
1648
- VImage ReattachGainMap(VImage image, VImage gainMap, PipelineBaton *baton) {
1649
- VipsArea *gainMapJpeg = reinterpret_cast<VipsArea*>(gainMap.jpegsave_buffer(VImage::option()
1650
- ->set("keep", FALSE)
1651
- ->set("Q", baton->jpegQuality)
1652
- ->set("subsample_mode", VIPS_FOREIGN_SUBSAMPLE_OFF)
1653
- ->set("trellis_quant", baton->jpegTrellisQuantisation)
1654
- ->set("quant_table", baton->jpegQuantisationTable)
1655
- ->set("overshoot_deringing", baton->jpegOvershootDeringing)
1656
- ->set("optimize_coding", baton->jpegOptimiseCoding)));
1657
- image = image.copy();
1658
- image.set("gainmap-data", reinterpret_cast<VipsCallbackFn>(vips_area_free_cb),
1659
- gainMapJpeg->data, gainMapJpeg->length);
1660
- return image;
1661
- }
1662
-
1663
- /*
1664
- Clear all thread-local data.
1665
- */
1666
- void Error() {
1667
- // Clean up libvips' per-request data and threads
1668
- vips_error_clear();
1669
- vips_thread_shutdown();
1670
- }
1671
- };
1672
-
1673
- /*
1674
- pipeline(options, output, callback)
1675
- */
1676
- Napi::Value pipeline(const Napi::CallbackInfo& info) {
1677
- // V8 objects are converted to non-V8 types held in the baton struct
1678
- PipelineBaton *baton = new PipelineBaton;
1679
- Napi::Object options = info[size_t(0)].As<Napi::Object>();
1680
-
1681
- // Input
1682
- baton->input = sharp::CreateInputDescriptor(options.Get("input").As<Napi::Object>());
1683
- // Join images together
1684
- if (sharp::HasAttr(options, "join")) {
1685
- Napi::Array join = options.Get("join").As<Napi::Array>();
1686
- for (unsigned int i = 0; i < join.Length(); i++) {
1687
- baton->join.push_back(
1688
- sharp::CreateInputDescriptor(join.Get(i).As<Napi::Object>()));
1689
- }
1690
- }
1691
- // Extract image options
1692
- baton->topOffsetPre = sharp::AttrAsInt32(options, "topOffsetPre");
1693
- baton->leftOffsetPre = sharp::AttrAsInt32(options, "leftOffsetPre");
1694
- baton->widthPre = sharp::AttrAsInt32(options, "widthPre");
1695
- baton->heightPre = sharp::AttrAsInt32(options, "heightPre");
1696
- baton->topOffsetPost = sharp::AttrAsInt32(options, "topOffsetPost");
1697
- baton->leftOffsetPost = sharp::AttrAsInt32(options, "leftOffsetPost");
1698
- baton->widthPost = sharp::AttrAsInt32(options, "widthPost");
1699
- baton->heightPost = sharp::AttrAsInt32(options, "heightPost");
1700
- // Output image dimensions
1701
- baton->width = sharp::AttrAsInt32(options, "width");
1702
- baton->height = sharp::AttrAsInt32(options, "height");
1703
- // Canvas option
1704
- std::string canvas = sharp::AttrAsStr(options, "canvas");
1705
- if (canvas == "crop") {
1706
- baton->canvas = sharp::Canvas::CROP;
1707
- } else if (canvas == "embed") {
1708
- baton->canvas = sharp::Canvas::EMBED;
1709
- } else if (canvas == "max") {
1710
- baton->canvas = sharp::Canvas::MAX;
1711
- } else if (canvas == "min") {
1712
- baton->canvas = sharp::Canvas::MIN;
1713
- } else if (canvas == "ignore_aspect") {
1714
- baton->canvas = sharp::Canvas::IGNORE_ASPECT;
1715
- }
1716
- // Composite
1717
- Napi::Array compositeArray = options.Get("composite").As<Napi::Array>();
1718
- for (unsigned int i = 0; i < compositeArray.Length(); i++) {
1719
- Napi::Object compositeObject = compositeArray.Get(i).As<Napi::Object>();
1720
- Composite *composite = new Composite;
1721
- composite->input = sharp::CreateInputDescriptor(compositeObject.Get("input").As<Napi::Object>());
1722
- composite->mode = sharp::AttrAsEnum<VipsBlendMode>(compositeObject, "blend", VIPS_TYPE_BLEND_MODE);
1723
- composite->gravity = sharp::AttrAsUint32(compositeObject, "gravity");
1724
- composite->left = sharp::AttrAsInt32(compositeObject, "left");
1725
- composite->top = sharp::AttrAsInt32(compositeObject, "top");
1726
- composite->hasOffset = sharp::AttrAsBool(compositeObject, "hasOffset");
1727
- composite->tile = sharp::AttrAsBool(compositeObject, "tile");
1728
- composite->premultiplied = sharp::AttrAsBool(compositeObject, "premultiplied");
1729
- baton->composite.push_back(composite);
1730
- }
1731
- // Resize options
1732
- baton->withoutEnlargement = sharp::AttrAsBool(options, "withoutEnlargement");
1733
- baton->withoutReduction = sharp::AttrAsBool(options, "withoutReduction");
1734
- baton->position = sharp::AttrAsInt32(options, "position");
1735
- baton->resizeBackground = sharp::AttrAsVectorOfDouble(options, "resizeBackground");
1736
- baton->kernel = sharp::AttrAsEnum<VipsKernel>(options, "kernel", VIPS_TYPE_KERNEL);
1737
- baton->fastShrinkOnLoad = sharp::AttrAsBool(options, "fastShrinkOnLoad");
1738
- // Join Channel Options
1739
- if (options.Has("joinChannelIn")) {
1740
- Napi::Array joinChannelArray = options.Get("joinChannelIn").As<Napi::Array>();
1741
- for (unsigned int i = 0; i < joinChannelArray.Length(); i++) {
1742
- baton->joinChannelIn.push_back(
1743
- sharp::CreateInputDescriptor(joinChannelArray.Get(i).As<Napi::Object>()));
1744
- }
1745
- }
1746
- // Operators
1747
- baton->flatten = sharp::AttrAsBool(options, "flatten");
1748
- baton->flattenBackground = sharp::AttrAsVectorOfDouble(options, "flattenBackground");
1749
- baton->unflatten = sharp::AttrAsBool(options, "unflatten");
1750
- baton->negate = sharp::AttrAsBool(options, "negate");
1751
- baton->negateAlpha = sharp::AttrAsBool(options, "negateAlpha");
1752
- baton->blurSigma = sharp::AttrAsDouble(options, "blurSigma");
1753
- baton->precision = sharp::AttrAsEnum<VipsPrecision>(options, "precision", VIPS_TYPE_PRECISION);
1754
- baton->minAmpl = sharp::AttrAsDouble(options, "minAmpl");
1755
- baton->brightness = sharp::AttrAsDouble(options, "brightness");
1756
- baton->saturation = sharp::AttrAsDouble(options, "saturation");
1757
- baton->hue = sharp::AttrAsInt32(options, "hue");
1758
- baton->lightness = sharp::AttrAsDouble(options, "lightness");
1759
- baton->medianSize = sharp::AttrAsUint32(options, "medianSize");
1760
- baton->sharpenSigma = sharp::AttrAsDouble(options, "sharpenSigma");
1761
- baton->sharpenM1 = sharp::AttrAsDouble(options, "sharpenM1");
1762
- baton->sharpenM2 = sharp::AttrAsDouble(options, "sharpenM2");
1763
- baton->sharpenX1 = sharp::AttrAsDouble(options, "sharpenX1");
1764
- baton->sharpenY2 = sharp::AttrAsDouble(options, "sharpenY2");
1765
- baton->sharpenY3 = sharp::AttrAsDouble(options, "sharpenY3");
1766
- baton->threshold = sharp::AttrAsInt32(options, "threshold");
1767
- baton->thresholdGrayscale = sharp::AttrAsBool(options, "thresholdGrayscale");
1768
- baton->trimBackground = sharp::AttrAsVectorOfDouble(options, "trimBackground");
1769
- baton->trimThreshold = sharp::AttrAsDouble(options, "trimThreshold");
1770
- baton->trimLineArt = sharp::AttrAsBool(options, "trimLineArt");
1771
- baton->trimMargin = sharp::AttrAsUint32(options, "trimMargin");
1772
- baton->gamma = sharp::AttrAsDouble(options, "gamma");
1773
- baton->gammaOut = sharp::AttrAsDouble(options, "gammaOut");
1774
- baton->linearA = sharp::AttrAsVectorOfDouble(options, "linearA");
1775
- baton->linearB = sharp::AttrAsVectorOfDouble(options, "linearB");
1776
- baton->dilateWidth = sharp::AttrAsUint32(options, "dilateWidth");
1777
- baton->erodeWidth = sharp::AttrAsUint32(options, "erodeWidth");
1778
- baton->greyscale = sharp::AttrAsBool(options, "greyscale");
1779
- baton->normalise = sharp::AttrAsBool(options, "normalise");
1780
- baton->normaliseLower = sharp::AttrAsUint32(options, "normaliseLower");
1781
- baton->normaliseUpper = sharp::AttrAsUint32(options, "normaliseUpper");
1782
- baton->tint = sharp::AttrAsVectorOfDouble(options, "tint");
1783
- baton->claheWidth = sharp::AttrAsUint32(options, "claheWidth");
1784
- baton->claheHeight = sharp::AttrAsUint32(options, "claheHeight");
1785
- baton->claheMaxSlope = sharp::AttrAsUint32(options, "claheMaxSlope");
1786
- baton->angle = sharp::AttrAsInt32(options, "angle");
1787
- baton->rotationAngle = sharp::AttrAsDouble(options, "rotationAngle");
1788
- baton->rotationBackground = sharp::AttrAsVectorOfDouble(options, "rotationBackground");
1789
- baton->rotateBefore = sharp::AttrAsBool(options, "rotateBefore");
1790
- baton->orientBefore = sharp::AttrAsBool(options, "orientBefore");
1791
- baton->flip = sharp::AttrAsBool(options, "flip");
1792
- baton->flop = sharp::AttrAsBool(options, "flop");
1793
- baton->extendTop = sharp::AttrAsInt32(options, "extendTop");
1794
- baton->extendBottom = sharp::AttrAsInt32(options, "extendBottom");
1795
- baton->extendLeft = sharp::AttrAsInt32(options, "extendLeft");
1796
- baton->extendRight = sharp::AttrAsInt32(options, "extendRight");
1797
- baton->extendBackground = sharp::AttrAsVectorOfDouble(options, "extendBackground");
1798
- baton->extendWith = sharp::AttrAsEnum<VipsExtend>(options, "extendWith", VIPS_TYPE_EXTEND);
1799
- baton->extractChannel = sharp::AttrAsInt32(options, "extractChannel");
1800
- baton->affineMatrix = sharp::AttrAsVectorOfDouble(options, "affineMatrix");
1801
- baton->affineBackground = sharp::AttrAsVectorOfDouble(options, "affineBackground");
1802
- baton->affineIdx = sharp::AttrAsDouble(options, "affineIdx");
1803
- baton->affineIdy = sharp::AttrAsDouble(options, "affineIdy");
1804
- baton->affineOdx = sharp::AttrAsDouble(options, "affineOdx");
1805
- baton->affineOdy = sharp::AttrAsDouble(options, "affineOdy");
1806
- baton->affineInterpolator = sharp::AttrAsStr(options, "affineInterpolator");
1807
- baton->removeAlpha = sharp::AttrAsBool(options, "removeAlpha");
1808
- baton->ensureAlpha = sharp::AttrAsDouble(options, "ensureAlpha");
1809
- if (options.Has("boolean")) {
1810
- baton->boolean = sharp::CreateInputDescriptor(options.Get("boolean").As<Napi::Object>());
1811
- baton->booleanOp = sharp::AttrAsEnum<VipsOperationBoolean>(options, "booleanOp", VIPS_TYPE_OPERATION_BOOLEAN);
1812
- }
1813
- if (options.Has("bandBoolOp")) {
1814
- baton->bandBoolOp = sharp::AttrAsEnum<VipsOperationBoolean>(options, "bandBoolOp", VIPS_TYPE_OPERATION_BOOLEAN);
1815
- }
1816
- if (options.Has("convKernel")) {
1817
- Napi::Object kernel = options.Get("convKernel").As<Napi::Object>();
1818
- baton->convKernelWidth = sharp::AttrAsUint32(kernel, "width");
1819
- baton->convKernelHeight = sharp::AttrAsUint32(kernel, "height");
1820
- baton->convKernelScale = sharp::AttrAsDouble(kernel, "scale");
1821
- baton->convKernelOffset = sharp::AttrAsDouble(kernel, "offset");
1822
- size_t const kernelSize = static_cast<size_t>(baton->convKernelWidth * baton->convKernelHeight);
1823
- baton->convKernel.resize(kernelSize);
1824
- Napi::Array kdata = kernel.Get("kernel").As<Napi::Array>();
1825
- for (unsigned int i = 0; i < kernelSize; i++) {
1826
- baton->convKernel[i] = sharp::AttrAsDouble(kdata, i);
1827
- }
1828
- }
1829
- if (options.Has("recombMatrix")) {
1830
- Napi::Array recombMatrix = options.Get("recombMatrix").As<Napi::Array>();
1831
- unsigned int matrixElements = recombMatrix.Length();
1832
- baton->recombMatrix.resize(matrixElements);
1833
- for (unsigned int i = 0; i < matrixElements; i++) {
1834
- baton->recombMatrix[i] = sharp::AttrAsDouble(recombMatrix, i);
1835
- }
1836
- }
1837
- baton->colourspacePipeline = sharp::AttrAsEnum<VipsInterpretation>(
1838
- options, "colourspacePipeline", VIPS_TYPE_INTERPRETATION);
1839
- if (baton->colourspacePipeline == VIPS_INTERPRETATION_ERROR) {
1840
- baton->colourspacePipeline = VIPS_INTERPRETATION_LAST;
1841
- }
1842
- baton->colourspace = sharp::AttrAsEnum<VipsInterpretation>(options, "colourspace", VIPS_TYPE_INTERPRETATION);
1843
- if (baton->colourspace == VIPS_INTERPRETATION_ERROR) {
1844
- baton->colourspace = VIPS_INTERPRETATION_sRGB;
1845
- }
1846
- // Output
1847
- baton->formatOut = sharp::AttrAsStr(options, "formatOut");
1848
- baton->fileOut = sharp::AttrAsStr(options, "fileOut");
1849
- baton->typedArrayOut = sharp::AttrAsBool(options, "typedArrayOut");
1850
- baton->keepMetadata = sharp::AttrAsUint32(options, "keepMetadata");
1851
- baton->withMetadataOrientation = sharp::AttrAsUint32(options, "withMetadataOrientation");
1852
- baton->withMetadataDensity = sharp::AttrAsDouble(options, "withMetadataDensity");
1853
- baton->withIccProfile = sharp::AttrAsStr(options, "withIccProfile");
1854
- Napi::Object withExif = options.Get("withExif").As<Napi::Object>();
1855
- Napi::Array withExifKeys = withExif.GetPropertyNames();
1856
- for (unsigned int i = 0; i < withExifKeys.Length(); i++) {
1857
- std::string k = sharp::AttrAsStr(withExifKeys, i);
1858
- if (withExif.HasOwnProperty(k)) {
1859
- baton->withExif.insert(std::make_pair(k, sharp::AttrAsStr(withExif, k)));
1860
- }
1861
- }
1862
- baton->withExifMerge = sharp::AttrAsBool(options, "withExifMerge");
1863
- baton->withXmp = sharp::AttrAsStr(options, "withXmp");
1864
- baton->keepGainMap = sharp::AttrAsBool(options, "keepGainMap");
1865
- baton->withGainMap = sharp::AttrAsBool(options, "withGainMap");
1866
- baton->timeoutSeconds = sharp::AttrAsUint32(options, "timeoutSeconds");
1867
- baton->loop = sharp::AttrAsUint32(options, "loop");
1868
- baton->delay = sharp::AttrAsInt32Vector(options, "delay");
1869
- // Format-specific
1870
- baton->jpegQuality = sharp::AttrAsUint32(options, "jpegQuality");
1871
- baton->jpegProgressive = sharp::AttrAsBool(options, "jpegProgressive");
1872
- baton->jpegChromaSubsampling = sharp::AttrAsStr(options, "jpegChromaSubsampling");
1873
- baton->jpegTrellisQuantisation = sharp::AttrAsBool(options, "jpegTrellisQuantisation");
1874
- baton->jpegQuantisationTable = sharp::AttrAsUint32(options, "jpegQuantisationTable");
1875
- baton->jpegOvershootDeringing = sharp::AttrAsBool(options, "jpegOvershootDeringing");
1876
- baton->jpegOptimiseScans = sharp::AttrAsBool(options, "jpegOptimiseScans");
1877
- baton->jpegOptimiseCoding = sharp::AttrAsBool(options, "jpegOptimiseCoding");
1878
- baton->pngProgressive = sharp::AttrAsBool(options, "pngProgressive");
1879
- baton->pngCompressionLevel = sharp::AttrAsUint32(options, "pngCompressionLevel");
1880
- baton->pngAdaptiveFiltering = sharp::AttrAsBool(options, "pngAdaptiveFiltering");
1881
- baton->pngPalette = sharp::AttrAsBool(options, "pngPalette");
1882
- baton->pngQuality = sharp::AttrAsUint32(options, "pngQuality");
1883
- baton->pngEffort = sharp::AttrAsUint32(options, "pngEffort");
1884
- baton->pngBitdepth = sharp::AttrAsUint32(options, "pngBitdepth");
1885
- baton->pngDither = sharp::AttrAsDouble(options, "pngDither");
1886
- baton->jp2Quality = sharp::AttrAsUint32(options, "jp2Quality");
1887
- baton->jp2Lossless = sharp::AttrAsBool(options, "jp2Lossless");
1888
- baton->jp2TileHeight = sharp::AttrAsUint32(options, "jp2TileHeight");
1889
- baton->jp2TileWidth = sharp::AttrAsUint32(options, "jp2TileWidth");
1890
- baton->jp2ChromaSubsampling = sharp::AttrAsStr(options, "jp2ChromaSubsampling");
1891
- baton->webpQuality = sharp::AttrAsUint32(options, "webpQuality");
1892
- baton->webpAlphaQuality = sharp::AttrAsUint32(options, "webpAlphaQuality");
1893
- baton->webpLossless = sharp::AttrAsBool(options, "webpLossless");
1894
- baton->webpNearLossless = sharp::AttrAsBool(options, "webpNearLossless");
1895
- baton->webpSmartSubsample = sharp::AttrAsBool(options, "webpSmartSubsample");
1896
- baton->webpSmartDeblock = sharp::AttrAsBool(options, "webpSmartDeblock");
1897
- baton->webpPreset = sharp::AttrAsEnum<VipsForeignWebpPreset>(options, "webpPreset", VIPS_TYPE_FOREIGN_WEBP_PRESET);
1898
- baton->webpEffort = sharp::AttrAsUint32(options, "webpEffort");
1899
- baton->webpMinSize = sharp::AttrAsBool(options, "webpMinSize");
1900
- baton->webpMixed = sharp::AttrAsBool(options, "webpMixed");
1901
- baton->webpExact = sharp::AttrAsBool(options, "webpExact");
1902
- baton->gifBitdepth = sharp::AttrAsUint32(options, "gifBitdepth");
1903
- baton->gifEffort = sharp::AttrAsUint32(options, "gifEffort");
1904
- baton->gifDither = sharp::AttrAsDouble(options, "gifDither");
1905
- baton->gifInterFrameMaxError = sharp::AttrAsDouble(options, "gifInterFrameMaxError");
1906
- baton->gifInterPaletteMaxError = sharp::AttrAsDouble(options, "gifInterPaletteMaxError");
1907
- baton->gifKeepDuplicateFrames = sharp::AttrAsBool(options, "gifKeepDuplicateFrames");
1908
- baton->gifReuse = sharp::AttrAsBool(options, "gifReuse");
1909
- baton->gifProgressive = sharp::AttrAsBool(options, "gifProgressive");
1910
- baton->tiffQuality = sharp::AttrAsUint32(options, "tiffQuality");
1911
- baton->tiffBigtiff = sharp::AttrAsBool(options, "tiffBigtiff");
1912
- baton->tiffPyramid = sharp::AttrAsBool(options, "tiffPyramid");
1913
- baton->tiffMiniswhite = sharp::AttrAsBool(options, "tiffMiniswhite");
1914
- baton->tiffBitdepth = sharp::AttrAsUint32(options, "tiffBitdepth");
1915
- baton->tiffTile = sharp::AttrAsBool(options, "tiffTile");
1916
- baton->tiffTileWidth = sharp::AttrAsUint32(options, "tiffTileWidth");
1917
- baton->tiffTileHeight = sharp::AttrAsUint32(options, "tiffTileHeight");
1918
- baton->tiffXres = sharp::AttrAsDouble(options, "tiffXres");
1919
- baton->tiffYres = sharp::AttrAsDouble(options, "tiffYres");
1920
- if (baton->tiffXres == 1.0 && baton->tiffYres == 1.0 && baton->withMetadataDensity > 0) {
1921
- baton->tiffXres = baton->tiffYres = baton->withMetadataDensity / 25.4;
1922
- }
1923
- baton->tiffCompression = sharp::AttrAsEnum<VipsForeignTiffCompression>(
1924
- options, "tiffCompression", VIPS_TYPE_FOREIGN_TIFF_COMPRESSION);
1925
- baton->tiffPredictor = sharp::AttrAsEnum<VipsForeignTiffPredictor>(
1926
- options, "tiffPredictor", VIPS_TYPE_FOREIGN_TIFF_PREDICTOR);
1927
- baton->tiffResolutionUnit = sharp::AttrAsEnum<VipsForeignTiffResunit>(
1928
- options, "tiffResolutionUnit", VIPS_TYPE_FOREIGN_TIFF_RESUNIT);
1929
- baton->heifQuality = sharp::AttrAsUint32(options, "heifQuality");
1930
- baton->heifLossless = sharp::AttrAsBool(options, "heifLossless");
1931
- baton->heifCompression = sharp::AttrAsEnum<VipsForeignHeifCompression>(
1932
- options, "heifCompression", VIPS_TYPE_FOREIGN_HEIF_COMPRESSION);
1933
- baton->heifEffort = sharp::AttrAsUint32(options, "heifEffort");
1934
- baton->heifChromaSubsampling = sharp::AttrAsStr(options, "heifChromaSubsampling");
1935
- baton->heifBitdepth = sharp::AttrAsUint32(options, "heifBitdepth");
1936
- baton->heifTune = sharp::AttrAsStr(options, "heifTune");
1937
- baton->jxlDistance = sharp::AttrAsDouble(options, "jxlDistance");
1938
- baton->jxlDecodingTier = sharp::AttrAsUint32(options, "jxlDecodingTier");
1939
- baton->jxlEffort = sharp::AttrAsUint32(options, "jxlEffort");
1940
- baton->jxlLossless = sharp::AttrAsBool(options, "jxlLossless");
1941
- baton->rawDepth = sharp::AttrAsEnum<VipsBandFormat>(options, "rawDepth", VIPS_TYPE_BAND_FORMAT);
1942
- baton->tileSize = sharp::AttrAsUint32(options, "tileSize");
1943
- baton->tileOverlap = sharp::AttrAsUint32(options, "tileOverlap");
1944
- baton->tileAngle = sharp::AttrAsInt32(options, "tileAngle");
1945
- baton->tileBackground = sharp::AttrAsVectorOfDouble(options, "tileBackground");
1946
- baton->tileSkipBlanks = sharp::AttrAsInt32(options, "tileSkipBlanks");
1947
- baton->tileContainer = sharp::AttrAsEnum<VipsForeignDzContainer>(
1948
- options, "tileContainer", VIPS_TYPE_FOREIGN_DZ_CONTAINER);
1949
- baton->tileLayout = sharp::AttrAsEnum<VipsForeignDzLayout>(options, "tileLayout", VIPS_TYPE_FOREIGN_DZ_LAYOUT);
1950
- baton->tileFormat = sharp::AttrAsStr(options, "tileFormat");
1951
- baton->tileDepth = sharp::AttrAsEnum<VipsForeignDzDepth>(options, "tileDepth", VIPS_TYPE_FOREIGN_DZ_DEPTH);
1952
- baton->tileCentre = sharp::AttrAsBool(options, "tileCentre");
1953
- baton->tileId = sharp::AttrAsStr(options, "tileId");
1954
- baton->tileBasename = sharp::AttrAsStr(options, "tileBasename");
1955
-
1956
- // Function to notify of libvips warnings
1957
- Napi::Function debuglog = options.Get("debuglog").As<Napi::Function>();
1958
-
1959
- // Function to notify of queue length changes
1960
- Napi::Function queueListener = options.Get("queueListener").As<Napi::Function>();
1961
-
1962
- // Join queue for worker thread
1963
- Napi::Function callback = info[size_t(1)].As<Napi::Function>();
1964
- PipelineWorker *worker = new PipelineWorker(callback, baton, debuglog, queueListener);
1965
- worker->Receiver().Set("options", options);
1966
- worker->Queue();
1967
-
1968
- // Increment queued task counter
1969
- Napi::Number queueLength = Napi::Number::New(info.Env(), static_cast<int>(++sharp::counterQueue));
1970
- queueListener.SHARP_CALLBACK_FN_NAME(info.This(), { queueLength });
1971
-
1972
- return info.Env().Undefined();
1973
- }