UNPKG

61.6 kBtext/x-cView Raw
1// Copyright 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 Lovell Fuller and contributors.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15#include <algorithm>
16#include <cmath>
17#include <map>
18#include <memory>
19#include <numeric>
20#include <string>
21#include <tuple>
22#include <utility>
23#include <vector>
24#include <sys/types.h>
25#include <sys/stat.h>
26
27#include <vips/vips8>
28#include <napi.h>
29
30#include "common.h"
31#include "operations.h"
32#include "pipeline.h"
33
34#if defined(WIN32)
35#define STAT64_STRUCT __stat64
36#define STAT64_FUNCTION _stat64
37#elif defined(__APPLE__)
38#define STAT64_STRUCT stat
39#define STAT64_FUNCTION stat
40#elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
41#define STAT64_STRUCT stat
42#define STAT64_FUNCTION stat
43#else
44#define STAT64_STRUCT stat64
45#define STAT64_FUNCTION stat64
46#endif
47
48class PipelineWorker : public Napi::AsyncWorker {
49 public:
50 PipelineWorker(Napi::Function callback, PipelineBaton *baton,
51 Napi::Function debuglog, Napi::Function queueListener) :
52 Napi::AsyncWorker(callback),
53 baton(baton),
54 debuglog(Napi::Persistent(debuglog)),
55 queueListener(Napi::Persistent(queueListener)) {}
56 ~PipelineWorker() {}
57
58 // libuv worker
59 void Execute() {
60 // Decrement queued task counter
61 g_atomic_int_dec_and_test(&sharp::counterQueue);
62 // Increment processing task counter
63 g_atomic_int_inc(&sharp::counterProcess);
64
65 try {
66 // Open input
67 vips::VImage image;
68 sharp::ImageType inputImageType;
69 std::tie(image, inputImageType) = sharp::OpenInput(baton->input);
70
71 // Calculate angle of rotation
72 VipsAngle rotation;
73 if (baton->useExifOrientation) {
74 // Rotate and flip image according to Exif orientation
75 bool flip;
76 bool flop;
77 std::tie(rotation, flip, flop) = CalculateExifRotationAndFlip(sharp::ExifOrientation(image));
78 baton->flip = baton->flip || flip;
79 baton->flop = baton->flop || flop;
80 } else {
81 rotation = CalculateAngleRotation(baton->angle);
82 }
83
84 // Rotate pre-extract
85 if (baton->rotateBeforePreExtract) {
86 if (rotation != VIPS_ANGLE_D0) {
87 image = image.rot(rotation);
88 image = sharp::RemoveExifOrientation(image);
89 }
90 if (baton->rotationAngle != 0.0) {
91 std::vector<double> background;
92 std::tie(image, background) = sharp::ApplyAlpha(image, baton->rotationBackground);
93 image = image.rotate(baton->rotationAngle, VImage::option()->set("background", background));
94 }
95 }
96
97 // Trim
98 if (baton->trimThreshold > 0.0) {
99 image = sharp::Trim(image, baton->trimThreshold);
100 baton->trimOffsetLeft = image.xoffset();
101 baton->trimOffsetTop = image.yoffset();
102 }
103
104 // Pre extraction
105 if (baton->topOffsetPre != -1) {
106 image = image.extract_area(baton->leftOffsetPre, baton->topOffsetPre, baton->widthPre, baton->heightPre);
107 }
108
109 // Get pre-resize image width and height
110 int inputWidth = image.width();
111 int inputHeight = image.height();
112 if (!baton->rotateBeforePreExtract &&
113 (rotation == VIPS_ANGLE_D90 || rotation == VIPS_ANGLE_D270)) {
114 // Swap input output width and height when rotating by 90 or 270 degrees
115 std::swap(inputWidth, inputHeight);
116 }
117
118 // If withoutEnlargement is specified,
119 // Override target width and height if exceeds respective value from input file
120 if (baton->withoutEnlargement) {
121 if (baton->width > inputWidth) {
122 baton->width = inputWidth;
123 }
124 if (baton->height > inputHeight) {
125 baton->height = inputHeight;
126 }
127 }
128
129 // Scaling calculations
130 double xfactor = 1.0;
131 double yfactor = 1.0;
132 int targetResizeWidth = baton->width;
133 int targetResizeHeight = baton->height;
134 if (baton->width > 0 && baton->height > 0) {
135 // Fixed width and height
136 xfactor = static_cast<double>(inputWidth) / static_cast<double>(baton->width);
137 yfactor = static_cast<double>(inputHeight) / static_cast<double>(baton->height);
138 switch (baton->canvas) {
139 case Canvas::CROP:
140 if (xfactor < yfactor) {
141 targetResizeHeight = static_cast<int>(round(static_cast<double>(inputHeight) / xfactor));
142 yfactor = xfactor;
143 } else {
144 targetResizeWidth = static_cast<int>(round(static_cast<double>(inputWidth) / yfactor));
145 xfactor = yfactor;
146 }
147 break;
148 case Canvas::EMBED:
149 if (xfactor > yfactor) {
150 targetResizeHeight = static_cast<int>(round(static_cast<double>(inputHeight) / xfactor));
151 yfactor = xfactor;
152 } else {
153 targetResizeWidth = static_cast<int>(round(static_cast<double>(inputWidth) / yfactor));
154 xfactor = yfactor;
155 }
156 break;
157 case Canvas::MAX:
158 if (xfactor > yfactor) {
159 targetResizeHeight = baton->height = static_cast<int>(round(static_cast<double>(inputHeight) / xfactor));
160 yfactor = xfactor;
161 } else {
162 targetResizeWidth = baton->width = static_cast<int>(round(static_cast<double>(inputWidth) / yfactor));
163 xfactor = yfactor;
164 }
165 break;
166 case Canvas::MIN:
167 if (xfactor < yfactor) {
168 targetResizeHeight = baton->height = static_cast<int>(round(static_cast<double>(inputHeight) / xfactor));
169 yfactor = xfactor;
170 } else {
171 targetResizeWidth = baton->width = static_cast<int>(round(static_cast<double>(inputWidth) / yfactor));
172 xfactor = yfactor;
173 }
174 break;
175 case Canvas::IGNORE_ASPECT:
176 if (!baton->rotateBeforePreExtract &&
177 (rotation == VIPS_ANGLE_D90 || rotation == VIPS_ANGLE_D270)) {
178 std::swap(xfactor, yfactor);
179 }
180 break;
181 }
182 } else if (baton->width > 0) {
183 // Fixed width
184 xfactor = static_cast<double>(inputWidth) / static_cast<double>(baton->width);
185 if (baton->canvas == Canvas::IGNORE_ASPECT) {
186 targetResizeHeight = baton->height = inputHeight;
187 } else {
188 // Auto height
189 yfactor = xfactor;
190 targetResizeHeight = baton->height = static_cast<int>(round(static_cast<double>(inputHeight) / yfactor));
191 }
192 } else if (baton->height > 0) {
193 // Fixed height
194 yfactor = static_cast<double>(inputHeight) / static_cast<double>(baton->height);
195 if (baton->canvas == Canvas::IGNORE_ASPECT) {
196 targetResizeWidth = baton->width = inputWidth;
197 } else {
198 // Auto width
199 xfactor = yfactor;
200 targetResizeWidth = baton->width = static_cast<int>(round(static_cast<double>(inputWidth) / xfactor));
201 }
202 } else {
203 // Identity transform
204 baton->width = inputWidth;
205 baton->height = inputHeight;
206 }
207
208 // Calculate integral box shrink
209 int xshrink = std::max(1, static_cast<int>(floor(xfactor)));
210 int yshrink = std::max(1, static_cast<int>(floor(yfactor)));
211
212 // Calculate residual float affine transformation
213 double xresidual = static_cast<double>(xshrink) / xfactor;
214 double yresidual = static_cast<double>(yshrink) / yfactor;
215
216 // If integral x and y shrink are equal, try to use shrink-on-load for JPEG and WebP,
217 // but not when applying gamma correction, pre-resize extract or trim
218 int shrink_on_load = 1;
219
220 int shrink_on_load_factor = 1;
221 // Leave at least a factor of two for the final resize step, when fastShrinkOnLoad: false
222 // for more consistent results and avoid occasional small image shifting
223 if (!baton->fastShrinkOnLoad) {
224 shrink_on_load_factor = 2;
225 }
226 if (
227 xshrink == yshrink && xshrink >= 2 * shrink_on_load_factor &&
228 (inputImageType == sharp::ImageType::JPEG || inputImageType == sharp::ImageType::WEBP) &&
229 baton->gamma == 0 && baton->topOffsetPre == -1 && baton->trimThreshold == 0.0
230 ) {
231 if (xshrink >= 8 * shrink_on_load_factor) {
232 xfactor = xfactor / 8;
233 yfactor = yfactor / 8;
234 shrink_on_load = 8;
235 } else if (xshrink >= 4 * shrink_on_load_factor) {
236 xfactor = xfactor / 4;
237 yfactor = yfactor / 4;
238 shrink_on_load = 4;
239 } else if (xshrink >= 2 * shrink_on_load_factor) {
240 xfactor = xfactor / 2;
241 yfactor = yfactor / 2;
242 shrink_on_load = 2;
243 }
244 }
245 // Help ensure a final kernel-based reduction to prevent shrink aliasing
246 if (shrink_on_load > 1 && (xresidual == 1.0 || yresidual == 1.0)) {
247 shrink_on_load = shrink_on_load / 2;
248 xfactor = xfactor * 2;
249 yfactor = yfactor * 2;
250 }
251 if (shrink_on_load > 1) {
252 // Reload input using shrink-on-load
253 vips::VOption *option = VImage::option()
254 ->set("access", baton->input->access)
255 ->set("shrink", shrink_on_load)
256 ->set("fail", baton->input->failOnError);
257 if (baton->input->buffer != nullptr) {
258 VipsBlob *blob = vips_blob_new(nullptr, baton->input->buffer, baton->input->bufferLength);
259 if (inputImageType == sharp::ImageType::JPEG) {
260 // Reload JPEG buffer
261 image = VImage::jpegload_buffer(blob, option);
262 } else {
263 // Reload WebP buffer
264 image = VImage::webpload_buffer(blob, option);
265 }
266 vips_area_unref(reinterpret_cast<VipsArea*>(blob));
267 } else {
268 if (inputImageType == sharp::ImageType::JPEG) {
269 // Reload JPEG file
270 image = VImage::jpegload(const_cast<char*>(baton->input->file.data()), option);
271 } else {
272 // Reload WebP file
273 image = VImage::webpload(const_cast<char*>(baton->input->file.data()), option);
274 }
275 }
276 // Recalculate integral shrink and double residual
277 int const shrunkOnLoadWidth = image.width();
278 int const shrunkOnLoadHeight = image.height();
279 if (!baton->rotateBeforePreExtract &&
280 (rotation == VIPS_ANGLE_D90 || rotation == VIPS_ANGLE_D270)) {
281 // Swap when rotating by 90 or 270 degrees
282 xfactor = static_cast<double>(shrunkOnLoadWidth) / static_cast<double>(targetResizeHeight);
283 yfactor = static_cast<double>(shrunkOnLoadHeight) / static_cast<double>(targetResizeWidth);
284 } else {
285 xfactor = static_cast<double>(shrunkOnLoadWidth) / static_cast<double>(targetResizeWidth);
286 yfactor = static_cast<double>(shrunkOnLoadHeight) / static_cast<double>(targetResizeHeight);
287 }
288 }
289
290 // Ensure we're using a device-independent colour space
291 if (
292 sharp::HasProfile(image) &&
293 image.interpretation() != VIPS_INTERPRETATION_LABS &&
294 image.interpretation() != VIPS_INTERPRETATION_GREY16
295 ) {
296 // Convert to sRGB using embedded profile
297 try {
298 image = image.icc_transform("srgb", VImage::option()
299 ->set("embedded", TRUE)
300 ->set("depth", image.interpretation() == VIPS_INTERPRETATION_RGB16 ? 16 : 8)
301 ->set("intent", VIPS_INTENT_PERCEPTUAL));
302 } catch(...) {
303 // Ignore failure of embedded profile
304 }
305 } else if (image.interpretation() == VIPS_INTERPRETATION_CMYK) {
306 image = image.icc_transform("srgb", VImage::option()
307 ->set("input_profile", "cmyk")
308 ->set("intent", VIPS_INTENT_PERCEPTUAL));
309 }
310
311 // Flatten image to remove alpha channel
312 if (baton->flatten && sharp::HasAlpha(image)) {
313 // Scale up 8-bit values to match 16-bit input image
314 double const multiplier = sharp::Is16Bit(image.interpretation()) ? 256.0 : 1.0;
315 // Background colour
316 std::vector<double> background {
317 baton->flattenBackground[0] * multiplier,
318 baton->flattenBackground[1] * multiplier,
319 baton->flattenBackground[2] * multiplier
320 };
321 image = image.flatten(VImage::option()
322 ->set("background", background));
323 }
324
325 // Negate the colours in the image
326 if (baton->negate) {
327 image = image.invert();
328 }
329
330 // Gamma encoding (darken)
331 if (baton->gamma >= 1 && baton->gamma <= 3) {
332 image = sharp::Gamma(image, 1.0 / baton->gamma);
333 }
334
335 // Convert to greyscale (linear, therefore after gamma encoding, if any)
336 if (baton->greyscale) {
337 image = image.colourspace(VIPS_INTERPRETATION_B_W);
338 }
339
340 bool const shouldResize = xfactor != 1.0 || yfactor != 1.0;
341 bool const shouldBlur = baton->blurSigma != 0.0;
342 bool const shouldConv = baton->convKernelWidth * baton->convKernelHeight > 0;
343 bool const shouldSharpen = baton->sharpenSigma != 0.0;
344 bool const shouldApplyMedian = baton->medianSize > 0;
345 bool const shouldComposite = !baton->composite.empty();
346 bool const shouldModulate = baton->brightness != 1.0 || baton->saturation != 1.0 || baton->hue != 0.0;
347
348 if (shouldComposite && !sharp::HasAlpha(image)) {
349 image = sharp::EnsureAlpha(image);
350 }
351
352 bool const shouldPremultiplyAlpha = sharp::HasAlpha(image) &&
353 (shouldResize || shouldBlur || shouldConv || shouldSharpen || shouldComposite);
354
355 // Premultiply image alpha channel before all transformations to avoid
356 // dark fringing around bright pixels
357 // See: http://entropymine.com/imageworsener/resizealpha/
358 if (shouldPremultiplyAlpha) {
359 image = image.premultiply();
360 }
361
362 // Resize
363 if (shouldResize) {
364 VipsKernel kernel = static_cast<VipsKernel>(
365 vips_enum_from_nick(nullptr, VIPS_TYPE_KERNEL, baton->kernel.data()));
366 if (
367 kernel != VIPS_KERNEL_NEAREST && kernel != VIPS_KERNEL_CUBIC && kernel != VIPS_KERNEL_LANCZOS2 &&
368 kernel != VIPS_KERNEL_LANCZOS3 && kernel != VIPS_KERNEL_MITCHELL
369 ) {
370 throw vips::VError("Unknown kernel");
371 }
372 // Ensure shortest edge is at least 1 pixel
373 if (image.width() / xfactor < 0.5) {
374 xfactor = 2 * image.width();
375 baton->width = 1;
376 }
377 if (image.height() / yfactor < 0.5) {
378 yfactor = 2 * image.height();
379 baton->height = 1;
380 }
381 image = image.resize(1.0 / xfactor, VImage::option()
382 ->set("vscale", 1.0 / yfactor)
383 ->set("kernel", kernel));
384 }
385
386 // Rotate post-extract 90-angle
387 if (!baton->rotateBeforePreExtract && rotation != VIPS_ANGLE_D0) {
388 image = image.rot(rotation);
389 image = sharp::RemoveExifOrientation(image);
390 }
391
392
393 // Flip (mirror about Y axis)
394 if (baton->flip) {
395 image = image.flip(VIPS_DIRECTION_VERTICAL);
396 image = sharp::RemoveExifOrientation(image);
397 }
398
399 // Flop (mirror about X axis)
400 if (baton->flop) {
401 image = image.flip(VIPS_DIRECTION_HORIZONTAL);
402 image = sharp::RemoveExifOrientation(image);
403 }
404
405 // Join additional color channels to the image
406 if (baton->joinChannelIn.size() > 0) {
407 VImage joinImage;
408 sharp::ImageType joinImageType = sharp::ImageType::UNKNOWN;
409
410 for (unsigned int i = 0; i < baton->joinChannelIn.size(); i++) {
411 std::tie(joinImage, joinImageType) = sharp::OpenInput(baton->joinChannelIn[i]);
412 image = image.bandjoin(joinImage);
413 }
414 image = image.copy(VImage::option()->set("interpretation", baton->colourspace));
415 }
416
417 // Crop/embed
418 if (image.width() != baton->width || image.height() != baton->height) {
419 if (baton->canvas == Canvas::EMBED) {
420 std::vector<double> background;
421 std::tie(image, background) = sharp::ApplyAlpha(image, baton->resizeBackground);
422
423 // Embed
424
425 // Calculate where to position the embeded image if gravity specified, else center.
426 int left;
427 int top;
428
429 left = static_cast<int>(round((baton->width - image.width()) / 2));
430 top = static_cast<int>(round((baton->height - image.height()) / 2));
431
432 int width = std::max(image.width(), baton->width);
433 int height = std::max(image.height(), baton->height);
434 std::tie(left, top) = sharp::CalculateEmbedPosition(
435 image.width(), image.height(), baton->width, baton->height, baton->position);
436
437 image = image.embed(left, top, width, height, VImage::option()
438 ->set("extend", VIPS_EXTEND_BACKGROUND)
439 ->set("background", background));
440
441 } else if (
442 baton->canvas != Canvas::IGNORE_ASPECT &&
443 (image.width() > baton->width || image.height() > baton->height)
444 ) {
445 // Crop/max/min
446 if (baton->position < 9) {
447 // Gravity-based crop
448 int left;
449 int top;
450 std::tie(left, top) = sharp::CalculateCrop(
451 image.width(), image.height(), baton->width, baton->height, baton->position);
452 int width = std::min(image.width(), baton->width);
453 int height = std::min(image.height(), baton->height);
454 image = image.extract_area(left, top, width, height);
455 } else {
456 // Attention-based or Entropy-based crop
457 if (baton->width > image.width()) {
458 baton->width = image.width();
459 }
460 if (baton->height > image.height()) {
461 baton->height = image.height();
462 }
463 image = image.tilecache(VImage::option()
464 ->set("access", VIPS_ACCESS_RANDOM)
465 ->set("threaded", TRUE));
466 image = image.smartcrop(baton->width, baton->height, VImage::option()
467 ->set("interesting", baton->position == 16 ? VIPS_INTERESTING_ENTROPY : VIPS_INTERESTING_ATTENTION));
468 baton->hasCropOffset = true;
469 baton->cropOffsetLeft = static_cast<int>(image.xoffset());
470 baton->cropOffsetTop = static_cast<int>(image.yoffset());
471 }
472 }
473 }
474
475 // Rotate post-extract non-90 angle
476 if (!baton->rotateBeforePreExtract && baton->rotationAngle != 0.0) {
477 std::vector<double> background;
478 std::tie(image, background) = sharp::ApplyAlpha(image, baton->rotationBackground);
479 image = image.rotate(baton->rotationAngle, VImage::option()->set("background", background));
480 }
481
482 // Post extraction
483 if (baton->topOffsetPost != -1) {
484 image = image.extract_area(
485 baton->leftOffsetPost, baton->topOffsetPost, baton->widthPost, baton->heightPost);
486 }
487
488 // Extend edges
489 if (baton->extendTop > 0 || baton->extendBottom > 0 || baton->extendLeft > 0 || baton->extendRight > 0) {
490 std::vector<double> background;
491 std::tie(image, background) = sharp::ApplyAlpha(image, baton->extendBackground);
492
493 // Embed
494 baton->width = image.width() + baton->extendLeft + baton->extendRight;
495 baton->height = image.height() + baton->extendTop + baton->extendBottom;
496
497 image = image.embed(baton->extendLeft, baton->extendTop, baton->width, baton->height,
498 VImage::option()->set("extend", VIPS_EXTEND_BACKGROUND)->set("background", background));
499 }
500 // Median - must happen before blurring, due to the utility of blurring after thresholding
501 if (shouldApplyMedian) {
502 image = image.median(baton->medianSize);
503 }
504 // Threshold - must happen before blurring, due to the utility of blurring after thresholding
505 if (baton->threshold != 0) {
506 image = sharp::Threshold(image, baton->threshold, baton->thresholdGrayscale);
507 }
508
509 // Blur
510 if (shouldBlur) {
511 image = sharp::Blur(image, baton->blurSigma);
512 }
513
514 // Convolve
515 if (shouldConv) {
516 image = sharp::Convolve(image,
517 baton->convKernelWidth, baton->convKernelHeight,
518 baton->convKernelScale, baton->convKernelOffset,
519 baton->convKernel);
520 }
521
522 // Recomb
523 if (baton->recombMatrix != NULL) {
524 image = sharp::Recomb(image, baton->recombMatrix);
525 }
526
527 if (shouldModulate) {
528 image = sharp::Modulate(image, baton->brightness, baton->saturation, baton->hue);
529 }
530
531 // Sharpen
532 if (shouldSharpen) {
533 image = sharp::Sharpen(image, baton->sharpenSigma, baton->sharpenFlat, baton->sharpenJagged);
534 }
535
536 // Composite
537 if (shouldComposite) {
538 for (Composite *composite : baton->composite) {
539 VImage compositeImage;
540 sharp::ImageType compositeImageType = sharp::ImageType::UNKNOWN;
541 std::tie(compositeImage, compositeImageType) = OpenInput(composite->input);
542 // Verify within current dimensions
543 if (compositeImage.width() > image.width() || compositeImage.height() > image.height()) {
544 throw vips::VError("Image to composite must have same dimensions or smaller");
545 }
546 // Check if overlay is tiled
547 if (composite->tile) {
548 int across = 0;
549 int down = 0;
550 // Use gravity in overlay
551 if (compositeImage.width() <= baton->width) {
552 across = static_cast<int>(ceil(static_cast<double>(image.width()) / compositeImage.width()));
553 }
554 if (compositeImage.height() <= baton->height) {
555 down = static_cast<int>(ceil(static_cast<double>(image.height()) / compositeImage.height()));
556 }
557 if (across != 0 || down != 0) {
558 int left;
559 int top;
560 compositeImage = compositeImage.replicate(across, down);
561 if (composite->left >= 0 && composite->top >= 0) {
562 std::tie(left, top) = sharp::CalculateCrop(
563 compositeImage.width(), compositeImage.height(), image.width(), image.height(),
564 composite->left, composite->top);
565 } else {
566 std::tie(left, top) = sharp::CalculateCrop(
567 compositeImage.width(), compositeImage.height(), image.width(), image.height(), composite->gravity);
568 }
569 compositeImage = compositeImage.extract_area(left, top, image.width(), image.height());
570 }
571 // gravity was used for extract_area, set it back to its default value of 0
572 composite->gravity = 0;
573 }
574 // Ensure image to composite is sRGB with premultiplied alpha
575 compositeImage = compositeImage.colourspace(VIPS_INTERPRETATION_sRGB);
576 if (!sharp::HasAlpha(compositeImage)) {
577 compositeImage = sharp::EnsureAlpha(compositeImage);
578 }
579 if (!composite->premultiplied) compositeImage = compositeImage.premultiply();
580 // Calculate position
581 int left;
582 int top;
583 if (composite->left >= 0 && composite->top >= 0) {
584 // Composite image at given offsets
585 std::tie(left, top) = sharp::CalculateCrop(image.width(), image.height(),
586 compositeImage.width(), compositeImage.height(), composite->left, composite->top);
587 } else {
588 // Composite image with given gravity
589 std::tie(left, top) = sharp::CalculateCrop(image.width(), image.height(),
590 compositeImage.width(), compositeImage.height(), composite->gravity);
591 }
592 // Composite
593 image = image.composite2(compositeImage, composite->mode, VImage::option()
594 ->set("premultiplied", TRUE)
595 ->set("x", left)
596 ->set("y", top));
597 }
598 }
599
600 // Reverse premultiplication after all transformations:
601 if (shouldPremultiplyAlpha) {
602 image = image.unpremultiply();
603 // Cast pixel values to integer
604 if (sharp::Is16Bit(image.interpretation())) {
605 image = image.cast(VIPS_FORMAT_USHORT);
606 } else {
607 image = image.cast(VIPS_FORMAT_UCHAR);
608 }
609 }
610 baton->premultiplied = shouldPremultiplyAlpha;
611
612 // Gamma decoding (brighten)
613 if (baton->gammaOut >= 1 && baton->gammaOut <= 3) {
614 image = sharp::Gamma(image, baton->gammaOut);
615 }
616
617 // Linear adjustment (a * in + b)
618 if (baton->linearA != 1.0 || baton->linearB != 0.0) {
619 image = sharp::Linear(image, baton->linearA, baton->linearB);
620 }
621
622 // Apply normalisation - stretch luminance to cover full dynamic range
623 if (baton->normalise) {
624 image = sharp::Normalise(image);
625 }
626
627 // Apply bitwise boolean operation between images
628 if (baton->boolean != nullptr) {
629 VImage booleanImage;
630 sharp::ImageType booleanImageType = sharp::ImageType::UNKNOWN;
631 std::tie(booleanImage, booleanImageType) = sharp::OpenInput(baton->boolean);
632 image = sharp::Boolean(image, booleanImage, baton->booleanOp);
633 }
634
635 // Apply per-channel Bandbool bitwise operations after all other operations
636 if (baton->bandBoolOp >= VIPS_OPERATION_BOOLEAN_AND && baton->bandBoolOp < VIPS_OPERATION_BOOLEAN_LAST) {
637 image = sharp::Bandbool(image, baton->bandBoolOp);
638 }
639
640 // Tint the image
641 if (baton->tintA < 128.0 || baton->tintB < 128.0) {
642 image = sharp::Tint(image, baton->tintA, baton->tintB);
643 }
644
645 // Extract an image channel (aka vips band)
646 if (baton->extractChannel > -1) {
647 if (baton->extractChannel >= image.bands()) {
648 if (baton->extractChannel == 3 && sharp::HasAlpha(image)) {
649 baton->extractChannel = image.bands() - 1;
650 } else {
651 (baton->err).append("Cannot extract channel from image. Too few channels in image.");
652 return Error();
653 }
654 }
655 VipsInterpretation const interpretation = sharp::Is16Bit(image.interpretation())
656 ? VIPS_INTERPRETATION_GREY16
657 : VIPS_INTERPRETATION_B_W;
658 image = image
659 .extract_band(baton->extractChannel)
660 .copy(VImage::option()->set("interpretation", interpretation));
661 }
662
663 // Remove alpha channel, if any
664 if (baton->removeAlpha) {
665 image = sharp::RemoveAlpha(image);
666 }
667
668 // Ensure alpha channel, if missing
669 if (baton->ensureAlpha) {
670 image = sharp::EnsureAlpha(image);
671 }
672
673 // Convert image to sRGB, if not already
674 if (sharp::Is16Bit(image.interpretation())) {
675 image = image.cast(VIPS_FORMAT_USHORT);
676 }
677 if (image.interpretation() != baton->colourspace) {
678 // Convert colourspace, pass the current known interpretation so libvips doesn't have to guess
679 image = image.colourspace(baton->colourspace, VImage::option()->set("source_space", image.interpretation()));
680 // Transform colours from embedded profile to output profile
681 if (baton->withMetadata && sharp::HasProfile(image)) {
682 image = image.icc_transform(vips_enum_nick(VIPS_TYPE_INTERPRETATION, baton->colourspace),
683 VImage::option()->set("embedded", TRUE));
684 }
685 }
686
687 // Override EXIF Orientation tag
688 if (baton->withMetadata && baton->withMetadataOrientation != -1) {
689 image = sharp::SetExifOrientation(image, baton->withMetadataOrientation);
690 }
691
692 // Number of channels used in output image
693 baton->channels = image.bands();
694 baton->width = image.width();
695 baton->height = image.height();
696 // Output
697 if (baton->fileOut.empty()) {
698 // Buffer output
699 if (baton->formatOut == "jpeg" || (baton->formatOut == "input" && inputImageType == sharp::ImageType::JPEG)) {
700 // Write JPEG to buffer
701 sharp::AssertImageTypeDimensions(image, sharp::ImageType::JPEG);
702 VipsArea *area = VIPS_AREA(image.jpegsave_buffer(VImage::option()
703 ->set("strip", !baton->withMetadata)
704 ->set("Q", baton->jpegQuality)
705 ->set("interlace", baton->jpegProgressive)
706 ->set("no_subsample", baton->jpegChromaSubsampling == "4:4:4")
707 ->set("trellis_quant", baton->jpegTrellisQuantisation)
708 ->set("quant_table", baton->jpegQuantisationTable)
709 ->set("overshoot_deringing", baton->jpegOvershootDeringing)
710 ->set("optimize_scans", baton->jpegOptimiseScans)
711 ->set("optimize_coding", baton->jpegOptimiseCoding)));
712 baton->bufferOut = static_cast<char*>(area->data);
713 baton->bufferOutLength = area->length;
714 area->free_fn = nullptr;
715 vips_area_unref(area);
716 baton->formatOut = "jpeg";
717 if (baton->colourspace == VIPS_INTERPRETATION_CMYK) {
718 baton->channels = std::min(baton->channels, 4);
719 } else {
720 baton->channels = std::min(baton->channels, 3);
721 }
722 } else if (baton->formatOut == "png" || (baton->formatOut == "input" &&
723 (inputImageType == sharp::ImageType::PNG || inputImageType == sharp::ImageType::GIF ||
724 inputImageType == sharp::ImageType::SVG))) {
725 // Write PNG to buffer
726 sharp::AssertImageTypeDimensions(image, sharp::ImageType::PNG);
727 VipsArea *area = VIPS_AREA(image.pngsave_buffer(VImage::option()
728 ->set("strip", !baton->withMetadata)
729 ->set("interlace", baton->pngProgressive)
730 ->set("compression", baton->pngCompressionLevel)
731 ->set("filter", baton->pngAdaptiveFiltering ? VIPS_FOREIGN_PNG_FILTER_ALL : VIPS_FOREIGN_PNG_FILTER_NONE)
732 ->set("palette", baton->pngPalette)
733 ->set("Q", baton->pngQuality)
734 ->set("colours", baton->pngColours)
735 ->set("dither", baton->pngDither)));
736 baton->bufferOut = static_cast<char*>(area->data);
737 baton->bufferOutLength = area->length;
738 area->free_fn = nullptr;
739 vips_area_unref(area);
740 baton->formatOut = "png";
741 } else if (baton->formatOut == "webp" ||
742 (baton->formatOut == "input" && inputImageType == sharp::ImageType::WEBP)) {
743 // Write WEBP to buffer
744 sharp::AssertImageTypeDimensions(image, sharp::ImageType::WEBP);
745 VipsArea *area = VIPS_AREA(image.webpsave_buffer(VImage::option()
746 ->set("strip", !baton->withMetadata)
747 ->set("Q", baton->webpQuality)
748 ->set("lossless", baton->webpLossless)
749 ->set("near_lossless", baton->webpNearLossless)
750 ->set("smart_subsample", baton->webpSmartSubsample)
751 ->set("reduction_effort", baton->webpReductionEffort)
752 ->set("alpha_q", baton->webpAlphaQuality)));
753 baton->bufferOut = static_cast<char*>(area->data);
754 baton->bufferOutLength = area->length;
755 area->free_fn = nullptr;
756 vips_area_unref(area);
757 baton->formatOut = "webp";
758 } else if (baton->formatOut == "tiff" ||
759 (baton->formatOut == "input" && inputImageType == sharp::ImageType::TIFF)) {
760 // Write TIFF to buffer
761 if (baton->tiffCompression == VIPS_FOREIGN_TIFF_COMPRESSION_JPEG) {
762 sharp::AssertImageTypeDimensions(image, sharp::ImageType::JPEG);
763 baton->channels = std::min(baton->channels, 3);
764 }
765 // Cast pixel values to float, if required
766 if (baton->tiffPredictor == VIPS_FOREIGN_TIFF_PREDICTOR_FLOAT) {
767 image = image.cast(VIPS_FORMAT_FLOAT);
768 }
769 VipsArea *area = VIPS_AREA(image.tiffsave_buffer(VImage::option()
770 ->set("strip", !baton->withMetadata)
771 ->set("Q", baton->tiffQuality)
772 ->set("squash", baton->tiffSquash)
773 ->set("compression", baton->tiffCompression)
774 ->set("predictor", baton->tiffPredictor)
775 ->set("pyramid", baton->tiffPyramid)
776 ->set("tile", baton->tiffTile)
777 ->set("tile_height", baton->tiffTileHeight)
778 ->set("tile_width", baton->tiffTileWidth)
779 ->set("xres", baton->tiffXres)
780 ->set("yres", baton->tiffYres)));
781 baton->bufferOut = static_cast<char*>(area->data);
782 baton->bufferOutLength = area->length;
783 area->free_fn = nullptr;
784 vips_area_unref(area);
785 baton->formatOut = "tiff";
786 } else if (baton->formatOut == "heif" ||
787 (baton->formatOut == "input" && inputImageType == sharp::ImageType::HEIF)) {
788 // Write HEIF to buffer
789 VipsArea *area = VIPS_AREA(image.heifsave_buffer(VImage::option()
790 ->set("strip", !baton->withMetadata)
791 ->set("compression", baton->heifCompression)
792 ->set("Q", baton->heifQuality)
793 ->set("lossless", baton->heifLossless)));
794 baton->bufferOut = static_cast<char*>(area->data);
795 baton->bufferOutLength = area->length;
796 area->free_fn = nullptr;
797 vips_area_unref(area);
798 baton->formatOut = "heif";
799 } else if (baton->formatOut == "raw" ||
800 (baton->formatOut == "input" && inputImageType == sharp::ImageType::RAW)) {
801 // Write raw, uncompressed image data to buffer
802 if (baton->greyscale || image.interpretation() == VIPS_INTERPRETATION_B_W) {
803 // Extract first band for greyscale image
804 image = image[0];
805 baton->channels = 1;
806 }
807 if (image.format() != VIPS_FORMAT_UCHAR) {
808 // Cast pixels to uint8 (unsigned char)
809 image = image.cast(VIPS_FORMAT_UCHAR);
810 }
811 // Get raw image data
812 baton->bufferOut = static_cast<char*>(image.write_to_memory(&baton->bufferOutLength));
813 if (baton->bufferOut == nullptr) {
814 (baton->err).append("Could not allocate enough memory for raw output");
815 return Error();
816 }
817 baton->formatOut = "raw";
818 } else {
819 // Unsupported output format
820 (baton->err).append("Unsupported output format ");
821 if (baton->formatOut == "input") {
822 (baton->err).append(ImageTypeId(inputImageType));
823 } else {
824 (baton->err).append(baton->formatOut);
825 }
826 return Error();
827 }
828 } else {
829 // File output
830 bool const isJpeg = sharp::IsJpeg(baton->fileOut);
831 bool const isPng = sharp::IsPng(baton->fileOut);
832 bool const isWebp = sharp::IsWebp(baton->fileOut);
833 bool const isTiff = sharp::IsTiff(baton->fileOut);
834 bool const isHeif = sharp::IsHeif(baton->fileOut);
835 bool const isDz = sharp::IsDz(baton->fileOut);
836 bool const isDzZip = sharp::IsDzZip(baton->fileOut);
837 bool const isV = sharp::IsV(baton->fileOut);
838 bool const mightMatchInput = baton->formatOut == "input";
839 bool const willMatchInput = mightMatchInput && !(isJpeg || isPng || isWebp || isTiff || isDz || isDzZip || isV);
840 if (baton->formatOut == "jpeg" || (mightMatchInput && isJpeg) ||
841 (willMatchInput && inputImageType == sharp::ImageType::JPEG)) {
842 // Write JPEG to file
843 sharp::AssertImageTypeDimensions(image, sharp::ImageType::JPEG);
844 image.jpegsave(const_cast<char*>(baton->fileOut.data()), VImage::option()
845 ->set("strip", !baton->withMetadata)
846 ->set("Q", baton->jpegQuality)
847 ->set("interlace", baton->jpegProgressive)
848 ->set("no_subsample", baton->jpegChromaSubsampling == "4:4:4")
849 ->set("trellis_quant", baton->jpegTrellisQuantisation)
850 ->set("quant_table", baton->jpegQuantisationTable)
851 ->set("overshoot_deringing", baton->jpegOvershootDeringing)
852 ->set("optimize_scans", baton->jpegOptimiseScans)
853 ->set("optimize_coding", baton->jpegOptimiseCoding));
854 baton->formatOut = "jpeg";
855 baton->channels = std::min(baton->channels, 3);
856 } else if (baton->formatOut == "png" || (mightMatchInput && isPng) || (willMatchInput &&
857 (inputImageType == sharp::ImageType::PNG || inputImageType == sharp::ImageType::GIF ||
858 inputImageType == sharp::ImageType::SVG))) {
859 // Write PNG to file
860 sharp::AssertImageTypeDimensions(image, sharp::ImageType::PNG);
861 image.pngsave(const_cast<char*>(baton->fileOut.data()), VImage::option()
862 ->set("strip", !baton->withMetadata)
863 ->set("interlace", baton->pngProgressive)
864 ->set("compression", baton->pngCompressionLevel)
865 ->set("filter", baton->pngAdaptiveFiltering ? VIPS_FOREIGN_PNG_FILTER_ALL : VIPS_FOREIGN_PNG_FILTER_NONE)
866 ->set("palette", baton->pngPalette)
867 ->set("Q", baton->pngQuality)
868 ->set("colours", baton->pngColours)
869 ->set("dither", baton->pngDither));
870 baton->formatOut = "png";
871 } else if (baton->formatOut == "webp" || (mightMatchInput && isWebp) ||
872 (willMatchInput && inputImageType == sharp::ImageType::WEBP)) {
873 // Write WEBP to file
874 sharp::AssertImageTypeDimensions(image, sharp::ImageType::WEBP);
875 image.webpsave(const_cast<char*>(baton->fileOut.data()), VImage::option()
876 ->set("strip", !baton->withMetadata)
877 ->set("Q", baton->webpQuality)
878 ->set("lossless", baton->webpLossless)
879 ->set("near_lossless", baton->webpNearLossless)
880 ->set("smart_subsample", baton->webpSmartSubsample)
881 ->set("reduction_effort", baton->webpReductionEffort)
882 ->set("alpha_q", baton->webpAlphaQuality));
883 baton->formatOut = "webp";
884 } else if (baton->formatOut == "tiff" || (mightMatchInput && isTiff) ||
885 (willMatchInput && inputImageType == sharp::ImageType::TIFF)) {
886 // Write TIFF to file
887 if (baton->tiffCompression == VIPS_FOREIGN_TIFF_COMPRESSION_JPEG) {
888 sharp::AssertImageTypeDimensions(image, sharp::ImageType::JPEG);
889 baton->channels = std::min(baton->channels, 3);
890 }
891 image.tiffsave(const_cast<char*>(baton->fileOut.data()), VImage::option()
892 ->set("strip", !baton->withMetadata)
893 ->set("Q", baton->tiffQuality)
894 ->set("squash", baton->tiffSquash)
895 ->set("compression", baton->tiffCompression)
896 ->set("predictor", baton->tiffPredictor)
897 ->set("pyramid", baton->tiffPyramid)
898 ->set("tile", baton->tiffTile)
899 ->set("tile_height", baton->tiffTileHeight)
900 ->set("tile_width", baton->tiffTileWidth)
901 ->set("xres", baton->tiffXres)
902 ->set("yres", baton->tiffYres));
903 baton->formatOut = "tiff";
904 } else if (baton->formatOut == "heif" || (mightMatchInput && isHeif) ||
905 (willMatchInput && inputImageType == sharp::ImageType::HEIF)) {
906 // Write HEIF to file
907 if (sharp::IsAvif(baton->fileOut)) {
908 baton->heifCompression = VIPS_FOREIGN_HEIF_COMPRESSION_AV1;
909 }
910 image.heifsave(const_cast<char*>(baton->fileOut.data()), VImage::option()
911 ->set("strip", !baton->withMetadata)
912 ->set("Q", baton->heifQuality)
913 ->set("compression", baton->heifCompression)
914 ->set("lossless", baton->heifLossless));
915 baton->formatOut = "heif";
916 } else if (baton->formatOut == "dz" || isDz || isDzZip) {
917 if (isDzZip) {
918 baton->tileContainer = VIPS_FOREIGN_DZ_CONTAINER_ZIP;
919 }
920 // Forward format options through suffix
921 std::string suffix;
922 if (baton->tileFormat == "png") {
923 std::vector<std::pair<std::string, std::string>> options {
924 {"interlace", baton->pngProgressive ? "TRUE" : "FALSE"},
925 {"compression", std::to_string(baton->pngCompressionLevel)},
926 {"filter", baton->pngAdaptiveFiltering ? "all" : "none"}
927 };
928 suffix = AssembleSuffixString(".png", options);
929 } else if (baton->tileFormat == "webp") {
930 std::vector<std::pair<std::string, std::string>> options {
931 {"Q", std::to_string(baton->webpQuality)},
932 {"alpha_q", std::to_string(baton->webpAlphaQuality)},
933 {"lossless", baton->webpLossless ? "TRUE" : "FALSE"},
934 {"near_lossless", baton->webpNearLossless ? "TRUE" : "FALSE"},
935 {"smart_subsample", baton->webpSmartSubsample ? "TRUE" : "FALSE"},
936 {"reduction_effort", std::to_string(baton->webpReductionEffort)}
937 };
938 suffix = AssembleSuffixString(".webp", options);
939 } else {
940 std::vector<std::pair<std::string, std::string>> options {
941 {"Q", std::to_string(baton->jpegQuality)},
942 {"interlace", baton->jpegProgressive ? "TRUE" : "FALSE"},
943 {"no_subsample", baton->jpegChromaSubsampling == "4:4:4" ? "TRUE": "FALSE"},
944 {"trellis_quant", baton->jpegTrellisQuantisation ? "TRUE" : "FALSE"},
945 {"quant_table", std::to_string(baton->jpegQuantisationTable)},
946 {"overshoot_deringing", baton->jpegOvershootDeringing ? "TRUE": "FALSE"},
947 {"optimize_scans", baton->jpegOptimiseScans ? "TRUE": "FALSE"},
948 {"optimize_coding", baton->jpegOptimiseCoding ? "TRUE": "FALSE"}
949 };
950 std::string extname = baton->tileLayout == VIPS_FOREIGN_DZ_LAYOUT_DZ ? ".jpeg" : ".jpg";
951 suffix = AssembleSuffixString(extname, options);
952 }
953 // Remove alpha channel from tile background if image does not contain an alpha channel
954 if (!sharp::HasAlpha(image)) {
955 baton->tileBackground.pop_back();
956 }
957 // Write DZ to file
958 vips::VOption *options = VImage::option()
959 ->set("strip", !baton->withMetadata)
960 ->set("tile_size", baton->tileSize)
961 ->set("overlap", baton->tileOverlap)
962 ->set("container", baton->tileContainer)
963 ->set("layout", baton->tileLayout)
964 ->set("suffix", const_cast<char*>(suffix.data()))
965 ->set("angle", CalculateAngleRotation(baton->tileAngle))
966 ->set("background", baton->tileBackground)
967 ->set("skip_blanks", baton->tileSkipBlanks);
968 // libvips chooses a default depth based on layout. Instead of replicating that logic here by
969 // not passing anything - libvips will handle choice
970 if (baton->tileDepth < VIPS_FOREIGN_DZ_DEPTH_LAST) {
971 options->set("depth", baton->tileDepth);
972 }
973 image.dzsave(const_cast<char*>(baton->fileOut.data()), options);
974 baton->formatOut = "dz";
975 } else if (baton->formatOut == "v" || (mightMatchInput && isV) ||
976 (willMatchInput && inputImageType == sharp::ImageType::VIPS)) {
977 // Write V to file
978 image.vipssave(const_cast<char*>(baton->fileOut.data()), VImage::option()
979 ->set("strip", !baton->withMetadata));
980 baton->formatOut = "v";
981 } else {
982 // Unsupported output format
983 (baton->err).append("Unsupported output format " + baton->fileOut);
984 return Error();
985 }
986 }
987 } catch (vips::VError const &err) {
988 char const *what = err.what();
989 if (what && what[0]) {
990 (baton->err).append(what);
991 } else {
992 (baton->err).append("Unknown error");
993 }
994 }
995 // Clean up libvips' per-request data and threads
996 vips_error_clear();
997 vips_thread_shutdown();
998 }
999
1000 void OnOK() {
1001 Napi::Env env = Env();
1002 Napi::HandleScope scope(env);
1003
1004 // Handle warnings
1005 std::string warning = sharp::VipsWarningPop();
1006 while (!warning.empty()) {
1007 debuglog.Call({ Napi::String::New(env, warning) });
1008 warning = sharp::VipsWarningPop();
1009 }
1010
1011 if (baton->err.empty()) {
1012 int width = baton->width;
1013 int height = baton->height;
1014 if (baton->topOffsetPre != -1 && (baton->width == -1 || baton->height == -1)) {
1015 width = baton->widthPre;
1016 height = baton->heightPre;
1017 }
1018 if (baton->topOffsetPost != -1) {
1019 width = baton->widthPost;
1020 height = baton->heightPost;
1021 }
1022 // Info Object
1023 Napi::Object info = Napi::Object::New(env);
1024 info.Set("format", baton->formatOut);
1025 info.Set("width", static_cast<uint32_t>(width));
1026 info.Set("height", static_cast<uint32_t>(height));
1027 info.Set("channels", static_cast<uint32_t>(baton->channels));
1028 info.Set("premultiplied", baton->premultiplied);
1029 if (baton->hasCropOffset) {
1030 info.Set("cropOffsetLeft", static_cast<int32_t>(baton->cropOffsetLeft));
1031 info.Set("cropOffsetTop", static_cast<int32_t>(baton->cropOffsetTop));
1032 }
1033 if (baton->trimThreshold > 0.0) {
1034 info.Set("trimOffsetLeft", static_cast<int32_t>(baton->trimOffsetLeft));
1035 info.Set("trimOffsetTop", static_cast<int32_t>(baton->trimOffsetTop));
1036 }
1037
1038 if (baton->bufferOutLength > 0) {
1039 // Add buffer size to info
1040 info.Set("size", static_cast<uint32_t>(baton->bufferOutLength));
1041 // Pass ownership of output data to Buffer instance
1042 Napi::Buffer<char> data = Napi::Buffer<char>::New(env, static_cast<char*>(baton->bufferOut),
1043 baton->bufferOutLength, sharp::FreeCallback);
1044 Callback().MakeCallback(Receiver().Value(), { env.Null(), data, info });
1045 } else {
1046 // Add file size to info
1047 struct STAT64_STRUCT st;
1048 if (STAT64_FUNCTION(baton->fileOut.data(), &st) == 0) {
1049 info.Set("size", static_cast<uint32_t>(st.st_size));
1050 }
1051 Callback().MakeCallback(Receiver().Value(), { env.Null(), info });
1052 }
1053 } else {
1054 Callback().MakeCallback(Receiver().Value(), { Napi::Error::New(env, baton->err).Value() });
1055 }
1056
1057 // Delete baton
1058 delete baton->input;
1059 delete baton->boolean;
1060 for (Composite *composite : baton->composite) {
1061 delete composite->input;
1062 delete composite;
1063 }
1064 for (sharp::InputDescriptor *input : baton->joinChannelIn) {
1065 delete input;
1066 }
1067 delete baton;
1068
1069 // Decrement processing task counter
1070 g_atomic_int_dec_and_test(&sharp::counterProcess);
1071 Napi::Number queueLength = Napi::Number::New(env, static_cast<double>(sharp::counterQueue));
1072 queueListener.Call(Receiver().Value(), { queueLength });
1073 }
1074
1075 private:
1076 PipelineBaton *baton;
1077 Napi::FunctionReference debuglog;
1078 Napi::FunctionReference queueListener;
1079
1080 /*
1081 Calculate the angle of rotation and need-to-flip for the given Exif orientation
1082 By default, returns zero, i.e. no rotation.
1083 */
1084 std::tuple<VipsAngle, bool, bool>
1085 CalculateExifRotationAndFlip(int const exifOrientation) {
1086 VipsAngle rotate = VIPS_ANGLE_D0;
1087 bool flip = FALSE;
1088 bool flop = FALSE;
1089 switch (exifOrientation) {
1090 case 6: rotate = VIPS_ANGLE_D90; break;
1091 case 3: rotate = VIPS_ANGLE_D180; break;
1092 case 8: rotate = VIPS_ANGLE_D270; break;
1093 case 2: flop = TRUE; break; // flop 1
1094 case 7: flip = TRUE; rotate = VIPS_ANGLE_D90; break; // flip 6
1095 case 4: flop = TRUE; rotate = VIPS_ANGLE_D180; break; // flop 3
1096 case 5: flip = TRUE; rotate = VIPS_ANGLE_D270; break; // flip 8
1097 }
1098 return std::make_tuple(rotate, flip, flop);
1099 }
1100
1101 /*
1102 Calculate the rotation for the given angle.
1103 Supports any positive or negative angle that is a multiple of 90.
1104 */
1105 VipsAngle
1106 CalculateAngleRotation(int angle) {
1107 angle = angle % 360;
1108 if (angle < 0)
1109 angle = 360 + angle;
1110 switch (angle) {
1111 case 90: return VIPS_ANGLE_D90;
1112 case 180: return VIPS_ANGLE_D180;
1113 case 270: return VIPS_ANGLE_D270;
1114 }
1115 return VIPS_ANGLE_D0;
1116 }
1117
1118 /*
1119 Assemble the suffix argument to dzsave, which is the format (by extname)
1120 alongisde comma-separated arguments to the corresponding `formatsave` vips
1121 action.
1122 */
1123 std::string
1124 AssembleSuffixString(std::string extname, std::vector<std::pair<std::string, std::string>> options) {
1125 std::string argument;
1126 for (auto const &option : options) {
1127 if (!argument.empty()) {
1128 argument += ",";
1129 }
1130 argument += option.first + "=" + option.second;
1131 }
1132 return extname + "[" + argument + "]";
1133 }
1134
1135 /*
1136 Clear all thread-local data.
1137 */
1138 void Error() {
1139 // Clean up libvips' per-request data and threads
1140 vips_error_clear();
1141 vips_thread_shutdown();
1142 }
1143};
1144
1145/*
1146 pipeline(options, output, callback)
1147*/
1148Napi::Value pipeline(const Napi::CallbackInfo& info) {
1149 // V8 objects are converted to non-V8 types held in the baton struct
1150 PipelineBaton *baton = new PipelineBaton;
1151 Napi::Object options = info[0].As<Napi::Object>();
1152
1153 // Input
1154 baton->input = sharp::CreateInputDescriptor(options.Get("input").As<Napi::Object>());
1155 // Extract image options
1156 baton->topOffsetPre = sharp::AttrAsInt32(options, "topOffsetPre");
1157 baton->leftOffsetPre = sharp::AttrAsInt32(options, "leftOffsetPre");
1158 baton->widthPre = sharp::AttrAsInt32(options, "widthPre");
1159 baton->heightPre = sharp::AttrAsInt32(options, "heightPre");
1160 baton->topOffsetPost = sharp::AttrAsInt32(options, "topOffsetPost");
1161 baton->leftOffsetPost = sharp::AttrAsInt32(options, "leftOffsetPost");
1162 baton->widthPost = sharp::AttrAsInt32(options, "widthPost");
1163 baton->heightPost = sharp::AttrAsInt32(options, "heightPost");
1164 // Output image dimensions
1165 baton->width = sharp::AttrAsInt32(options, "width");
1166 baton->height = sharp::AttrAsInt32(options, "height");
1167 // Canvas option
1168 std::string canvas = sharp::AttrAsStr(options, "canvas");
1169 if (canvas == "crop") {
1170 baton->canvas = Canvas::CROP;
1171 } else if (canvas == "embed") {
1172 baton->canvas = Canvas::EMBED;
1173 } else if (canvas == "max") {
1174 baton->canvas = Canvas::MAX;
1175 } else if (canvas == "min") {
1176 baton->canvas = Canvas::MIN;
1177 } else if (canvas == "ignore_aspect") {
1178 baton->canvas = Canvas::IGNORE_ASPECT;
1179 }
1180 // Tint chroma
1181 baton->tintA = sharp::AttrAsDouble(options, "tintA");
1182 baton->tintB = sharp::AttrAsDouble(options, "tintB");
1183 // Composite
1184 Napi::Array compositeArray = options.Get("composite").As<Napi::Array>();
1185 for (unsigned int i = 0; i < compositeArray.Length(); i++) {
1186 Napi::Object compositeObject = compositeArray.Get(i).As<Napi::Object>();
1187 Composite *composite = new Composite;
1188 composite->input = sharp::CreateInputDescriptor(compositeObject.Get("input").As<Napi::Object>());
1189 composite->mode = static_cast<VipsBlendMode>(
1190 vips_enum_from_nick(nullptr, VIPS_TYPE_BLEND_MODE, sharp::AttrAsStr(compositeObject, "blend").data()));
1191 composite->gravity = sharp::AttrAsUint32(compositeObject, "gravity");
1192 composite->left = sharp::AttrAsInt32(compositeObject, "left");
1193 composite->top = sharp::AttrAsInt32(compositeObject, "top");
1194 composite->tile = sharp::AttrAsBool(compositeObject, "tile");
1195 composite->premultiplied = sharp::AttrAsBool(compositeObject, "premultiplied");
1196 baton->composite.push_back(composite);
1197 }
1198 // Resize options
1199 baton->withoutEnlargement = sharp::AttrAsBool(options, "withoutEnlargement");
1200 baton->position = sharp::AttrAsInt32(options, "position");
1201 baton->resizeBackground = sharp::AttrAsRgba(options, "resizeBackground");
1202 baton->kernel = sharp::AttrAsStr(options, "kernel");
1203 baton->fastShrinkOnLoad = sharp::AttrAsBool(options, "fastShrinkOnLoad");
1204 // Join Channel Options
1205 if (options.Has("joinChannelIn")) {
1206 Napi::Array joinChannelArray = options.Get("joinChannelIn").As<Napi::Array>();
1207 for (unsigned int i = 0; i < joinChannelArray.Length(); i++) {
1208 baton->joinChannelIn.push_back(
1209 sharp::CreateInputDescriptor(joinChannelArray.Get(i).As<Napi::Object>()));
1210 }
1211 }
1212 // Operators
1213 baton->flatten = sharp::AttrAsBool(options, "flatten");
1214 baton->flattenBackground = sharp::AttrAsRgba(options, "flattenBackground");
1215 baton->negate = sharp::AttrAsBool(options, "negate");
1216 baton->blurSigma = sharp::AttrAsDouble(options, "blurSigma");
1217 baton->brightness = sharp::AttrAsDouble(options, "brightness");
1218 baton->saturation = sharp::AttrAsDouble(options, "saturation");
1219 baton->hue = sharp::AttrAsInt32(options, "hue");
1220 baton->medianSize = sharp::AttrAsUint32(options, "medianSize");
1221 baton->sharpenSigma = sharp::AttrAsDouble(options, "sharpenSigma");
1222 baton->sharpenFlat = sharp::AttrAsDouble(options, "sharpenFlat");
1223 baton->sharpenJagged = sharp::AttrAsDouble(options, "sharpenJagged");
1224 baton->threshold = sharp::AttrAsInt32(options, "threshold");
1225 baton->thresholdGrayscale = sharp::AttrAsBool(options, "thresholdGrayscale");
1226 baton->trimThreshold = sharp::AttrAsDouble(options, "trimThreshold");
1227 baton->gamma = sharp::AttrAsDouble(options, "gamma");
1228 baton->gammaOut = sharp::AttrAsDouble(options, "gammaOut");
1229 baton->linearA = sharp::AttrAsDouble(options, "linearA");
1230 baton->linearB = sharp::AttrAsDouble(options, "linearB");
1231 baton->greyscale = sharp::AttrAsBool(options, "greyscale");
1232 baton->normalise = sharp::AttrAsBool(options, "normalise");
1233 baton->useExifOrientation = sharp::AttrAsBool(options, "useExifOrientation");
1234 baton->angle = sharp::AttrAsInt32(options, "angle");
1235 baton->rotationAngle = sharp::AttrAsDouble(options, "rotationAngle");
1236 baton->rotationBackground = sharp::AttrAsRgba(options, "rotationBackground");
1237 baton->rotateBeforePreExtract = sharp::AttrAsBool(options, "rotateBeforePreExtract");
1238 baton->flip = sharp::AttrAsBool(options, "flip");
1239 baton->flop = sharp::AttrAsBool(options, "flop");
1240 baton->extendTop = sharp::AttrAsInt32(options, "extendTop");
1241 baton->extendBottom = sharp::AttrAsInt32(options, "extendBottom");
1242 baton->extendLeft = sharp::AttrAsInt32(options, "extendLeft");
1243 baton->extendRight = sharp::AttrAsInt32(options, "extendRight");
1244 baton->extendBackground = sharp::AttrAsRgba(options, "extendBackground");
1245 baton->extractChannel = sharp::AttrAsInt32(options, "extractChannel");
1246
1247 baton->removeAlpha = sharp::AttrAsBool(options, "removeAlpha");
1248 baton->ensureAlpha = sharp::AttrAsBool(options, "ensureAlpha");
1249 if (options.Has("boolean")) {
1250 baton->boolean = sharp::CreateInputDescriptor(options.Get("boolean").As<Napi::Object>());
1251 baton->booleanOp = sharp::GetBooleanOperation(sharp::AttrAsStr(options, "booleanOp"));
1252 }
1253 if (options.Has("bandBoolOp")) {
1254 baton->bandBoolOp = sharp::GetBooleanOperation(sharp::AttrAsStr(options, "bandBoolOp"));
1255 }
1256 if (options.Has("convKernel")) {
1257 Napi::Object kernel = options.Get("convKernel").As<Napi::Object>();
1258 baton->convKernelWidth = sharp::AttrAsUint32(kernel, "width");
1259 baton->convKernelHeight = sharp::AttrAsUint32(kernel, "height");
1260 baton->convKernelScale = sharp::AttrAsDouble(kernel, "scale");
1261 baton->convKernelOffset = sharp::AttrAsDouble(kernel, "offset");
1262 size_t const kernelSize = static_cast<size_t>(baton->convKernelWidth * baton->convKernelHeight);
1263 baton->convKernel = std::unique_ptr<double[]>(new double[kernelSize]);
1264 Napi::Array kdata = kernel.Get("kernel").As<Napi::Array>();
1265 for (unsigned int i = 0; i < kernelSize; i++) {
1266 baton->convKernel[i] = sharp::AttrAsDouble(kdata, i);
1267 }
1268 }
1269 if (options.Has("recombMatrix")) {
1270 baton->recombMatrix = std::unique_ptr<double[]>(new double[9]);
1271 Napi::Array recombMatrix = options.Get("recombMatrix").As<Napi::Array>();
1272 for (unsigned int i = 0; i < 9; i++) {
1273 baton->recombMatrix[i] = sharp::AttrAsDouble(recombMatrix, i);
1274 }
1275 }
1276 baton->colourspace = sharp::GetInterpretation(sharp::AttrAsStr(options, "colourspace"));
1277 if (baton->colourspace == VIPS_INTERPRETATION_ERROR) {
1278 baton->colourspace = VIPS_INTERPRETATION_sRGB;
1279 }
1280 // Output
1281 baton->formatOut = sharp::AttrAsStr(options, "formatOut");
1282 baton->fileOut = sharp::AttrAsStr(options, "fileOut");
1283 baton->withMetadata = sharp::AttrAsBool(options, "withMetadata");
1284 baton->withMetadataOrientation = sharp::AttrAsUint32(options, "withMetadataOrientation");
1285 // Format-specific
1286 baton->jpegQuality = sharp::AttrAsUint32(options, "jpegQuality");
1287 baton->jpegProgressive = sharp::AttrAsBool(options, "jpegProgressive");
1288 baton->jpegChromaSubsampling = sharp::AttrAsStr(options, "jpegChromaSubsampling");
1289 baton->jpegTrellisQuantisation = sharp::AttrAsBool(options, "jpegTrellisQuantisation");
1290 baton->jpegQuantisationTable = sharp::AttrAsUint32(options, "jpegQuantisationTable");
1291 baton->jpegOvershootDeringing = sharp::AttrAsBool(options, "jpegOvershootDeringing");
1292 baton->jpegOptimiseScans = sharp::AttrAsBool(options, "jpegOptimiseScans");
1293 baton->jpegOptimiseCoding = sharp::AttrAsBool(options, "jpegOptimiseCoding");
1294 baton->pngProgressive = sharp::AttrAsBool(options, "pngProgressive");
1295 baton->pngCompressionLevel = sharp::AttrAsUint32(options, "pngCompressionLevel");
1296 baton->pngAdaptiveFiltering = sharp::AttrAsBool(options, "pngAdaptiveFiltering");
1297 baton->pngPalette = sharp::AttrAsBool(options, "pngPalette");
1298 baton->pngQuality = sharp::AttrAsUint32(options, "pngQuality");
1299 baton->pngColours = sharp::AttrAsUint32(options, "pngColours");
1300 baton->pngDither = sharp::AttrAsDouble(options, "pngDither");
1301 baton->webpQuality = sharp::AttrAsUint32(options, "webpQuality");
1302 baton->webpAlphaQuality = sharp::AttrAsUint32(options, "webpAlphaQuality");
1303 baton->webpLossless = sharp::AttrAsBool(options, "webpLossless");
1304 baton->webpNearLossless = sharp::AttrAsBool(options, "webpNearLossless");
1305 baton->webpSmartSubsample = sharp::AttrAsBool(options, "webpSmartSubsample");
1306 baton->webpReductionEffort = sharp::AttrAsUint32(options, "webpReductionEffort");
1307 baton->tiffQuality = sharp::AttrAsUint32(options, "tiffQuality");
1308 baton->tiffPyramid = sharp::AttrAsBool(options, "tiffPyramid");
1309 baton->tiffSquash = sharp::AttrAsBool(options, "tiffSquash");
1310 baton->tiffTile = sharp::AttrAsBool(options, "tiffTile");
1311 baton->tiffTileWidth = sharp::AttrAsUint32(options, "tiffTileWidth");
1312 baton->tiffTileHeight = sharp::AttrAsUint32(options, "tiffTileHeight");
1313 baton->tiffXres = sharp::AttrAsDouble(options, "tiffXres");
1314 baton->tiffYres = sharp::AttrAsDouble(options, "tiffYres");
1315 // tiff compression options
1316 baton->tiffCompression = static_cast<VipsForeignTiffCompression>(
1317 vips_enum_from_nick(nullptr, VIPS_TYPE_FOREIGN_TIFF_COMPRESSION,
1318 sharp::AttrAsStr(options, "tiffCompression").data()));
1319 baton->tiffPredictor = static_cast<VipsForeignTiffPredictor>(
1320 vips_enum_from_nick(nullptr, VIPS_TYPE_FOREIGN_TIFF_PREDICTOR,
1321 sharp::AttrAsStr(options, "tiffPredictor").data()));
1322 baton->heifQuality = sharp::AttrAsUint32(options, "heifQuality");
1323 baton->heifLossless = sharp::AttrAsBool(options, "heifLossless");
1324 baton->heifCompression = static_cast<VipsForeignHeifCompression>(
1325 vips_enum_from_nick(nullptr, VIPS_TYPE_FOREIGN_HEIF_COMPRESSION,
1326 sharp::AttrAsStr(options, "heifCompression").data()));
1327 // Tile output
1328 baton->tileSize = sharp::AttrAsUint32(options, "tileSize");
1329 baton->tileOverlap = sharp::AttrAsUint32(options, "tileOverlap");
1330 baton->tileAngle = sharp::AttrAsInt32(options, "tileAngle");
1331 baton->tileBackground = sharp::AttrAsRgba(options, "tileBackground");
1332 baton->tileSkipBlanks = sharp::AttrAsInt32(options, "tileSkipBlanks");
1333 baton->tileContainer = static_cast<VipsForeignDzContainer>(
1334 vips_enum_from_nick(nullptr, VIPS_TYPE_FOREIGN_DZ_CONTAINER,
1335 sharp::AttrAsStr(options, "tileContainer").data()));
1336 baton->tileLayout = static_cast<VipsForeignDzLayout>(
1337 vips_enum_from_nick(nullptr, VIPS_TYPE_FOREIGN_DZ_LAYOUT,
1338 sharp::AttrAsStr(options, "tileLayout").data()));
1339 baton->tileFormat = sharp::AttrAsStr(options, "tileFormat");
1340 baton->tileDepth = static_cast<VipsForeignDzDepth>(
1341 vips_enum_from_nick(nullptr, VIPS_TYPE_FOREIGN_DZ_DEPTH,
1342 sharp::AttrAsStr(options, "tileDepth").data()));
1343
1344 // Force random access for certain operations
1345 if (baton->input->access == VIPS_ACCESS_SEQUENTIAL) {
1346 if (
1347 baton->trimThreshold > 0.0 ||
1348 baton->normalise ||
1349 baton->position == 16 || baton->position == 17 ||
1350 baton->angle % 360 != 0 ||
1351 fmod(baton->rotationAngle, 360.0) != 0.0 ||
1352 baton->useExifOrientation
1353 ) {
1354 baton->input->access = VIPS_ACCESS_RANDOM;
1355 }
1356 }
1357
1358 // Function to notify of libvips warnings
1359 Napi::Function debuglog = options.Get("debuglog").As<Napi::Function>();
1360
1361 // Function to notify of queue length changes
1362 Napi::Function queueListener = options.Get("queueListener").As<Napi::Function>();
1363
1364 // Join queue for worker thread
1365 Napi::Function callback = info[1].As<Napi::Function>();
1366 PipelineWorker *worker = new PipelineWorker(callback, baton, debuglog, queueListener);
1367 worker->Receiver().Set("options", options);
1368 worker->Queue();
1369
1370 // Increment queued task counter
1371 g_atomic_int_inc(&sharp::counterQueue);
1372 Napi::Number queueLength = Napi::Number::New(info.Env(), static_cast<double>(sharp::counterQueue));
1373 queueListener.Call(info.This(), { queueLength });
1374
1375 return info.Env().Undefined();
1376}