# macOS 15.3 font smoothing: recovered algorithm

**Result:** the outline dilation is recovered, not fitted. The Rust implementation matches 1,800
CoreGraphics output paths to **1.71e-12 device px**, and produces identical masks when both paths go
through zeno. With CoreGraphics' curve flattening and small-size autohinter also reconstructed,
**14,400 end-to-end masks differ by at most 3/255**. Independent Swash outline extraction and font
metrics reach the same bound in **9,600 Inter Regular/Bold cases**. It is not yet byte-exact scan conversion.

Machine: Apple Silicon arm64, macOS 15.3 / 24D60. Research date: 2026-10-27.
Scope: default horizontal grayscale antialiasing, opaque solid ink, ordinary static Latin outlines,
positive isotropic scale. Positions are unquantized in the main corpus. No project rendering code changed.

## 1. Exact amount

Convert the foreground colour to **linear sRGB**, then:

```text
Y = fma(Blinear, 0.0722, fma(Rlinear, 0.2126, Glinear * 0.7152))
q = round_away_from_zero(4 * Y) / 4
c = fma(q, 0.010000000000000002, 0.0058)
d = min(ppem * c, double(0.3f))
```

For ordinary in-gamut RGB, q is one of 0, 0.25, 0.5, 0.75, 1. The reference clamps the bucket to this
range; extended/HDR colours are outside the validated scope. `double(0.3f)` is exactly
**0.30000001192092896**. `d` is the **radius**, not total stroke-width growth.

For encoded sRGB, decode each component with `v/12.92` below 0.04045 and
`((v+0.055)/1.055)^2.4` otherwise. Other colour spaces need colour management to linear sRGB first.
Background colour is not an input to the dilation decision. Alpha is not part of this luminance sum.

| Linear Y interval | q | radius / ppem | Radius at 32 px | Cap starts at ppem |
|---|---:|---:|---:|---:|
| [0, .125) | 0 | .0058 | .1856 | 51.72414 |
| [.125, .375) | .25 | .0083 | .2656 | 36.14458 |
| [.375, .625) | .5 | .0108 | .3000000119 | 27.77778 |
| [.625, .875) | .75 | .0133 | .3000000119 | 22.55639 |
| [.875, 1] | 1 | .0158 | .3000000119 | 18.98734 |

The corresponding encoded-sRGB grey boundaries are approximately .388573, .646077, .812366, .942905.
An internal-function sweep at 4,097 greys agreed with this formula at every sample. A separate
black-box 16-px glyph-mask sweep at 1/1024 resolution found the five transitions at 0, .388671875,
.646484375, .8125, .943359375. At 32 px the last three levels collapse to the same capped radius.
Pure red selects q=.25, green q=.75, blue q=0. Both #296d9a and #d03030 select q=.25.

**There is no 72-px cutoff.** The cap persists through 96, 128 and 200 px in the additional checks.
At 32 px, #1d1e22 grows by .1856 px on either side and .3712 px upward, not exactly .1875/.375:
the older measurement inferred those values from quantized alpha bytes.

## 2. Exact geometric operation

Use **y-up device coordinates**. Keep all contours' relative winding. The orientation iterator
integrates signed area across the entire glyph and reverses **all contours together** if necessary,
so outer contours are counterclockwise and holes clockwise. Reversing each contour independently
would fill or expand counters incorrectly.

Apply the fractional glyph origin **before** dilation. Integer placement follows rasterization.
Although the geometric operation looks translation invariant, its floating-point branch decisions
are not: adding phase after dilation produced isolated 63-level errors; moving it before dilation
removed all of them in the tested non-autohinted cases.

For each line, or each cubic piece monotonic in x and y, let `P` be its start and `Q` its end:

```text
sx = sign(Q.y - P.y) * dx
sy = -sign(Q.x - P.x) * dy + dy
emit move/line to P + (sx,sy)
emit line/cubic translated by (sx,sy)
```

`sign(0)=0`. Here `dx=dy=d` for the modern grayscale path. Consecutive translated pieces are joined
with straight lines. A final translated closing line is followed by close-subpath.

Consequences:
- Vertical sides move ±d horizontally; top edges move +2d; bottom edges stay put.
- A diagonal receives the full per-axis displacement, not a unit-normal displacement.
- Corners have bevel connectors. This is not FreeType/Swash's point emboldening, a round stroke,
  or a literal rectangular Minkowski union at every corner.
- Curved monotonic segments are translated intact, including control points; they are not
  recomputed as parallel/normal-offset curves.

### Curves and floating-point details

Quadratics become cubics, then cubics are split at x derivative roots and subsequently y derivative
roots. Roots within `1e-10 ..= 0.9999999999` are used. Current/start coordinates and radii are stored
as f32; emitted endpoints and control points are computed in f64. Initial translated piece starts
are calculated through f32 additions. The reference preserves this mixed precision.

One observed quirk in the curve-splitting root computation is reproduced by the reference. The y-root stage uses the ordinary y difference. We
validated the resulting algorithm on the glyph corpus, not on every possible arbitrary cubic or
degenerate self-intersecting path. De Casteljau split arithmetic can differ from Apple's polynomial
evaluation at roughly machine epsilon; this explains the tiny coordinate residual above.

