ferrisma-libwebp 0.1.0

A mechanical Rust port of libwebp, the WebP reference implementation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
// libwebp v1.6.0, src/dsp/cpu.c:
//
// Copyright 2011 Google Inc. All Rights Reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the COPYING file in the root of the source
// tree. An additional intellectual property rights grant can be found
// in the file PATENTS. All contributing project authors may
// be found in the AUTHORS file in the root of the source tree.
// -----------------------------------------------------------------------------
//
// CPU detection
//
// Author: Christian Duvivier (cduvivier@google.com)

// libwebp v1.6.0, src/dsp/cpu.h:
//
// Copyright 2022 Google Inc. All Rights Reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the COPYING file in the root of the source
// tree. An additional intellectual property rights grant can be found
// in the file PATENTS. All contributing project authors may
// be found in the AUTHORS file in the root of the source tree.
// -----------------------------------------------------------------------------
//
//   CPU detection functions and macros.
//
// Author: Skal (pascal.massimino@gmail.com)

//! Translation of `src/dsp/cpu.c` and `src/dsp/cpu.h` from libwebp v1.6.0.
//!
//! Work package: WP4 (pixel ops).
//!
//! `VP8GetCPUInfo` is a query, not a function pointer (ADR 0003). On x86 it
//! answers for the running CPU as `x86CPUInfo` does. On 64-bit ARM with the
//! `simd` feature it answers `kNEON` as `armCPUInfo` does in upstream's NEON
//! build (WP20, ADR 0008): upstream defines `WEBP_HAVE_NEON` there, assigns
//! `armCPUInfo`, and without `WEBP_HAVE_NEON_RTCD`, which only 32-bit ARM
//! builds use for their `/proc/cpuinfo` test, the query reports NEON and
//! nothing else. Elsewhere, and in the scalar build, the reference
//! configuration leaves the pointer NULL, and the query answers `false`.
//! The `WEBP_DSP_INIT` guards of `cpu.h` have no counterpart: they protect
//! pointer assignments, which ADR 0003 omits. The compile-time macros of
//! `cpu.h` (`WEBP_USE_SSE2` and the other `WEBP_HAVE_*` tests, the sanitizer
//! and byte-order macros) become `cfg` or are not compiled in the reference
//! configuration, which defines no SIMD, uses no sanitizer and is
//! little-endian.
//!
//! # Checks not applicable
//!
//! These checks do not apply, or cannot be made, with the reason:
//!
//! 1. **x86 query on an arm64 host.** `x86cpu_info`, `check_slow_model` and the
//!    x86 branch of `vp8_get_cpu_info` are compiled only on x86 targets. On an
//!    arm64 host the x86 test `slow_model_table_matches_the_c_helper` and the
//!    x86 answers of `cpu_query_matches_the_c_query` are not run. They are
//!    type-checked for `x86_64-unknown-linux-gnu` with Clippy, and they run on
//!    the Linux x86-64 CI host (ADR 0002).
//! 2. **Platform queries.** `AndroidCPUInfo`, `armCPUInfo`, `wasmCPUInfo` and
//!    `mipsCPUInfo` (`cpu.c`) are selected only by macros the reference
//!    configuration does not define.
//! 3. **`WEBP_DSP_INIT`, `WEBP_DSP_INIT_FUNC` and `WEBP_DSP_INIT_STUB`** are
//!    the once-only guards around the `Init` functions and the stubs that
//!    expose a symbol per module. No counterpart is needed (ADR 0003).
//! 4. **Preprocessor and sanitizer macros** (`LOCAL_GCC_*`, `LOCAL_CLANG_*`,
//!    `WEBP_NEON_*`, `WEBP_TSAN_IGNORE_FUNCTION`, `WEBP_UBSAN_*`, `WEBP_MSAN`,
//!    `WEBP_OFFSET_PTR`, `WEBP_RESTRICT`, `__has_builtin`): compiler and
//!    sanitizer plumbing that Rust expresses with `cfg` or has no need for.

#[cfg(target_arch = "x86")]
use core::arch::x86::__cpuid_count;
#[cfg(target_arch = "x86_64")]
use core::arch::x86_64::__cpuid_count;
use std::sync::atomic::{AtomicU64, Ordering};

// upstream: src/dsp/cpu.h CPUFeature
/// A CPU feature that the query reports on. The C enumeration has no negative
/// values, so its type is `unsigned int` (ADR 0003).
#[must_use]
#[repr(transparent)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct CPUFeature(pub u32);

