Skip to main content

read_fonts/tables/
fvar.rs

1//! The [Font Variations](https://docs.microsoft.com/en-us/typography/opentype/spec/fvar) table
2
3include!("../../generated/generated_fvar.rs");
4
5#[path = "./instance_record.rs"]
6mod instance_record;
7
8use super::{avar::Avar, variations::DeltaSetIndex};
9use smallvec::SmallVec;
10
11pub use instance_record::InstanceRecord;
12
13const MAX_INLINE_AVAR2_AXES: usize = 64;
14/// Maximum number of axes for which we will use a quadratic path to normalize user coordinates.
15const MAX_NORMALIZE_QUADRATIC_AXES: usize = 64;
16const MAX_INLINE_NORMALIZE_AXES: usize = 128;
17
18#[inline]
19fn round_f64_to_i32(value: f64) -> i32 {
20    if value >= 0.0 {
21        (value + 0.5) as i32
22    } else {
23        (value - 0.5) as i32
24    }
25}
26
27#[inline]
28fn apply_avar2_delta(coord: Fixed, delta_2dot14: f64) -> Fixed {
29    // HarfBuzz keeps the avar1 result in 16.16 through the avar2 add, and
30    // converts the avar2 delta from 2.14 units by multiplying by four.
31    Fixed::from_bits(
32        coord
33            .to_bits()
34            .wrapping_add(round_f64_to_i32(delta_2dot14 * 4.0)),
35    )
36}
37
38#[inline(never)]
39fn sort_axis_order(axes: &[VariationAxisRecord], axis_order: &mut [u16]) {
40    axis_order.sort_unstable_by_key(|&i| axes[i as usize].axis_tag());
41}
42
43fn normalize_user_coords<T>(
44    axes: &[VariationAxisRecord],
45    user_coords: impl IntoIterator<Item = (Tag, Fixed)>,
46    coords: &mut [T],
47    convert: impl Fn(Fixed) -> T,
48) {
49    let axis_count = axes.len().min(coords.len());
50    let axes = &axes[..axis_count];
51    let coords = &mut coords[..axis_count];
52    if axis_count <= MAX_NORMALIZE_QUADRATIC_AXES {
53        for (tag, user_coord) in user_coords {
54            // To permit non-linear interpolation, iterate over all axes to
55            // ensure we match multiple axes with the same tag:
56            // https://github.com/PeterConstable/OT_Drafts/blob/master/NLI/UnderstandingNLI.md
57            for (axis, coord) in axes
58                .iter()
59                .zip(coords.iter_mut())
60                .filter(|(axis, _)| axis.axis_tag() == tag)
61            {
62                *coord = convert(axis.normalize(user_coord));
63            }
64        }
65        return;
66    }
67    // Above MAX_NORMALIZE_QUADRATIC_AXES, use an indexed path to avoid O(n^2) behavior
68    let mut axis_order = SmallVec::<[u16; MAX_INLINE_NORMALIZE_AXES]>::from_elem(0, axis_count);
69    let axis_order = axis_order.as_mut_slice();
70    // Initialize axis_order with the identity mapping
71    for (i, axis_index) in axis_order.iter_mut().enumerate() {
72        *axis_index = i as u16;
73    }
74    // Then sort by tag to group axes with the same tag together, so we can use
75    // partition_point to find the range of axes for each tag
76    sort_axis_order(axes, axis_order);
77    for (tag, user_coord) in user_coords {
78        let start = axis_order.partition_point(|&i| axes[i as usize].axis_tag() < tag);
79        let end = axis_order.partition_point(|&i| axes[i as usize].axis_tag() <= tag);
80        for &i in &axis_order[start..end] {
81            coords[i as usize] = convert(axes[i as usize].normalize(user_coord));
82        }
83    }
84}
85
86fn apply_avar_mappings<T>(
87    avar: Option<&Avar>,
88    coords: &mut [T],
89    to_fixed: impl Fn(&T) -> Fixed,
90    from_fixed: impl Fn(Fixed) -> T,
91) {
92    if let Some(maps) = avar.map(|avar| avar.axis_segment_maps()) {
93        for (coord, map) in coords.iter_mut().zip(maps.iter()) {
94            if let Ok(map) = map {
95                *coord = from_fixed(map.apply(to_fixed(coord)));
96            }
97        }
98    }
99}
100
101fn to_normalized_coords(fixed_coords: &[Fixed], normalized_coords: &mut [F2Dot14]) {
102    for (target_coord, coord) in normalized_coords.iter_mut().zip(fixed_coords.iter()) {
103        *target_coord = coord.to_f2dot14();
104    }
105}
106
107impl<'a> Fvar<'a> {
108    /// Returns the array of variation axis records.
109    pub fn axes(&self) -> Result<&'a [VariationAxisRecord], ReadError> {
110        Ok(self.axis_instance_arrays()?.axes())
111    }
112
113    /// Returns the array of instance records.
114    pub fn instances(&self) -> Result<ComputedArray<'a, InstanceRecord<'a>>, ReadError> {
115        Ok(self.axis_instance_arrays()?.instances())
116    }
117
118    /// Converts user space coordinates provided by an unordered iterator
119    /// of `(tag, value)` pairs to normalized coordinates in axis list order.
120    ///
121    /// Stores the resulting normalized coordinates in the given slice.
122    ///
123    /// * User coordinate tags that don't match an axis are ignored.
124    /// * User coordinate values are clamped to the range of their associated
125    ///   axis before normalization.
126    /// * If more than one user coordinate is provided for the same tag, the
127    ///   last one is used.
128    /// * If no user coordinate for an axis is provided, the associated
129    ///   coordinate is set to the normalized value 0.0, representing the
130    ///   default location in variation space.
131    /// * The length of `normalized_coords` should equal the number of axes
132    ///   present in the this table. If the length is smaller, axes at
133    ///   out of bounds indices are ignored. If the length is larger, the
134    ///   excess entries will be filled with zeros.
135    ///
136    /// If the [`Avar`] table is provided, applies remapping of coordinates
137    /// according to the specification.
138    pub fn user_to_normalized(
139        &self,
140        avar: Option<&Avar>,
141        user_coords: impl IntoIterator<Item = (Tag, Fixed)>,
142        normalized_coords: &mut [F2Dot14],
143    ) {
144        normalized_coords.fill(F2Dot14::ZERO);
145        let axes = self.axes().unwrap_or_default();
146        let actual_len = axes.len().min(normalized_coords.len());
147        let normalized_coords = &mut normalized_coords[..actual_len];
148
149        let mut fixed_coords =
150            SmallVec::<[Fixed; MAX_INLINE_AVAR2_AXES]>::from_elem(Fixed::ZERO, actual_len);
151        let fixed_coords = fixed_coords.as_mut_slice();
152        normalize_user_coords(axes, user_coords, fixed_coords, core::convert::identity);
153        apply_avar_mappings(avar, fixed_coords, |coord| *coord, core::convert::identity);
154
155        let Some(avar) = avar else {
156            to_normalized_coords(fixed_coords, normalized_coords);
157            return;
158        };
159        if avar.version() == MajorMinor::VERSION_1_0 {
160            to_normalized_coords(fixed_coords, normalized_coords);
161            return;
162        }
163
164        let var_store = avar.var_store();
165        let var_index_map = avar.axis_index_map();
166
167        let mut coords_2dot14 =
168            SmallVec::<[F2Dot14; MAX_INLINE_AVAR2_AXES]>::from_elem(F2Dot14::ZERO, actual_len);
169        let coords_2dot14 = coords_2dot14.as_mut_slice();
170        for (coord_2dot14, coord) in coords_2dot14.iter_mut().zip(fixed_coords.iter()) {
171            *coord_2dot14 = coord.to_f2dot14();
172        }
173
174        if let Some(Ok(varstore)) = var_store.as_ref() {
175            for (i, coord) in fixed_coords.iter_mut().enumerate() {
176                let var_index = if let Some(Ok(ref map)) = var_index_map {
177                    match map.get(i as u32) {
178                        Ok(index) => index,
179                        Err(_) => continue,
180                    }
181                } else {
182                    DeltaSetIndex {
183                        outer: 0,
184                        inner: i as u16,
185                    }
186                };
187                if let Some(delta) = varstore.compute_delta(var_index, coords_2dot14) {
188                    *coord =
189                        apply_avar2_delta(*coord, delta.to_f64()).clamp(Fixed::NEG_ONE, Fixed::ONE);
190                }
191            }
192        }
193
194        to_normalized_coords(fixed_coords, normalized_coords);
195    }
196}
197
198impl VariationAxisRecord {
199    /// Returns a normalized coordinate for the given value.
200    pub fn normalize(&self, mut value: Fixed) -> Fixed {
201        use core::cmp::Ordering::*;
202        let min_value = self.min_value();
203        let default_value = self.default_value();
204        // Make sure max is >= min to avoid potential panic in clamp.
205        let max_value = self.max_value().max(min_value);
206        value = value.clamp(min_value, max_value);
207        value = match value.cmp(&default_value) {
208            Less => {
209                -((default_value.saturating_sub(value)) / (default_value.saturating_sub(min_value)))
210            }
211            Greater => {
212                (value.saturating_sub(default_value)) / (max_value.saturating_sub(default_value))
213            }
214            Equal => Fixed::ZERO,
215        };
216        value.clamp(Fixed::NEG_ONE, Fixed::ONE)
217    }
218}
219
220#[cfg(test)]
221mod tests {
222    use super::*;
223    use crate::{FontRef, TableProvider};
224    use types::{BigEndian, F2Dot14, Fixed, NameId, Tag};
225
226    #[test]
227    fn axes() {
228        let font = FontRef::new(font_test_data::VAZIRMATN_VAR).unwrap();
229        let fvar = font.fvar().unwrap();
230        assert_eq!(fvar.axis_count(), 1);
231        let wght = &fvar.axes().unwrap().first().unwrap();
232        assert_eq!(wght.axis_tag(), Tag::new(b"wght"));
233        assert_eq!(wght.min_value(), Fixed::from_f64(100.0));
234        assert_eq!(wght.default_value(), Fixed::from_f64(400.0));
235        assert_eq!(wght.max_value(), Fixed::from_f64(900.0));
236        assert_eq!(wght.flags(), 0);
237        assert_eq!(wght.axis_name_id(), NameId::new(257));
238    }
239
240    #[test]
241    fn instances() {
242        let font = FontRef::new(font_test_data::VAZIRMATN_VAR).unwrap();
243        let fvar = font.fvar().unwrap();
244        assert_eq!(fvar.instance_count(), 9);
245        // There are 9 instances equally spaced from 100.0 to 900.0
246        // with name id monotonically increasing starting at 258.
247        let instances = fvar.instances().unwrap();
248        for i in 0..9 {
249            let value = 100.0 * (i + 1) as f64;
250            let name_id = NameId::new(258 + i as u16);
251            let instance = instances.get(i).unwrap();
252            assert_eq!(instance.coordinates.len(), 1);
253            assert_eq!(
254                instance.coordinates.first().unwrap().get(),
255                Fixed::from_f64(value)
256            );
257            assert_eq!(instance.subfamily_name_id, name_id);
258            assert_eq!(instance.post_script_name_id, None);
259        }
260    }
261
262    #[test]
263    fn normalize() {
264        let font = FontRef::new(font_test_data::VAZIRMATN_VAR).unwrap();
265        let fvar = font.fvar().unwrap();
266        let axis = fvar.axes().unwrap().first().unwrap();
267        let values = [100.0, 220.0, 250.0, 400.0, 650.0, 900.0];
268        let expected = [-1.0, -0.60001, -0.5, 0.0, 0.5, 1.0];
269        for (value, expected) in values.into_iter().zip(expected) {
270            assert_eq!(
271                axis.normalize(Fixed::from_f64(value)),
272                Fixed::from_f64(expected)
273            );
274        }
275    }
276
277    #[test]
278    fn normalize_overflow() {
279        // From: https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=69787
280        // & https://oss-fuzz.com/testcase?key=6159008335986688
281        // fvar entry triggering overflow:
282        // min: -26335.87451171875 def 8224.12548828125 max 8224.12548828125
283        let test_case = &[
284            79, 84, 84, 79, 0, 1, 32, 32, 255, 32, 32, 32, 102, 118, 97, 114, 32, 32, 32, 32, 0, 0,
285            0, 28, 0, 0, 0, 41, 32, 0, 0, 0, 0, 1, 32, 32, 0, 2, 32, 32, 32, 32, 0, 0, 32, 32, 32,
286            32, 32, 0, 0, 0, 0, 153, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32, 32,
287        ];
288        let font = FontRef::new(test_case).unwrap();
289        let fvar = font.fvar().unwrap();
290        let axis = fvar.axes().unwrap()[1];
291        // Should not panic with "attempt to subtract with overflow".
292        assert_eq!(
293            axis.normalize(Fixed::from_f64(0.0)),
294            Fixed::from_f64(-0.2509765625)
295        );
296    }
297
298    #[test]
299    fn normalize_user_coords_uses_indexed_path_for_large_axis_counts() {
300        let axis = VariationAxisRecord {
301            axis_tag: BigEndian::from(Tag::new(b"wght")),
302            min_value: BigEndian::from(Fixed::from_f64(-1.0)),
303            default_value: BigEndian::from(Fixed::ZERO),
304            max_value: BigEndian::from(Fixed::ONE),
305            flags: BigEndian::from(0),
306            axis_name_id: BigEndian::from(NameId::new(1)),
307        };
308        let axes = vec![axis; MAX_NORMALIZE_QUADRATIC_AXES + 1];
309        let mut coords = vec![Fixed::ZERO; axes.len()];
310        normalize_user_coords(
311            &axes,
312            [(Tag::new(b"wght"), Fixed::from_f64(0.5))],
313            &mut coords,
314            core::convert::identity,
315        );
316        assert!(coords.iter().all(|coord| *coord == Fixed::from_f64(0.5)));
317    }
318
319    #[test]
320    fn normalize_user_coords_handles_duplicate_tags_in_indexed_path() {
321        let wght_axis = VariationAxisRecord {
322            axis_tag: BigEndian::from(Tag::new(b"wght")),
323            min_value: BigEndian::from(Fixed::from_f64(-1.0)),
324            default_value: BigEndian::from(Fixed::ZERO),
325            max_value: BigEndian::from(Fixed::ONE),
326            flags: BigEndian::from(0),
327            axis_name_id: BigEndian::from(NameId::new(1)),
328        };
329        let wdth_axis = VariationAxisRecord {
330            axis_tag: BigEndian::from(Tag::new(b"wdth")),
331            min_value: BigEndian::from(Fixed::from_f64(-1.0)),
332            default_value: BigEndian::from(Fixed::ZERO),
333            max_value: BigEndian::from(Fixed::ONE),
334            flags: BigEndian::from(0),
335            axis_name_id: BigEndian::from(NameId::new(2)),
336        };
337        let axes = (0..(MAX_NORMALIZE_QUADRATIC_AXES + 2))
338            .map(|i| if i % 2 == 0 { wght_axis } else { wdth_axis })
339            .collect::<Vec<_>>();
340        let mut coords = vec![Fixed::ZERO; axes.len()];
341        normalize_user_coords(
342            &axes,
343            [(Tag::new(b"wght"), Fixed::from_f64(0.25))],
344            &mut coords,
345            core::convert::identity,
346        );
347        for (i, coord) in coords.iter().enumerate() {
348            if i % 2 == 0 {
349                assert_eq!(*coord, Fixed::from_f64(0.25));
350            } else {
351                assert_eq!(*coord, Fixed::ZERO);
352            }
353        }
354    }
355
356    #[test]
357    fn user_to_normalized() {
358        let font = FontRef::from_index(font_test_data::VAZIRMATN_VAR, 0).unwrap();
359        let fvar = font.fvar().unwrap();
360        let avar = font.avar().ok();
361        let wght = Tag::new(b"wght");
362        let axis = fvar.axes().unwrap()[0];
363        let mut normalized_coords = [F2Dot14::default(); 1];
364        // avar table maps 0.8 to 0.83875
365        let avar_user = axis.default_value().to_f32()
366            + (axis.max_value().to_f32() - axis.default_value().to_f32()) * 0.8;
367        let avar_normalized = 0.83875;
368        #[rustfmt::skip]
369        let cases = [
370            // (user, normalized)
371            (-1000.0, -1.0f32),
372            (100.0, -1.0),
373            (200.0, -0.5),
374            (400.0, 0.0),
375            (900.0, 1.0),
376            (avar_user, avar_normalized),
377            (1251.5, 1.0),
378        ];
379        for (user, normalized) in cases {
380            fvar.user_to_normalized(
381                avar.as_ref(),
382                [(wght, Fixed::from_f64(user as f64))],
383                &mut normalized_coords,
384            );
385            assert_eq!(normalized_coords[0], F2Dot14::from_f32(normalized));
386        }
387    }
388
389    #[test]
390    fn avar2() {
391        let font = FontRef::new(font_test_data::AVAR2_CHECKER).unwrap();
392        let avar = font.avar().ok();
393        let fvar = font.fvar().unwrap();
394        let avar_axis = Tag::new(b"AVAR");
395        let avwk_axis = Tag::new(b"AVWK");
396        let mut normalized_coords = [F2Dot14::default(); 2];
397        let cases = [
398            ((100.0, 0.0), (1.0, 1.0)),
399            ((50.0, 0.0), (0.5, 0.5)),
400            ((0.0, 50.0), (0.0, 0.5)),
401        ];
402        for (user, expected) in cases {
403            fvar.user_to_normalized(
404                avar.as_ref(),
405                [
406                    (avar_axis, Fixed::from_f64(user.0)),
407                    (avwk_axis, Fixed::from_f64(user.1)),
408                ],
409                &mut normalized_coords,
410            );
411            assert_eq!(normalized_coords[0], F2Dot14::from_f32(expected.0));
412            assert_eq!(normalized_coords[1], F2Dot14::from_f32(expected.1));
413        }
414    }
415
416    #[test]
417    fn avar2_no_panic_with_wrong_size_coords_array() {
418        // this font has 2 axes
419        let font = FontRef::new(font_test_data::AVAR2_CHECKER).unwrap();
420        let avar = font.avar().ok();
421        let fvar = font.fvar().unwrap();
422        // output array too small
423        let mut normalized_coords = [F2Dot14::default(); 1];
424        fvar.user_to_normalized(avar.as_ref(), [], &mut normalized_coords);
425        // output array too large
426        let mut normalized_coords = [F2Dot14::default(); 4];
427        fvar.user_to_normalized(avar.as_ref(), [], &mut normalized_coords);
428    }
429
430    #[test]
431    fn avar2_preserves_16_16_precision_until_final_rounding() {
432        // Quantizing to 2.14 before applying the avar2 delta would produce 0x0002
433        // here, but HarfBuzz's 16.16 path produces 0x0001.
434        let coord = Fixed::from_bits(3);
435        assert_eq!(
436            super::apply_avar2_delta(coord, 0.5).to_f2dot14(),
437            F2Dot14::from_bits(1)
438        );
439    }
440
441    #[test]
442    fn avar2_clamps_hidden_axis_for_amstelvar_repro() {
443        let font = FontRef::new(font_test_data::AMSTELVAR_AVAR2_A).unwrap();
444        let avar = font.avar().ok();
445        let fvar = font.fvar().unwrap();
446        let mut normalized_coords = [F2Dot14::ZERO; 12];
447
448        fvar.user_to_normalized(
449            avar.as_ref(),
450            [(Tag::new(b"wght"), Fixed::from_f64(1000.0))],
451            &mut normalized_coords,
452        );
453
454        assert_eq!(normalized_coords[1], F2Dot14::from_bits(-5370)); // XTRA
455        assert_eq!(normalized_coords[2], F2Dot14::ONE); // XOPQ clamped from > 1
456        assert_eq!(normalized_coords[3], F2Dot14::from_bits(2254)); // YOPQ
457        assert_eq!(normalized_coords[11], F2Dot14::ONE); // wght
458    }
459}