## 3. The integer-baseline quirk is an autohinter

The earlier claim that CoreText “never hints” is too broad. This is not TrueType bytecode hinting,
but CoreGraphics has its own metric-driven y autohinter.

It applies for eligible fonts when:
- effective ppem is an **integer 7 through 18**, inclusive;
- the em matrix is positive isotropic and axis aligned;
- the bitmap key's vertical fractional phase is zero.

The font-provider eligibility flag exists but has not been mapped for all font formats. Inter
Regular, Inter Bold and Helvetica all take this path. Main-corpus phases with nonzero y skip it.
The autohinter is **after dilation, before flattening** and maps every control point independently.

Inputs in font units: `U=unitsPerEm`, `X=top of glyph 'X' bbox`, `O=top of glyph 'o' bbox`,
`F=font bbox maxY`, `H=descriptor stemH`. These are not necessarily OS/2 xHeight/capHeight.
For the tested TrueType fonts H=0. `truetype_hint_metrics()` derives these from Swash and `head`.
For CFF or unusual fonts provide the appropriate metrics explicitly.

### Target selection

```text
s = ppem / U
r = min(ppem * .015125, .3)       // reference radius, independent of ink
(xo, xc) = (floor(O*s + 2r + .5), floor(X*s + 2r + .5))
(yo, yc) = (floor(O*s + .5),      floor(X*s + .5))
```

If xo != yo, evaluate both candidate target pairs at dilation r and 0. For each pair sum
`abs(lower_slope-1)+abs(middle_slope-1)` over both dilations. Choose `(yo,yc)` only if its cost is
strictly smaller. Then construct the final transform using the actual colour-dependent radius d.

### Piecewise y transform (default nonlinear mode)

Let chosen targets be `To,Tc` and:

```text
h = min(H == 0 ? X : H, .333*O, (X-O)/2) * s
a = h+d
b = O*s+d;         B = To-d
c = X*s-h-d;       C = Tc-h-3d
e = X*s+d;         E = Tc-d
f = F*s+d
l = (B-a)/(b-a)
m = (C-B)/(c-b)
u = (f-E)/(f-e)
```

Zero denominators give slope 0. If `m < .75` or `m-l > .3`, suppress cap-height snapping:
set `E=e`, `C=e-h-2d`, recompute m, set u=1. Reject the transform if `O/X > .85 && m < .33`.
Otherwise map:

```text
y < a        → y
a ≤ y ≤ b    → a + (y-a)*l
b < y ≤ c    → B + (y-b)*m
c < y ≤ e    → y + (C-c)
y > e        → E + (y-e)*u
```

The reference agrees with **180 directly captured native transforms** (3 fonts × 12 sizes ×
5 buckets), maximum parameter discrepancy 1.89e-15 and no validity mismatches. This removes the
large integer-phase errors, including the “T” example from the previous report.

## 4. Match the flattening before asking zeno for coverage

CoreGraphics casts incoming coordinates to f32, then recursively halves Beziers in f64.

- Quadratic flatness: both components of `(P0+P2-2P1)^2` ≤ **.6400000000000001**.
- Cubic flatness: both components of both `(P0+P2-2P1)^2` and `(P1+P3-2P2)^2`
  ≤ **.07111111111111111**.
- Subdivision depth is bounded (the reconstructed normal path stops beyond 22).
- Emit the endpoint of each accepted segment as a line.

Those constants come from `aa_create`, not from tuning the comparison. Sending the resulting
polylines to zeno removes almost all of the previously reported “different curve rasterizer” error.

Apple then converts vertices using `trunc(coord*4096+.5)`, stores fixed-point slopes, and performs
its own scan conversion. Zeno uses different fixed-point coverage arithmetic. The remaining
**≤3 alpha levels** are scan-conversion/rounding differences; exact Apple scan conversion has not
been ported. `analytic_mask()` is a separate ideal-area experiment using the 12-bit vertex grid;
it reduces pixels off by >1 but is still not byte-exact. It is slower and is not needed for the
Swash/zeno integration.

## 5. Swash integration recipe

1. Extract an **unhinted outline at unitsPerEm**, not at final ppem. Convert points to f64 and
   multiply by ppem/unitsPerEm. Swash's final-size extraction has earlier quantization; using it
   directly left outliers up to 65 levels despite the correct dilation algorithm.
2. Keep the outline y-up. Add the chosen fractional device-pixel origin before dilation.
3. Normalize whole-glyph winding; run the direction-sign dilator with the colour-derived radius.
4. Apply the metric autohinter when eligible and vertical phase is zero.
5. Flatten with the recovered CG tolerances, then feed **line commands** to zeno.
6. Rasterize with ordinary coverage; composite in the destination's encoded space to match the
   tested sRGB CG context. Do not add Rune's compensating coverage gamma to this model.
7. Cache masks by font/variation, ppem, phase and luminance bucket (buckets can share after capping).