#[expect(
    non_upper_case_globals,
    reason = "C enumerator names such as kSSE2 keep their case"
)]
impl CPUFeature {
    // upstream: src/dsp/cpu.h kSSE2
    pub const kSSE2: Self = Self(0);
    // upstream: src/dsp/cpu.h kSSE3
    pub const kSSE3: Self = Self(1);
    // upstream: src/dsp/cpu.h kSlowSSSE3
    pub const kSlowSSSE3: Self = Self(2);
    // upstream: src/dsp/cpu.h kSSE4_1
    pub const kSSE4_1: Self = Self(3);
    // upstream: src/dsp/cpu.h kAVX
    pub const kAVX: Self = Self(4);
    // upstream: src/dsp/cpu.h kAVX2
    pub const kAVX2: Self = Self(5);
    // upstream: src/dsp/cpu.h kNEON
    pub const kNEON: Self = Self(6);
    // upstream: src/dsp/cpu.h kMIPS32
    pub const kMIPS32: Self = Self(7);
    // upstream: src/dsp/cpu.h kMIPSdspR2
    pub const kMIPSdspR2: Self = Self(8);
    // upstream: src/dsp/cpu.h kMSA
    pub const kMSA: Self = Self(9);
}

// upstream: src/dsp/cpu.h VP8CPUInfo
/// The signature of the feature query: whether the CPU supports the feature.
pub type VP8CPUInfo = fn(CPUFeature) -> bool;

// upstream: src/dsp/cpu.c GetCPUInfo
/// Runs `cpuid` with `info_type` in EAX and ECX zero, and returns EAX, EBX,
/// ECX and EDX.
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
fn get_cpu_info(info_type: u32) -> [u32; 4] {
    let result = __cpuid_count(info_type, 0);
    [result.eax, result.ebx, result.ecx, result.edx]
}

// upstream: src/dsp/cpu.c CheckSlowModel
/// Whether the display model in `info`, the EAX value of `cpuid` leaf 1, is
/// one of the Intel models with the longer latencies of `bsr` and of some
/// SSSE3 instructions such as `pshufb`.
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
#[must_use]
pub fn check_slow_model(info: u32) -> bool {
    // Table listing display models with longer latencies for the bsr instruction
    // (ie 2 cycles vs 10/16 cycles) and some SSSE3 instructions like pshufb.
    // Refer to Intel 64 and IA-32 Architectures Optimization Reference Manual.
    const SLOW_MODELS: [u32; 6] = [
        0x37, 0x4a, 0x4d, // Silvermont Microarchitecture
        0x1c, 0x26, 0x27, // Atom Microarchitecture
    ];
    let model = ((info & 0xf_0000) >> 12) | ((info >> 4) & 0xf);
    let family = (info >> 8) & 0xf;
    if family == 0x06 {
        return SLOW_MODELS.contains(&model);
    }
    false
}

// upstream: src/dsp/cpu.c x86CPUInfo
/// The x86 query. The reference configuration installs it on x86 targets.
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
#[expect(
    clippy::cast_possible_wrap,
    reason = "cpuid returns the highest leaf in the EAX of the C int that is compared with 1 and 7"
)]
fn x86cpu_info(feature: CPUFeature) -> bool {
    const VENDOR_ID_INTEL_EBX: u32 = 0x756e_6547; // uneG
    const VENDOR_ID_INTEL_EDX: u32 = 0x4965_6e69; // Ieni
    const VENDOR_ID_INTEL_ECX: u32 = 0x6c65_746e; // letn
    // get the highest feature value cpuid supports
    let cpu_info = get_cpu_info(0);
    let max_cpuid_value = cpu_info[0] as i32;
    if max_cpuid_value < 1 {
        return false;
    }
    let is_intel = cpu_info[1] == VENDOR_ID_INTEL_EBX
        && cpu_info[2] == VENDOR_ID_INTEL_ECX
        && cpu_info[3] == VENDOR_ID_INTEL_EDX; // genuine Intel?

    let cpu_info = get_cpu_info(1);
    if feature == CPUFeature::kSSE2 {
        return cpu_info[3] & (1 << 26) != 0;
    }
    if feature == CPUFeature::kSSE3 {
        return cpu_info[2] & (1 << 0) != 0;
    }
    if feature == CPUFeature::kSlowSSSE3 {
        if is_intel && cpu_info[2] & (1 << 9) != 0 {
            // SSSE3?
            return check_slow_model(cpu_info[0]);
        }
        return false;
    }
    if feature == CPUFeature::kSSE4_1 {
        return cpu_info[2] & (1 << 19) != 0;
    }
    if feature == CPUFeature::kAVX {
        // bits 27 (OSXSAVE) & 28 (256-bit AVX)
        if cpu_info[2] & 0x1800_0000 == 0x1800_0000 {
            // XMM state and YMM state enabled by the OS. The C code reads XCR0
            // with xgetbv and tests bits 1 and 2; the standard library's AVX
            // detection performs that same test, and it is safe Rust.
            return std::is_x86_feature_detected!("avx");
        }
    }
    if feature == CPUFeature::kAVX2 && x86cpu_info(CPUFeature::kAVX) && max_cpuid_value >= 7 {
        let cpu_info = get_cpu_info(7);
        return cpu_info[1] & (1 << 5) != 0;
    }
    false
}

