utility.js 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. // Copyright 2013 Lovell Fuller and others.
  2. // SPDX-License-Identifier: Apache-2.0
  3. 'use strict';
  4. const events = require('node:events');
  5. const detectLibc = require('detect-libc');
  6. const is = require('./is');
  7. const { runtimePlatformArch } = require('./libvips');
  8. const sharp = require('./sharp');
  9. const runtimePlatform = runtimePlatformArch();
  10. const libvipsVersion = sharp.libvipsVersion();
  11. /**
  12. * An Object containing nested boolean values representing the available input and output formats/methods.
  13. * @member
  14. * @example
  15. * console.log(sharp.format);
  16. * @returns {Object}
  17. */
  18. const format = sharp.format();
  19. format.heif.output.alias = ['avif', 'heic'];
  20. format.jpeg.output.alias = ['jpe', 'jpg'];
  21. format.tiff.output.alias = ['tif'];
  22. format.jp2k.output.alias = ['j2c', 'j2k', 'jp2', 'jpx'];
  23. /**
  24. * An Object containing the available interpolators and their proper values
  25. * @readonly
  26. * @enum {string}
  27. */
  28. const interpolators = {
  29. /** [Nearest neighbour interpolation](http://en.wikipedia.org/wiki/Nearest-neighbor_interpolation). Suitable for image enlargement only. */
  30. nearest: 'nearest',
  31. /** [Bilinear interpolation](http://en.wikipedia.org/wiki/Bilinear_interpolation). Faster than bicubic but with less smooth results. */
  32. bilinear: 'bilinear',
  33. /** [Bicubic interpolation](http://en.wikipedia.org/wiki/Bicubic_interpolation) (the default). */
  34. bicubic: 'bicubic',
  35. /** [LBB interpolation](https://github.com/libvips/libvips/blob/master/libvips/resample/lbb.cpp#L100). Prevents some "[acutance](http://en.wikipedia.org/wiki/Acutance)" but typically reduces performance by a factor of 2. */
  36. locallyBoundedBicubic: 'lbb',
  37. /** [Nohalo interpolation](http://eprints.soton.ac.uk/268086/). Prevents acutance but typically reduces performance by a factor of 3. */
  38. nohalo: 'nohalo',
  39. /** [VSQBS interpolation](https://github.com/libvips/libvips/blob/master/libvips/resample/vsqbs.cpp#L48). Prevents "staircasing" when enlarging. */
  40. vertexSplitQuadraticBasisSpline: 'vsqbs'
  41. };
  42. /**
  43. * An Object containing the version numbers of sharp, libvips
  44. * and (when using prebuilt binaries) its dependencies.
  45. *
  46. * @member
  47. * @example
  48. * console.log(sharp.versions);
  49. */
  50. let versions = {
  51. vips: libvipsVersion.semver
  52. };
  53. /* istanbul ignore next */
  54. if (!libvipsVersion.isGlobal) {
  55. if (!libvipsVersion.isWasm) {
  56. try {
  57. versions = require(`@img/sharp-${runtimePlatform}/versions`);
  58. } catch (_) {
  59. try {
  60. versions = require(`@img/sharp-libvips-${runtimePlatform}/versions`);
  61. } catch (_) {}
  62. }
  63. } else {
  64. try {
  65. versions = require('@img/sharp-wasm32/versions');
  66. } catch (_) {}
  67. }
  68. }
  69. versions.sharp = require('../package.json').version;
  70. /* istanbul ignore next */
  71. if (versions.heif && format.heif) {
  72. // Prebuilt binaries provide AV1
  73. format.heif.input.fileSuffix = ['.avif'];
  74. format.heif.output.alias = ['avif'];
  75. }
  76. /**
  77. * Gets or, when options are provided, sets the limits of _libvips'_ operation cache.
  78. * Existing entries in the cache will be trimmed after any change in limits.
  79. * This method always returns cache statistics,
  80. * useful for determining how much working memory is required for a particular task.
  81. *
  82. * @example
  83. * const stats = sharp.cache();
  84. * @example
  85. * sharp.cache( { items: 200 } );
  86. * sharp.cache( { files: 0 } );
  87. * sharp.cache(false);
  88. *
  89. * @param {Object|boolean} [options=true] - Object with the following attributes, or boolean where true uses default cache settings and false removes all caching
  90. * @param {number} [options.memory=50] - is the maximum memory in MB to use for this cache
  91. * @param {number} [options.files=20] - is the maximum number of files to hold open
  92. * @param {number} [options.items=100] - is the maximum number of operations to cache
  93. * @returns {Object}
  94. */
  95. function cache (options) {
  96. if (is.bool(options)) {
  97. if (options) {
  98. // Default cache settings of 50MB, 20 files, 100 items
  99. return sharp.cache(50, 20, 100);
  100. } else {
  101. return sharp.cache(0, 0, 0);
  102. }
  103. } else if (is.object(options)) {
  104. return sharp.cache(options.memory, options.files, options.items);
  105. } else {
  106. return sharp.cache();
  107. }
  108. }
  109. cache(true);
  110. /**
  111. * Gets or, when a concurrency is provided, sets
  112. * the maximum number of threads _libvips_ should use to process _each image_.
  113. * These are from a thread pool managed by glib,
  114. * which helps avoid the overhead of creating new threads.
  115. *
  116. * This method always returns the current concurrency.
  117. *
  118. * The default value is the number of CPU cores,
  119. * except when using glibc-based Linux without jemalloc,
  120. * where the default is `1` to help reduce memory fragmentation.
  121. *
  122. * A value of `0` will reset this to the number of CPU cores.
  123. *
  124. * Some image format libraries spawn additional threads,
  125. * e.g. libaom manages its own 4 threads when encoding AVIF images,
  126. * and these are independent of the value set here.
  127. *
  128. * The maximum number of images that sharp can process in parallel
  129. * is controlled by libuv's `UV_THREADPOOL_SIZE` environment variable,
  130. * which defaults to 4.
  131. *
  132. * https://nodejs.org/api/cli.html#uv_threadpool_sizesize
  133. *
  134. * For example, by default, a machine with 8 CPU cores will process
  135. * 4 images in parallel and use up to 8 threads per image,
  136. * so there will be up to 32 concurrent threads.
  137. *
  138. * @example
  139. * const threads = sharp.concurrency(); // 4
  140. * sharp.concurrency(2); // 2
  141. * sharp.concurrency(0); // 4
  142. *
  143. * @param {number} [concurrency]
  144. * @returns {number} concurrency
  145. */
  146. function concurrency (concurrency) {
  147. return sharp.concurrency(is.integer(concurrency) ? concurrency : null);
  148. }
  149. /* istanbul ignore next */
  150. if (detectLibc.familySync() === detectLibc.GLIBC && !sharp._isUsingJemalloc()) {
  151. // Reduce default concurrency to 1 when using glibc memory allocator
  152. sharp.concurrency(1);
  153. } else if (detectLibc.familySync() === detectLibc.MUSL && sharp.concurrency() === 1024) {
  154. // Reduce default concurrency when musl thread over-subscription detected
  155. sharp.concurrency(require('node:os').availableParallelism());
  156. }
  157. /**
  158. * An EventEmitter that emits a `change` event when a task is either:
  159. * - queued, waiting for _libuv_ to provide a worker thread
  160. * - complete
  161. * @member
  162. * @example
  163. * sharp.queue.on('change', function(queueLength) {
  164. * console.log('Queue contains ' + queueLength + ' task(s)');
  165. * });
  166. */
  167. const queue = new events.EventEmitter();
  168. /**
  169. * Provides access to internal task counters.
  170. * - queue is the number of tasks this module has queued waiting for _libuv_ to provide a worker thread from its pool.
  171. * - process is the number of resize tasks currently being processed.
  172. *
  173. * @example
  174. * const counters = sharp.counters(); // { queue: 2, process: 4 }
  175. *
  176. * @returns {Object}
  177. */
  178. function counters () {
  179. return sharp.counters();
  180. }
  181. /**
  182. * Get and set use of SIMD vector unit instructions.
  183. * Requires libvips to have been compiled with highway support.
  184. *
  185. * Improves the performance of `resize`, `blur` and `sharpen` operations
  186. * by taking advantage of the SIMD vector unit of the CPU, e.g. Intel SSE and ARM NEON.
  187. *
  188. * @example
  189. * const simd = sharp.simd();
  190. * // simd is `true` if the runtime use of highway is currently enabled
  191. * @example
  192. * const simd = sharp.simd(false);
  193. * // prevent libvips from using highway at runtime
  194. *
  195. * @param {boolean} [simd=true]
  196. * @returns {boolean}
  197. */
  198. function simd (simd) {
  199. return sharp.simd(is.bool(simd) ? simd : null);
  200. }
  201. /**
  202. * Block libvips operations at runtime.
  203. *
  204. * This is in addition to the `VIPS_BLOCK_UNTRUSTED` environment variable,
  205. * which when set will block all "untrusted" operations.
  206. *
  207. * @since 0.32.4
  208. *
  209. * @example <caption>Block all TIFF input.</caption>
  210. * sharp.block({
  211. * operation: ['VipsForeignLoadTiff']
  212. * });
  213. *
  214. * @param {Object} options
  215. * @param {Array<string>} options.operation - List of libvips low-level operation names to block.
  216. */
  217. function block (options) {
  218. if (is.object(options)) {
  219. if (Array.isArray(options.operation) && options.operation.every(is.string)) {
  220. sharp.block(options.operation, true);
  221. } else {
  222. throw is.invalidParameterError('operation', 'Array<string>', options.operation);
  223. }
  224. } else {
  225. throw is.invalidParameterError('options', 'object', options);
  226. }
  227. }
  228. /**
  229. * Unblock libvips operations at runtime.
  230. *
  231. * This is useful for defining a list of allowed operations.
  232. *
  233. * @since 0.32.4
  234. *
  235. * @example <caption>Block all input except WebP from the filesystem.</caption>
  236. * sharp.block({
  237. * operation: ['VipsForeignLoad']
  238. * });
  239. * sharp.unblock({
  240. * operation: ['VipsForeignLoadWebpFile']
  241. * });
  242. *
  243. * @example <caption>Block all input except JPEG and PNG from a Buffer or Stream.</caption>
  244. * sharp.block({
  245. * operation: ['VipsForeignLoad']
  246. * });
  247. * sharp.unblock({
  248. * operation: ['VipsForeignLoadJpegBuffer', 'VipsForeignLoadPngBuffer']
  249. * });
  250. *
  251. * @param {Object} options
  252. * @param {Array<string>} options.operation - List of libvips low-level operation names to unblock.
  253. */
  254. function unblock (options) {
  255. if (is.object(options)) {
  256. if (Array.isArray(options.operation) && options.operation.every(is.string)) {
  257. sharp.block(options.operation, false);
  258. } else {
  259. throw is.invalidParameterError('operation', 'Array<string>', options.operation);
  260. }
  261. } else {
  262. throw is.invalidParameterError('options', 'object', options);
  263. }
  264. }
  265. /**
  266. * Decorate the Sharp class with utility-related functions.
  267. * @private
  268. */
  269. module.exports = function (Sharp) {
  270. Sharp.cache = cache;
  271. Sharp.concurrency = concurrency;
  272. Sharp.counters = counters;
  273. Sharp.simd = simd;
  274. Sharp.format = format;
  275. Sharp.interpolators = interpolators;
  276. Sharp.versions = versions;
  277. Sharp.queue = queue;
  278. Sharp.block = block;
  279. Sharp.unblock = unblock;
  280. };