`prepare_outline()` implements steps 2–5. `dilate_srgb()` is the smaller outline+ppem+ink operation.
`from_zeno()`, `scale_path()` and `truetype_hint_metrics()` bridge from Swash. No Apple API is used
by the Rust library or the independent Inter render path.

CG's default positional quantization is a separate upstream concern. The prior study measured
x flooring to 1/4 point (1/2 px at 2×); the present mask corpus disables that quantization so all
requested phases are tested directly. It does not revalidate rotated/nonuniform quantization.

## 6. Measurements

Corpus: 3 fonts (Inter Regular/Bold, Helvetica), 12 glyphs `IHT—/AVSog@8`, sizes
8/10/12/14/16/18/24/32/48/72 device px, 5 luminance buckets, 4 phases
`(0,0),(.25,1/64),(.5,.5),(.75,.25)`, at 1× and 2×. Each backing scale uses the same device ppem
(point size = ppem/scale). Masks are alpha bytes from transparent sRGB RGBA8 contexts.

Each error is evaluated over the union of the ink bounds plus a one-pixel border per glyph:
7,115,310 pixels total, not the much larger mostly empty 96×112 storage tiles.

| Pipeline vs smoothed CG | Cases | Mean absolute /255 | Max /255 | Pixels >1 | Pixels >8 |
|---|---:|---:|---:|---:|---:|
| Original unhinted outlines, ordinary zeno | 14,400 | 12.79934 | 225 | 22.3954% | 19.7794% |
| Recovered dilation, ordinary zeno | 14,400 | .85315 | 155 | 5.1096% | 2.8010% |
| + recovered CG flattening | 14,400 | .25892 | 155 | 1.6488% | .4665% |
| + phase before dilation | 14,400 | .24280 | 155 | 1.4489% | .3975% |
| + reconstructed autohinter, zeno lines | 14,400 | **.11293** | **3** | **.7458%** | **0%** |
| Same outlines, independent analytic line coverage | 14,400 | .10425 | 3 | .0933% | 0% |
| Independent Swash design-unit outlines + own metrics + model + zeno | 9,600 | **.10949** | **3** | **.7079%** | **0%** |

The first six rows use CoreText's unhinted outline extraction to isolate algorithm stages. The last
row independently loads the two Inter TTFs through Swash, including its own metric extraction.
The public Swift glyph renderer is always the reference mask. Full per-case metrics are supplied.
These are not directly comparable to the previous report's paragraph-band/RGB MAE denominator.

Additional checks:
- Alpha-only contexts **do not inherently force white's dilation**. Explicit black and white fill
  colours produce their respective RGBA-context masks exactly. The earlier alpha-only harness
  set white ink, which explains its white-bucket result.
- On black/white backgrounds, compositing black/grey/white ink from the transparent coverage in
  encoded RGB predicts opaque-context output to 0–0.5 byte levels in the straight-stem check.
- `CGContextSetFontDilation(0,0)` and `(1,1)`, smoothing styles 0x10/20/30/40 and contrast 0/10
  all left the tested ordinary glyph draw unchanged. The delegate's temporary custom override
  explains why the exposed dilation setter does not give control of modern text weight.

## 7. Prior art and corrections

- [Pathfinder effects.rs](https://github.com/servo/pathfinder/blob/2b5c6682d75a3f79b5a5e02af51650754a7f190d/content/src/effects.rs):
  `STEM_DARKENING_FACTORS=[.0121,.0121*1.25]`, cap `[.3,.3]`; its 72-ppem cutoff is explicitly
  subjective. Modern macOS uses the colour-dependent amounts described above instead.
- [Zed PR 54886](https://github.com/zed-industries/zed/pull/54886), merged April 2026, independently
  found Rec.709 and five buckets and keys a CG atlas by dilation. The PR prose accidentally swaps
  G/B labels; its patch uses the normal coefficients. Our measurements additionally establish
  the conversion to **linear** sRGB and recovers the subsequent geometry.
- [Skia mac scaler](https://github.com/google/skia/blob/main/src/ports/SkScalerContext_mac_ct.cpp):
  describes smoothing as outline dilation, disables CG quantization for its own positioning,
  draws black-on-white masks and carries historical LCD/gamma handling. The historical comments
  about gamma-2 smoothed blits are not a specification for the current grayscale alpha path.
- [WebRender #1767](https://github.com/servo/webrender/issues/1767): early evidence that foreground
  colour changes native glyph weight and therefore mask caching needs colour awareness.
- [WebKit private SPI](https://trac.webkit.org/changeset/238265/webkit): declarations for smoothing
  style and contrast. They are not sufficient controls for this modern delegate path.
- [macOS font rendering overview](https://skip.house/blog/macos-font-rendering): useful historical
  context, not a replacement for measuring 15.3.

## 8. Remaining work

The remaining gap is scan conversion: CoreGraphics fills outlines with a fixed-point rasteriser whose rounding differs slightly from zeno's, which accounts for the last few byte levels. Matching it byte-for-byte needs further measurement of single-edge polygons against CoreGraphics output.