// upstream: src/dsp/cpu.c VP8GetCPUInfo
/// Reports whether the running CPU supports `feature`.
///
/// On x86 the answer comes from `cpuid`, as in `x86CPUInfo`. On other targets
/// the reference configuration has no query, `VP8GetCPUInfo` is NULL, and the
/// answer is `false` for every feature. The NULL pointer itself exists only at
/// the C ABI (ADR 0004).
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
#[must_use]
pub fn vp8_get_cpu_info(feature: CPUFeature) -> bool {
    #[cfg(feature = "oracle")]
    if !gate_level_allows(feature) {
        return false;
    }
    x86cpu_info(feature)
}

/// Whether the differential gate's instruction-set level lets the query
/// report `feature` (ADR 0008). The environment variable `LIBWEBP_SIMD_LEVEL`
/// names the level of a `tools/check.py --oracle` mode: unset, `avx2` and
/// `neon` report every feature as the CPU does; `sse41` reports nothing above
/// `kSSE4_1`; `sse2` reports `kSSE2` alone. The oracle's
/// `tools/oracle/probe_support/simd_level.c` wraps upstream's `VP8GetCPUInfo`
/// with the same rule before `main`, so both sides select the variants of the
/// same level. Compiled only with the `oracle` feature, which no ordinary
/// build enables; no C counterpart.
#[cfg(all(feature = "oracle", any(target_arch = "x86", target_arch = "x86_64")))]
fn gate_level_allows(feature: CPUFeature) -> bool {
    match std::env::var("LIBWEBP_SIMD_LEVEL").as_deref() {
        Err(_) | Ok("" | "avx2" | "neon") => true,
        Ok("sse41") => feature <= CPUFeature::kSSE4_1,
        Ok("sse2") => feature == CPUFeature::kSSE2,
        Ok(level) => panic!("LIBWEBP_SIMD_LEVEL={level}: unknown level"),
    }
}

// upstream: src/dsp/cpu.c armCPUInfo
/// The ARM query of upstream's NEON build: NEON is reported, every other
/// feature is not. `WEBP_HAVE_NEON_RTCD`, the run-time test of 32-bit ARM
/// Linux builds, is not defined for 64-bit ARM.
#[cfg(all(feature = "simd", target_arch = "aarch64"))]
fn arm_cpu_info(feature: CPUFeature) -> bool {
    feature == CPUFeature::kNEON
}

// upstream: src/dsp/cpu.c VP8GetCPUInfo
/// Reports whether the running CPU supports `feature`. On 64-bit ARM with the
/// `simd` feature the answer is `armCPUInfo`'s: NEON only, as in upstream's
/// NEON build (ADR 0008).
#[cfg(all(feature = "simd", target_arch = "aarch64"))]
#[must_use]
pub fn vp8_get_cpu_info(feature: CPUFeature) -> bool {
    arm_cpu_info(feature)
}

// upstream: src/dsp/cpu.c VP8GetCPUInfo
/// Reports whether the running CPU supports `feature`. Without an x86 query,
/// the reference configuration's NULL pointer reports no feature.
#[cfg(not(any(
    target_arch = "x86",
    target_arch = "x86_64",
    all(feature = "simd", target_arch = "aarch64")
)))]
#[must_use]
pub fn vp8_get_cpu_info(_feature: CPUFeature) -> bool {
    false
}

//------------------------------------------------------------------------------
// Runtime selection of the SIMD variants (ADR 0008). No C counterpart as a
// function: C's `WEBP_DSP_INIT` re-runs an `Init` function when `VP8GetCPUInfo`
// changed since its last run, and the `Init` function assigns the dispatch
// pointers from the query's answers.

/// The CPU features that the dispatch functions select the SIMD variants by
/// (ADR 0008). Each x86 flag answers as the `Init` functions' queries do,
/// through the query behind the C ABI's `VP8GetCPUInfo` pointer: `false` for a
/// `NULL` pointer (`-noasm`), `cpuid` for the translation's own query, and the
/// caller's function for a query it installed. `neon` is true on 64-bit ARM
/// whatever the pointer says, where upstream compiles the NEON code in and
/// omits the C code it replaces (`WEBP_NEON_OMIT_C_CODE`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[expect(
    clippy::struct_excessive_bools,
    reason = "one flag per CPU feature, as the C query answers them"
)]
pub struct Features {
    /// `VP8GetCPUInfo(kSSE2)`.
    pub sse2: bool,
    /// `VP8GetCPUInfo(kSSE3)`.
    pub sse3: bool,
    /// `VP8GetCPUInfo(kSlowSSSE3)`.
    pub slow_ssse3: bool,
    /// `VP8GetCPUInfo(kSSE4_1)`.
    pub sse4_1: bool,
    /// `VP8GetCPUInfo(kAVX)`.
    pub avx: bool,
    /// `VP8GetCPUInfo(kAVX2)`.
    pub avx2: bool,
    /// NEON, always on 64-bit ARM.
    pub neon: bool,
    /// `VP8GetCPUInfo(kNEON)`, `false` for a `NULL` pointer. `VP8EncDspCostInit`
    /// (`cost.c`) is the one `Init` function that selects its NEON variants by
    /// the query alone, without `WEBP_NEON_OMIT_C_CODE`, so `-noasm` turns them
    /// off; every other selection uses [`Features::neon`] (WP20, ADR 0008).
    pub query_neon: bool,
}

