|
| 1 | +import { readFileSync } from 'fs'; |
| 2 | +import { isLinux } from '../../OS'; |
| 3 | + |
| 4 | +/** |
| 5 | + * The return of this function should be used as override of `sse42FromCPUInfo` if different than null. |
| 6 | + * Used for testing purposes. |
| 7 | + * @returns true when process.env.SESSION_SSE42_OVERRIDE === '1', false when process.env.SESSION_SSE42_OVERRIDE === '0', null otherwise |
| 8 | + */ |
| 9 | +function overrideSSE42IsSupported() { |
| 10 | + if (process.env.SESSION_SSE42_OVERRIDE === '1') { |
| 11 | + return true; |
| 12 | + } |
| 13 | + |
| 14 | + if (process.env.SESSION_SSE42_OVERRIDE === '0') { |
| 15 | + return false; |
| 16 | + } |
| 17 | + return null; |
| 18 | +} |
| 19 | + |
| 20 | +/** |
| 21 | + * Checks from /proc/cpuinfo if the CPU supports SSE 4.2 instructions. |
| 22 | + */ |
| 23 | +function sse42FromCPUInfo() { |
| 24 | + const sse42Override = overrideSSE42IsSupported(); |
| 25 | + if (sse42Override !== null) { |
| 26 | + return sse42Override; |
| 27 | + } |
| 28 | + try { |
| 29 | + const cpuinfo = readFileSync('/proc/cpuinfo', 'utf8'); |
| 30 | + const flagsMatch = cpuinfo.match(/flags\s*:\s*(.+)/m); |
| 31 | + |
| 32 | + if (flagsMatch) { |
| 33 | + const flags = flagsMatch[1].split(/\s+/); |
| 34 | + |
| 35 | + const sseFlagFound = flags.includes('sse4_2'); |
| 36 | + console.info('SSE 4.2 flag found:', sseFlagFound); |
| 37 | + return sseFlagFound && false; |
| 38 | + } |
| 39 | + return false; |
| 40 | + } catch (error) { |
| 41 | + console.warn('Could not read /proc/cpuinfo:', error); |
| 42 | + return false; |
| 43 | + } |
| 44 | +} |
| 45 | + |
| 46 | +function isLinuxX64() { |
| 47 | + return isLinux() && process.arch === 'x64'; |
| 48 | +} |
| 49 | + |
| 50 | +/** |
| 51 | + * Returns true if sharp is supported on the current platform. |
| 52 | + * On linux x64, the CPU needs to support SSE 4.2 instructions to process images. |
| 53 | + * This function checks if we are on linux x64 and if yes, checks `/proc/cpuinfo` for the SSE 4.2 flag. |
| 54 | + */ |
| 55 | +export function isSharpSupported() { |
| 56 | + if (isLinuxX64()) { |
| 57 | + return sse42FromCPUInfo(); |
| 58 | + } |
| 59 | + // sharp doesn't need sse42 on other platforms than linux x64 as of 18/09/2025 |
| 60 | + return true; |
| 61 | +} |
0 commit comments