Skip to content

fix(🍏): clip toneMapping "standard" at SDR white on iOS 18+ and macOS 15+ - #656

Open
andreialecu wants to merge 2 commits into
wcandillon:mainfrom
andreialecu:fix/canvas-tonemapping-standard
Open

andreialecu wants to merge 2 commits into
wcandillon:mainfrom
andreialecu:fix/canvas-tonemapping-standard

Conversation

@andreialecu

@andreialecu andreialecu commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Description

This replaces #643. I opened that one thinking toneMapping: { mode: "extended" } clipped at SDR white on iOS 26, but I had seen that on a simulator, which doesn't show EDR. On real devices the problem is the other way around.

While testing the diagnostic screen that William asked for in #643, I noticed that on an iPhone with iOS 27.2.1 and on a MacBook Pro with an XDR display (macOS 27.2.1), "standard" doesn't clip on main while an "extended" canvas is on screen too. Alone it clips, but next to "extended" the two canvases look the same, and both go above SDR white. With this PR, "standard" clips at SDR white next to "extended" too, and "extended" is unchanged.

This is what the spec asks for. WebGPU's GPUCanvasConfiguration.toneMapping defaults to {}, and the HTML spec defines CanvasToneMapping with mode = "standard" by default:

The "standard" value indicates that the HDR headroom of the bitmap is 0, and tone mapping does not change its color values.

The "extended" value indicates that the HDR headroom of the bitmap is not limited, and tone mapping does not change its color values.

Our docs say the same: on an rgba16float canvas "values above 1.0 are clamped to the display's SDR range by default". So an rgba16float canvas that doesn't set toneMapping and showed values above 1.0 next to an EDR layer on iOS/macOS 27.2.1 will now clip, as it does in Safari. 8-bit canvases look the same as before.

Agent-written content

On main, wantsExtendedDynamicRangeContent = NO is all that keeps a "standard" float canvas in SDR, and it stops working as soon as another layer on screen shows EDR. CAMetalLayer.h says so: "If any onscreen layer has this property set to true, all rendered content is clamped to the screen's maximumExtendedDynamicRangeColorComponentValue rather than 1.0." Chrome 157 does the same on my Mac: "standard" alone clips, next to "extended" it doesn't. Tone mapping is what keeps it in SDR: per the 27.2 SDK headers, CADynamicRangeStandard only applies to content that gets tone mapped, a float drawable is untagged (contentsHeadroom 0), and toneMapMode defaults to automatic, which leaves it as is.

applyCAMetalLayerColorSpace now sets toneMapMode:

  • "standard": toneMapMode = ifSupported with contentsHeadroom = 1.0, the spec's headroom of 0 stops. With an untagged headroom (0) it was tone mapped from an assumed headroom and values below 1.0 came out darker. With 1.0 they stay as they are, and anything above is clipped.
  • "extended": toneMapMode = never, so tone mapping doesn't change its values, as the spec says: they aren't compressed to fit the 16x headroom the layer declares, and they clip at the display's peak.

On the 26 SDKs the layer also sets preferredDynamicRange, which replaces the deprecated wantsExtendedDynamicRangeContent (still set for iOS 16 to 25). toneMapMode (iOS 18 / macOS 15 SDKs) and the 26 APIs are guarded at compile time, so older Xcodes should keep building. That hasn't been tested.

The native-window docs (MakeWebGPUCanvasContextFromNativeWindow) now say that a caller who brings their own CAMetalLayer has to set the same properties.

Manual testing

Diagnostics > Canvas toneMapping shows an "extended" and a "standard" canvas side by side. Each is a ramp from 0 to 4.0 with a marker at 1.0 and steps of 0.5 above it, next to a strip of plain SDR white. Buttons mount either canvas alone and switch between rgba16float and bgra8unorm.