impl Features {
    const SSE2: u32 = 1 << 0;
    const SSE3: u32 = 1 << 1;
    const SLOW_SSSE3: u32 = 1 << 2;
    const SSE4_1: u32 = 1 << 3;
    const AVX: u32 = 1 << 4;
    const AVX2: u32 = 1 << 5;
    const NEON: u32 = 1 << 6;
    const QUERY_NEON: u32 = 1 << 7;
    /// Marks a computed record in the cache word.
    const VALID: u32 = 1 << 31;

    fn bits(self) -> u32 {
        let mut bits = 0;
        for (flag, bit) in [
            (self.sse2, Self::SSE2),
            (self.sse3, Self::SSE3),
            (self.slow_ssse3, Self::SLOW_SSSE3),
            (self.sse4_1, Self::SSE4_1),
            (self.avx, Self::AVX),
            (self.avx2, Self::AVX2),
            (self.neon, Self::NEON),
            (self.query_neon, Self::QUERY_NEON),
        ] {
            if flag {
                bits |= bit;
            }
        }
        bits
    }

    #[inline]
    fn from_bits(bits: u32) -> Self {
        Self {
            sse2: bits & Self::SSE2 != 0,
            sse3: bits & Self::SSE3 != 0,
            slow_ssse3: bits & Self::SLOW_SSSE3 != 0,
            sse4_1: bits & Self::SSE4_1 != 0,
            avx: bits & Self::AVX != 0,
            avx2: bits & Self::AVX2 != 0,
            neon: bits & Self::NEON != 0,
            query_neon: bits & Self::QUERY_NEON != 0,
        }
    }
}

/// The cached record: the token of the `VP8GetCPUInfo` pointer it was computed
/// for in the high word, the feature bits with [`Features::VALID`] in the low
/// word. One atomic word, so a reader never pairs a token with another
/// pointer's bits.
static FEATURES_CACHE: AtomicU64 = AtomicU64::new(0);

/// The features the dispatch functions select by (ADR 0008), computed on the
/// first call and again whenever the C ABI's `VP8GetCPUInfo` pointer has
/// changed since, as `WEBP_DSP_INIT` re-runs the `Init` functions then.
///
/// The test of the cached record is inlined into each dispatch function, so a
/// call with an unchanged pointer reads the pointer and the cache word and
/// tests the one flag it selects by, where upstream reads its dispatch
/// pointer; the computation runs out of line ([`refresh_features`]).
#[inline]
#[must_use]
pub fn features() -> Features {
    let token = crate::abi::decode::cpu_query_token();
    let cached = FEATURES_CACHE.load(Ordering::Relaxed);
    #[expect(
        clippy::cast_possible_truncation,
        reason = "the low word of the cache holds the feature bits"
    )]
    let bits = cached as u32;
    let cached_token = (cached >> 32) as u32;
    if cached_token == token && bits & Features::VALID != 0 {
        return Features::from_bits(bits);
    }
    refresh_features(token)
}

/// Computes the record for the pointer of `token` and caches it: the first
/// call of [`features`], and the first after the pointer changed.
#[cold]
#[inline(never)]
fn refresh_features(token: u32) -> Features {
    let computed = compute_features();
    FEATURES_CACHE.store(
        (u64::from(token) << 32) | u64::from(computed.bits() | Features::VALID),
        Ordering::Relaxed,
    );
    computed
}

/// The record for the current `VP8GetCPUInfo` pointer.
fn compute_features() -> Features {
    let query =
        |feature: CPUFeature| crate::abi::decode::cpu_feature_query(feature).unwrap_or(false);
    Features {
        sse2: query(CPUFeature::kSSE2),
        sse3: query(CPUFeature::kSSE3),
        slow_ssse3: query(CPUFeature::kSlowSSSE3),
        sse4_1: query(CPUFeature::kSSE4_1),
        avx: query(CPUFeature::kAVX),
        avx2: query(CPUFeature::kAVX2),
        neon: cfg!(target_arch = "aarch64"),
        query_neon: query(CPUFeature::kNEON),
    }
}