Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ Supported platforms:

See autogenerated API docs at [https://jetbrains.github.io/skiko/](https://jetbrains.github.io/skiko/)

For experimental web rendering at 120 Hz using a transferred `OffscreenCanvas`, see
[the high refresh rate guide](WEB_HIGH_REFRESH_RATE.md).

## Using as dependency

To use in build scripts one has to compute appropriate target platform and version,
Expand Down
76 changes: 76 additions & 0 deletions WEB_HIGH_REFRESH_RATE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
# Experimental 120 Hz rendering on the web

Enable the experiment before attaching an HTML canvas:

```kotlin
@OptIn(ExperimentalSkikoApi::class)
fun attach(canvas: HTMLCanvasElement): SkiaLayer = SkiaLayer().apply {
experimentalHighRefreshRateEnabled = true
renderDelegate = SkiaLayerRenderDelegate(this, myRenderDelegate)
attachTo(canvas)
needRender()
}
```

The API is available on Kotlin/JS and Kotlin/Wasm. Rendering and DOM input
handlers stay on the main thread. The flag is off by default and cannot change
while attached.

## How it works

Based on Rida F'kih's [Safari 60 FPS bypass experiment](https://rida.dev/blog/bypassing-ios-safari-60-fps-limit):

- Transfer the HTML canvas to an `OffscreenCanvas` and draw through its WebGL2
context. The original element remains a placeholder, returned by `component`.
Placeholder presentation is the bypass; a faster timer alone is insufficient.
- Pace requested frames with timer/MessageChannel tasks aligned to rAF timestamps,
allowing two frames per 60 Hz rAF interval. Account for iOS clock rounding and
skip missed deadlines after a stall.
- While rendering, share a tiny smooth scroller with a composited animation to
encourage ProMotion to use 120 Hz. Idle or hidden layers stop their timers,
rAF loop and display boost. Visibility restoration resumes pending requests.

The main-thread presentation path is inferred from WebKit's
[OffscreenCanvas task submission](https://github.com/WebKit/WebKit/blob/main/Source/WebCore/html/OffscreenCanvas.cpp)
and [asynchronous placeholder display](https://github.com/WebKit/WebKit/blob/main/Source/WebCore/html/canvas/PlaceholderRenderingContext.cpp).
Physical 120 Hz presentation on iOS still requires device validation; it has not
been established by the Chromium checks.

## Resize, reattach and fallback

If transfer or OffscreenCanvas WebGL2 is unavailable, or the HTML canvas already
has a context, attachment falls back to ordinary rAF.

Transfer is irreversible. Set CSS size normally, then call
`layer.resize(physicalWidth, physicalHeight)` instead of assigning the HTML
canvas's `width` or `height`. Skiko resizes the backing buffer and drawing surface.
The backing is cached in a `WeakMap`, so detach/reattach does not transfer it twice.
Disabling the flag after detach restores rAF scheduling but retains that backing;
use a new HTML canvas to restore an ordinary rendering context.

Request each next frame with `needRender()`, as `SkiaLayerRenderDelegate` does.
`detach()` cancels pending work, removes listeners, closes MessageChannel ports
and releases Skia resources. Frame timestamps use the window's performance clock.

Compose and other hosts must adopt `layer.resize()` before enabling the flag.
A host using its own 60 Hz animation clock must adapt it too: Skiko does not
produce intermediate application states or replace that clock. Native scroll
controllers and higher-frequency gesture input from the article are separate
host integrations; this experiment changes rendering only.

## Sample and device checks

```shell
cd samples/SkiaWebSample
./gradlew jsBrowserDevelopmentRun -Pskiko.composite.build=1
# Or: ./gradlew wasmJsBrowserDevelopmentRun -Pskiko.composite.build=1
```

Open `offscreen.html`, linked from the regular sample. It compares normal and
experimental rendering. Uncheck Animate, resize, and background/restore the page
to check lifecycle behavior.

Counters measure render callbacks, not presented frames. Validate on a ProMotion
iPhone using 240 FPS video or a presentation trace, with the normal canvas as a
60 Hz control. Check power settings, sustained pacing and idle energy use too.
WebKit may change this behavior, and the API remains experimental.
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,10 @@ private class DemoApp: SkikoRenderDelegate {
}

internal fun runApp() {
if (document.getElementById("high") != null) {
runHighRefreshRateDemo()
return
}
for (index in 1 .. 3) {
val skiaLayer = SkiaLayer()
val canvas = document.getElementById("c$index")!!
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
@file:OptIn(org.jetbrains.skiko.ExperimentalSkikoApi::class, kotlin.js.ExperimentalWasmJsInterop::class)

package org.jetbrains.skiko.sample.js

import kotlinx.browser.document
import org.jetbrains.skia.Color
import org.jetbrains.skia.Paint
import org.jetbrains.skiko.SkiaLayer
import org.jetbrains.skiko.SkikoRenderDelegate
import org.w3c.dom.HTMLCanvasElement
import kotlin.js.js

internal fun runHighRefreshRateDemo() {
val layers = mutableListOf<SkiaLayer>()
for (highRefresh in listOf(false, true)) {
val id = if (highRefresh) "high" else "normal"
val element = document.getElementById(id) as HTMLCanvasElement
val status = document.getElementById("$id-status")!!
val layer = SkiaLayer().apply { experimentalHighRefreshRateEnabled = highRefresh }
val paint = Paint().apply { color = if (highRefresh) Color.RED else Color.BLUE }
var start = 0L
var frames = 0
layer.renderDelegate = SkikoRenderDelegate { canvas, width, height, nanos ->
canvas.clear(Color.WHITE)
val x = ((nanos / 1_000_000.0 % 2000) / 2000 * width).toFloat()
canvas.drawCircle(x, height / 2f, 20 * layer.contentScale, paint)
if (start == 0L) start = nanos else frames++
val elapsed = (nanos - start) / 1_000_000.0
if (elapsed >= 1000) {
status.textContent = "${(frames * 1000 / elapsed).toInt()} render callbacks/s"
frames = 0
start = nanos
}
if (animationEnabled()) layer.needRender()
}
layer.attachTo(element)
observeSize(element) { width, height ->
layer.resize(width, height)
layer.needRender()
}
layer.needRender()
layers.add(layer)
}
onAnimationToggle { layers.forEach { it.needRender() } }
document.body!!.setAttribute("data-skiko-ready", "true")
}

private fun animationEnabled(): Boolean = js("document.getElementById('animate').checked")
private fun onAnimationToggle(callback: () -> Unit): Unit = js("document.getElementById('animate').addEventListener('change', callback)")
private fun observeSize(canvas: HTMLCanvasElement, callback: (Int, Int) -> Unit): Unit = js("""{
new ResizeObserver(function() {
callback(Math.round(canvas.clientWidth * devicePixelRatio), Math.round(canvas.clientHeight * devicePixelRatio));
}).observe(canvas);
}""")
1 change: 1 addition & 0 deletions samples/SkiaWebSample/src/webMain/resources/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@

<body>
<h1 id="description"></h1>
<p><a href="offscreen.html">Experimental 120 Hz rendering</a></p>
<canvas id="c1" width="600" height="600" style="width: 300px; height: 300px"></canvas>
<canvas id="c2" width="600" height="600" style="width: 300px; height: 300px"></canvas>
<div>
Expand Down
25 changes: 25 additions & 0 deletions samples/SkiaWebSample/src/webMain/resources/offscreen.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Skiko experimental 120 Hz rendering</title>
<style>
body { font: 16px system-ui; margin: 24px; }
canvas { display: block; width: 100%; height: 180px; border: 1px solid #888; }
</style>
<script src="webApp.js"></script>
<h1>Experimental 120 Hz rendering</h1>
<p>Both delegates run on the main thread. The experimental canvas uses a transferred
OffscreenCanvas, vsync phase, MessageChannel pacing and an active-only ProMotion boost.</p>
<p><label><input id="animate" type="checkbox" checked> Animate</label></p>
<h2>Ordinary canvas / rAF</h2>
<p id="normal-status" role="status">Starting…</p>
<canvas id="normal" width="900" height="180" aria-label="Normal rendering: moving blue circle"></canvas>
<h2>Experimental OffscreenCanvas / target 120</h2>
<p id="high-status" role="status">Starting…</p>
<canvas id="high" width="900" height="180" aria-label="Experimental rendering: moving red circle"></canvas>
<p>These counters measure render callbacks. They do not prove physical 120 FPS presentation.
If OffscreenCanvas transfer or WebGL2 is unavailable, the experiment falls back to rAF.
ProMotion activation uses a tiny background smooth scroller only during animation.</p>
<p><a href="index.html">Regular sample</a></p>
</html>
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
@file:OptIn(kotlin.js.ExperimentalWasmJsInterop::class)

package org.jetbrains.skiko

import kotlin.js.JsAny
import kotlin.js.js

internal class BrowserFrameClock : WebFrameClock {
private var channel: JsAny? = null
private var visibilityListener: JsAny? = null
private var active = false
private var nextId = 0
private val tasks = mutableMapOf<Int, () -> Unit>()

override fun now() = browserNow()
override fun requestAnimationFrame(callback: (Double) -> Unit) = browserRaf(callback)
override fun cancelAnimationFrame(id: Int) = browserCancelRaf(id)
override fun setTimeout(callback: () -> Unit, delay: Double) = browserTimeout(callback, delay)
override fun cancelTimeout(id: Int) = browserCancelTimeout(id)

override fun postTask(callback: () -> Unit): Int {
val port = channel ?: createChannel { id -> tasks.remove(id)?.invoke() }.also { channel = it }
val id = ++nextId
tasks[id] = callback
postChannel(port, id)
return id
}
override fun cancelTask(id: Int) {
tasks.remove(id)
}

override fun isVisible() = browserVisible()

override fun setVisibilityListener(callback: (() -> Unit)?) {
visibilityListener?.let(::removeVisibility)
visibilityListener = callback?.let(::addVisibility)
}

override fun setHighRefreshRateActive(active: Boolean) {
if (this.active == active) return
this.active = active
updateDisplayBoost(if (active) 1 else -1, displayBoost)
}

override fun close() {
setHighRefreshRateActive(false)
setVisibilityListener(null)
channel?.let(::closeChannel)
channel = null
tasks.clear()
}
}

private fun browserNow(): Double = js("performance.now()")
private fun browserRaf(callback: (Double) -> Unit): Int = js("requestAnimationFrame(callback)")
private fun browserCancelRaf(id: Int): Unit = js("cancelAnimationFrame(id)")
private fun browserTimeout(callback: () -> Unit, delay: Double): Int = js("setTimeout(callback, delay)")
private fun browserCancelTimeout(id: Int): Unit = js("clearTimeout(id)")
private fun browserVisible(): Boolean = js("!document.hidden")

// Keep the exact JS listener for removal on both Kotlin/JS and Kotlin/Wasm.
//language=JavaScript
private fun addVisibility(callback: () -> Unit): JsAny = js("""(function() {
document.addEventListener('visibilitychange', callback);
return callback;
})()""")
private fun removeVisibility(listener: JsAny): Unit = js("document.removeEventListener('visibilitychange', listener)")

//language=JavaScript
private fun createChannel(callback: (Int) -> Unit): JsAny = js("""(function() {
var channel = new MessageChannel();
channel.port1.onmessage = function(event) { callback(event.data); };
return channel;
})()""")
private fun postChannel(channel: JsAny, id: Int): Unit = js("channel.port2.postMessage(id)")
private fun closeChannel(channel: JsAny): Unit = js("{ channel.port1.close(); channel.port2.close(); }")

// ProMotion needs scrolling plus a compositor animation to reach 120 Hz. Share them between active layers.
private val displayBoost: JsAny = js("({ users: 0, element: null, timer: null, animation: null })")
//language=JavaScript
private fun updateDisplayBoost(delta: Int, state: JsAny): Unit = js("""(function() {
state.users += delta;
if (state.users > 0 && !state.element && document.body) {
var scroller = document.createElement('div');
scroller.setAttribute('data-skiko-refresh-boost', '');
scroller.setAttribute('aria-hidden', 'true');
scroller.style.cssText = 'position:fixed;left:0;bottom:0;width:1px;height:1px;overflow:hidden;opacity:0.01;pointer-events:none;contain:strict';
var animated = document.createElement('div');
animated.style.cssText = 'position:sticky;top:0;width:1px;height:1px;background:black;will-change:transform';
var spacer = document.createElement('div');
spacer.style.height = '10000px';
scroller.appendChild(animated);
scroller.appendChild(spacer);
document.body.appendChild(scroller);
state.element = scroller;
state.animation = animated.animate(
[{ transform: 'translateX(0)' }, { transform: 'translateX(0.1px)' }],
{ duration: 1000, iterations: Infinity, direction: 'alternate' }
);
var down = true;
var scroll = function() {
clearTimeout(state.timer);
if (state.element !== scroller) return;
scroller.scrollTo({ top: down ? 9000 : 0, behavior: 'smooth' });
down = !down;
state.timer = setTimeout(scroll, 1500);
};
scroller.addEventListener('scrollend', scroll);
state.timer = setTimeout(scroll, 0);
} else if (state.users === 0 && state.element) {
clearTimeout(state.timer);
state.animation.cancel();
state.element.remove();
state.element = null;
state.animation = null;
state.timer = null;
}
})()""")
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,12 @@ import org.jetbrains.skia.gpu.ganesh.makeFromBackendRenderTarget
import org.jetbrains.skia.impl.NativePointer
import org.jetbrains.skiko.wasm.EmscriptenWebGLContextAttributes
import org.khronos.webgl.WebGLRenderingContextBase
import org.w3c.dom.HTMLCanvasElement
import kotlin.js.ExperimentalWasmJsInterop
import kotlin.js.JsAny
import kotlin.js.js

/**
* CanvasRenderer takes an [HTMLCanvasElement] instance and initializes
* skiko's [Canvas] used for drawing (see [initCanvas]).
* Initializes Skiko's [Canvas] using an existing WebGL context (see [initCanvas]).
*
* After initialization [needRedraw] can be used to schedule a call to [drawFrame].
* [drawFrame] has to be implemented to perform the actual drawing on [canvas].
Expand All @@ -23,6 +22,7 @@ abstract class CanvasRenderer(
width: Int,
height: Int,
requestedSampleCount: Int = 1, // it must be the actual sampling from the current webgl context.
highRefreshRate: Boolean = false,
) {
var width: Int = width
private set
Expand Down Expand Up @@ -54,8 +54,7 @@ abstract class CanvasRenderer(
initCanvas()
}

private val requestAnimationFrameCallback: (timestamp: Double) -> Unit = callback@{ timestamp ->
redrawScheduled = false
private val frameScheduler = WebFrameScheduler(highRefreshRate) callback@{ timestamp ->
if (isDisposed) return@callback

GL.makeContextCurrent(contextPointer)
Expand Down Expand Up @@ -120,6 +119,7 @@ abstract class CanvasRenderer(
fun dispose() {
if (isDisposed) return
isDisposed = true
frameScheduler.dispose()
GL.makeContextCurrent(contextPointer)
disposeCanvas()
canvas = null
Expand All @@ -133,29 +133,17 @@ abstract class CanvasRenderer(
*/
abstract fun drawFrame(currentTimestamp: Double)

private var redrawScheduled = false

/**
* Schedules a call to [drawFrame] to the appropriate moment.
*/
@OptIn(ExperimentalWasmJsInterop::class)
fun needRedraw() {
if (isDisposed || redrawScheduled) {
return
}
redrawScheduled = true
windowRequestAnimationFrame(requestAnimationFrameCallback)
if (!isDisposed) frameScheduler.requestFrame()
}
}

@OptIn(ExperimentalWasmJsInterop::class)
private fun windowRequestAnimationFrame(callback: (Double) -> Unit) : Int =
//language=JavaScript
js("window.requestAnimationFrame(callback)")

@InternalSkikoApi
external interface GLInterface {
fun createContext(context: HTMLCanvasElement, contextAttributes: EmscriptenWebGLContextAttributes): NativePointer
fun createContext(context: JsAny, contextAttributes: EmscriptenWebGLContextAttributes): NativePointer
fun makeContextCurrent(contextPointer: NativePointer): Boolean
}

Expand All @@ -165,4 +153,4 @@ expect val GL: GLInterface
@InternalSkikoApi
@OptIn(ExperimentalWasmJsInterop::class)
fun currentGLContext(gl: GLInterface): WebGLRenderingContextBase? =
js("gl.currentContext ? gl.currentContext.GLctx : null")
js("gl.currentContext ? gl.currentContext.GLctx : null")
Loading
Loading