On an iPhone with iOS 27.2.1 (EDR headroom 8x) and on a MacBook Pro with a built-in XDR display (macOS 27.2.1), with rgba16float:

  1. Extended goes brighter than SDR white above 1.0 and clips at the display's peak, around 2.5 to 3.0 in canvas values depending on brightness.
  2. The steps between 1.0 and the peak are distinct, so extended isn't compressed.
  3. From 0 to 1.0 the two canvases look the same.
  4. Standard is flat SDR white above 1.0, the same as the white strip, alone and next to extended.

On main, standard alone clips too, but with both canvases on screen they show the same steps above 1.0.

Photos of the screen (a screenshot doesn't capture EDR), extended on the left and standard on the right:

main this PR
iPhone, iOS 27.2.1 iphone-main iphone-pr
MacBook Pro XDR, macOS 27.2.1 mac-main mac-pr

With bgra8unorm (iPhone), both canvases clip at 1.0 and look the same as rgba16float below 1.0.

Not tested: iOS 26, and Xcode older than 26.

@andreialecu

andreialecu commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor Author

Interestingly, Chrome doesn't get this right on my Mac, but Safari does.

I ported the diagnostic screen to a plain WebGPU page (no React Native, same shader and layout) and ran it on the same MacBook Pro with an XDR display (macOS 27.2.1):

  • Safari behaves like this PR: "extended" goes above SDR white, and "standard" clips at it.
  • Chrome 157 behaves like main here: "standard" doesn't clip and looks the same as "extended". It reports toneMapping in getConfiguration() and dynamic-range: high, so it looks like it runs into the same Core Animation behavior as main. I've only tested 27.2.1, so I can't say whether this is new in 27 or older.

To run it, save the code below as index.html, serve it from localhost (WebGPU needs a secure context), and open it on an HDR display:

python3 -m http.server 8000 --bind 127.0.0.1

Then open http://127.0.0.1:8000/. The buttons switch between both canvases or one alone, and between rgba16float and bgra8unorm. A screenshot doesn't capture EDR, so look at the display itself.

index.html
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Canvas toneMapping</title>
<style>
  :root { color-scheme: dark; }
  body { margin: 0; padding: 16px; background: black; color: white; font: 13px -apple-system, system-ui, sans-serif; height: 100vh; box-sizing: border-box; display: flex; flex-direction: column; }
  .buttons { display: flex; justify-content: center; gap: 8px; margin-bottom: 8px; }
  button { background: #333; color: white; border: 0; border-radius: 6px; padding: 6px 12px; font: inherit; cursor: pointer; }
  button.active { background: #06c; }
  .row { display: flex; }
  .ramps { flex: 1; min-height: 0; }
  .column { flex: 1; display: flex; min-width: 0; }
  .title { flex: 1; text-align: center; margin-bottom: 8px; }
  .scale { width: 40px; position: relative; }
  .label { position: absolute; width: 100%; text-align: center; font-size: 12px; line-height: 14px; transform: translateY(7px); }
  canvas { flex: 1; min-width: 0; height: 100%; display: block; }
  .sdr { width: 12px; margin-top: auto; height: 75%; background: white; }
  #info { text-align: center; color: #aaa; margin-bottom: 8px; }
</style>
</head>
<body>
<div id="info"></div>
<div class="buttons" id="shown"></div>
<div class="buttons" id="format"></div>
<div class="row"><div class="title">extended</div><div class="scale"></div><div class="title">standard</div></div>
<div class="row ramps" id="ramps"></div>
<script type="module">
const MAX_VALUE = 4;
const MODES = ["extended", "standard"];
const SHOWN = ["both", ...MODES];
const FORMATS = ["rgba16float", "bgra8unorm"];
const shader = `
struct VertexOut { @builtin(position) position: vec4f, @location(0) uv: vec2f };
@vertex fn vs(@builtin(vertex_index) index: u32) -> VertexOut {
  let corners = array(vec2f(-1, -1), vec2f(3, -1), vec2f(-1, 3));
  var out: VertexOut;
  out.position = vec4f(corners[index], 0, 1);
  out.uv = (corners[index] + 1) * 0.5;
  return out;
}
@fragment fn fs(in: VertexOut) -> @location(0) vec4f {
  let ramp = in.uv.y * ${MAX_VALUE}.0;
  let value = select(floor(ramp * 2) / 2, ramp, ramp <= 1);
  let line = abs(ramp - round(ramp)) < fwidth(ramp) * 2;
  let marker = line && round(ramp) == 1;
  let tick = line && round(ramp) > 1 && in.uv.x < 0.25;
  if (marker || tick) { return vec4f(0, 0, 0, 1); }
  return vec4f(value, value, value, 1);
}`;

const info = document.getElementById("info");
const hdr = matchMedia("(dynamic-range: high)").matches;
if (!navigator.gpu) { info.textContent = "navigator.gpu is not available"; throw new Error("no WebGPU"); }
const adapter = await navigator.gpu.requestAdapter();
const device = await adapter.requestDevice();
info.textContent = `${navigator.userAgent.match(/(Chrome|Version)\/[\d.]+/)?.[0] ?? ""} · dynamic-range: high = ${hdr}`;

let shown = "both", format = FORMATS[0];
const buttons = (id, options, get, set) => {
  const el = document.getElementById(id);
  el.replaceChildren(...options.map((o) => {
    const b = document.createElement("button");
    b.textContent = o;
    b.className = get() === o ? "active" : "";
    b.onclick = () => { set(o); render(); };
    return b;
  }));
};

function draw(canvas, mode) {
  const context = canvas.getContext("webgpu");
  canvas.width = canvas.clientWidth * devicePixelRatio;
  canvas.height = canvas.clientHeight * devicePixelRatio;
  context.configure({ device, format, alphaMode: "opaque", toneMapping: { mode } });
  const module = device.createShaderModule({ code: shader });
  const pipeline = device.createRenderPipeline({
    layout: "auto",
    vertex: { module, entryPoint: "vs" },
    fragment: { module, entryPoint: "fs", targets: [{ format }] },
  });
  const encoder = device.createCommandEncoder();
  const pass = encoder.beginRenderPass({ colorAttachments: [{ view: context.getCurrentTexture().createView(), loadOp: "clear", storeOp: "store" }] });
  pass.setPipeline(pipeline);
  pass.draw(3);
  pass.end();
  device.queue.submit([encoder.finish()]);
  const cfg = context.getConfiguration?.();
  return cfg && "toneMapping" in cfg ? `toneMapping supported` : `toneMapping NOT in getConfiguration()`;
}

function render() {
  buttons("shown", SHOWN, () => shown, (v) => (shown = v));
  buttons("format", FORMATS, () => format, (v) => (format = v));
  const ramps = document.getElementById("ramps");
  ramps.replaceChildren();
  const notes = [];
  MODES.forEach((mode, index) => {
    if (index > 0) {
      const scale = document.createElement("div");
      scale.className = "scale";
      for (let v = 0; v <= MAX_VALUE; v++) {
        const l = document.createElement("div");
        l.className = "label";
        l.style.bottom = `${(v / MAX_VALUE) * 100}%`;
        l.textContent = v.toFixed(1);
        scale.append(l);
      }
      ramps.append(scale);
    }
    const column = document.createElement("div");
    column.className = "column";
    ramps.append(column);
    if (shown === "both" || shown === mode) {
      const canvas = document.createElement("canvas");
      const sdr = document.createElement("div");
      sdr.className = "sdr";
      column.append(canvas, sdr);
      requestAnimationFrame(() => notes.push(draw(canvas, mode)));
    }
  });
  requestAnimationFrame(() => requestAnimationFrame(() => {
    info.textContent = `${navigator.userAgent.match(/(Chrome|Version)\/[\d.]+/)?.[0] ?? ""} · dynamic-range: high = ${hdr} · ${[...new Set(notes)].join(", ")}`;
  }));
}
render();
</script>
</body>
</html>

@andreialecu
andreialecu force-pushed the fix/canvas-tonemapping-standard branch from 134e07c to cc4f520 Compare November 25, 2026 13:24
@andreialecu

andreialecu commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor Author

A closer look at Chrome: on its own, each mode is right. With only the "standard" canvas mounted, it clips at SDR white, and "extended" alone goes well above it. It's only with both on screen that "standard" stops clipping and looks the same as "extended".

To reproduce, open the page from my previous comment in Chrome on an HDR display (I used a MacBook Pro with an XDR display), with rgba16float selected. Each canvas is a gray ramp from 0 at the bottom to 4.0 at the top, with a black line at 1.0 and steps of 0.5 above it. Next to each canvas there is a narrow strip of plain SDR white, which starts at the 1.0 line. Compare the part of the ramp above the 1.0 line with that strip:

  1. Press standard. Above 1.0 the ramp is flat and as white as the strip. That's correct.
  2. Press extended. The steps above 1.0 get brighter than the strip, up to around 2.5 to 3.0. That's correct too.
  3. Press both. The "standard" canvas on the right now shows the same bright steps as "extended" on the left, brighter than its strip. It should still look like step 1.

Safari shows step 3 with "standard" flat at the strip's white, as in step 1. A screenshot doesn't capture EDR, so look at the display itself.

That matches what CAMetalLayer.h says about wantsExtendedDynamicRangeContent: "If any onscreen layer has this property set to true, all rendered content is clamped to the screen's maximumExtendedDynamicRangeColorComponentValue rather than 1.0." So relying on the flag being off isn't enough for a "standard" canvas once an EDR layer is visible anywhere on screen, which looks like a Chrome bug. Safari keeps "standard" clipped in the same setup, and so does this PR, since the "standard" layer asks for tone mapping to SDR itself. The diagnostic screen in this PR reproduces the same thing on main, with the same buttons.

… 15+

With wantsExtendedDynamicRangeContent = NO alone, a "standard" float
canvas stops clipping at SDR white as soon as another layer on screen
shows EDR: per CAMetalLayer.h, all rendered content is then clamped to the
screen's EDR maximum rather than 1.0. On iOS and macOS 27.2.1, an
"extended" canvas next to a "standard" one made both look the same.

The layer now sets toneMapMode. "standard" is tone mapped to SDR from a
declared contentsHeadroom of 1.0, which keeps values up to 1.0 as they are
and clips above, next to an EDR layer too. "extended" is never tone
mapped, so its values are shown up to the display's headroom without
being compressed.

On the 26 SDKs the layer also sets preferredDynamicRange and
contentsHeadroom, which replace the deprecated
wantsExtendedDynamicRangeContent (still set for iOS 16 to 25). The 18 and
26 SDK APIs are guarded at compile time, so older Xcodes keep building.
Diagnostics > Canvas toneMapping shows an "extended" and a "standard"
canvas side by side, each a ramp from 0 to 4.0 with a marker at 1.0 and
steps of 0.5 above it, next to a strip of plain SDR white. Buttons mount
either canvas alone and switch the format between rgba16float and
bgra8unorm. A screenshot does not capture EDR, so the result is checked by
eye on an HDR display.
@andreialecu
andreialecu force-pushed the fix/canvas-tonemapping-standard branch from cc4f520 to 947226e Compare November 25, 2026 13:34
@andreialecu

Copy link
Copy Markdown
Contributor Author

I opened a Chromium bug report for this as well: https://issues.chromium.org/issues/590212663

@andreialecu

Copy link
Copy Markdown
Contributor Author

FWIW: Someone from Google commented on the CRBug report and confirmed the bug.

This is probably extremely low occurrence, however, so feel free not to give it a high priority.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant