Lens-Defocus Blur at the Cost of Dual Kawase
Most system frosted-glass effects are built on Dual Kawase, whose iterated small kernels converge to a Gaussian and smear highlights into a milky haze. The method described here replaces iteration with a single dense disc gather, preserves the weight of highlights in a heuristically expanded pseudo-HDR working space, and uses pyramid prefiltering, constant offsets, 4×4 block merging and symmetric unrolling to bring the cost in the Lab at R = 40 down to about 1.15 ms (a converted figure), on par with Dual Kawase's 1.20 ms in the same run. Ported into Android's SurfaceFlinger as a binary patch, and limited by its fixed pipeline, it takes about 1.35–1.47 ms with chromatic aberration, roughly 1.9 times the stock Kawase (0.75 ms).
https://blog.kev1nweng.space/en/posts/lens-blur/
The “frosted glass” material of mobile operating systems is almost always built on the same family of algorithms. Android’s window compositor, SurfaceFlinger, uses a variant of Dual Kawase blur by default (KawaseBlurDualFilterV2): the image is first reduced to a low resolution, a small kernel with only a handful of taps is applied repeatedly, and the result is then upsampled level by level. It is extremely cheap, but the output has an instantly recognisable “milky” look: highlights are flattened, edges have no shape, and the whole picture appears to sit behind a layer of fog.
The defocus blur discussed in this article pursues a different goal: rather than imitating fog, it imitates lens defocus. The point spread function of an out-of-focus lens is a flat-topped disc, so point lights in the scene spread into crisp-edged discs of light (bokeh), and when the radius varies continuously the image takes on the look of a photographic rack focus. There is only one design constraint: on a mobile GPU, the cost must be comparable to Dual Kawase.
The algorithm was developed in two stages. The first took place in a debug page built into an Android app, referred to below as the Lab: it fills the screen with a test photograph, implements the entire pipeline pass by pass in AGSL (Android’s runtime shading language, a dialect of Skia’s shading language SkSL), allows the radius to be dragged and the algorithm switched in real time, and ships with an OpenGL ES timing harness. The Lab imposes no system-level constraints, and the algorithm settled into its “ideal form” there. The second stage ported it into SurfaceFlinger, where it had to compromise with the existing pipeline structure; this is covered in the second half of the article.
It is worth stating the scope up front. Real-time circular defocus has a long research history (see “Related work” at the end); this article proposes no new defocus model and does not claim a generally faster defocus algorithm. It targets a narrower setting that has received little attention: window blur with 8-bit intermediate buffers, a fixed pipeline structure, and a per-frame budget on a phone. Under these constraints the usual high-quality approaches, which rely either on floating-point buffers or on a freely programmable multi-pass pipeline, cannot be used directly. The contribution is a way to obtain a flat-topped, hard-edged disc under these constraints, and an engineering path for putting it into SurfaceFlinger as a pure data patch. On performance, the two implementations must be kept apart: “the cost of Dual Kawase” in the title refers to the Lab version, which at is on par with Dual Kawase measured in the same run; the SurfaceFlinger version, limited by the fixed pipeline, costs about 1.6 times the stock Kawase at the notification shade’s blur radius without chromatic aberration, and about 1.8–2.0 times with it.
Below is a WebGL2 port of the Lab version, mathematically identical to the one discussed in the text. I suggest starting with the “light tree” image and dragging the divider to compare how the two blurs treat point lights.
Algorithm overview
We first give the complete procedure; the sections that follow explain why each step is done the way it is. Let the full-resolution image be (8-bit, gamma-encoded) and the target disc radius be pixels. Each frame is computed in five steps:
- Choosing the level. From , determine the resolution level at which the gather takes place ( a power of two); the disc radius at that level is texels. At the same time, the CPU generates the sampling layout (the offset and type of each tap) and the weights of the three channels.
- Pyramid prefiltering. Starting from , halve the resolution times, each level taking the HDR average of texels, to obtain ().
- Two average maps. At level , compute two further maps of the same size: the sub-block map (each texel is the HDR average of a neighbourhood) and the block map (the HDR average of a neighbourhood).
- Disc gather. For each output texel at level , read from or one tap at a time according to the layout, and sum with coverage weights in HDR space.
- Upsampling and compositing. Upsample the gather result back to full resolution with a cubic B-spline; for very small radii, additionally blend it with the original image in proportion.
All intermediate results are stored at 8 bits: before storing they are compressed back to encoded space with , and after reading they are immediately expanded with , so “HDR” only ever exists in shader registers. The table below lists the size of each pass for (, exact layout with 64 taps), with reads amortised over each full-resolution pixel:
| Step | Output resolution | Reads per output | Per pixel (amortised) |
|---|---|---|---|
| Pyramid | 1/2 | 4 | 1 |
| Pyramid | 1/4 | 4 | 1/4 |
| Sub-block map | 1/4 | 4 | 1/4 |
| Block map | 1/4 | 4 | 1/4 |
| Disc gather | 1/4 | 64 | 4 |
| B-spline upsampling | 1 | 4 (bilinear) | 4 |
| Total | ≈ 9.75 |
For comparison, direct convolution at full resolution requires reads per pixel.
The problem: why Kawase looks “milky”
The defocus point spread function
In the thin-lens model, a point at object distance forms, on an image plane focused at , a circle of confusion1 with diameter
where is the aperture diameter and the focal length. Ignoring diffraction and aberrations, the point spread function (PSF) of a circular aperture is a uniform disc:
For a background plane at a single depth, the defocused image is simply the convolution of the linear radiance with :
Two points matter here. First, the kernel is flat-topped and hard-edged. Second, the convolution acts on linear radiance, and a street lamp can be several orders of magnitude brighter than the wall around it; this is precisely why it can “spread out” into a bright disc.
Iterated small kernels and the central limit theorem
The efficiency of Kawase-style2 methods comes from iteration: each pass reads only 5 to 9 samples, but after chaining several passes the overall equivalent kernel is the convolution of the per-pass small kernels,
If every pass were a shift-invariant convolution, the central limit theorem would say that repeated convolution of small kernels tends to a Gaussian as grows, with covariance equal to the sum of the individual covariances, . A Gaussian kernel has no flat top and no edge; its energy decays smoothly with radius, so a point light is smeared into a blurry glow. Figure 2 demonstrates this convergence using separable box kernels. For ease of comparison, all three curves have the same second moment as a disc of radius , i.e. a per-axis variance of
Specifically for Dual Kawase (Bjørge, SIGGRAPH 2015)3: a downsampling pass halves the resolution and reads 5 times per output, with a centre weight of and for each of the four diagonals; an upsampling pass doubles the resolution and reads 8 times, for each of the 4 axial points and for each of the 4 diagonal points. With an offset of texels,
where ranges over the four axial unit vectors. Each read is itself a hardware bilinear interpolation, i.e. a small tent kernel. downsampling levels plus upsampling levels can be viewed, approximately, as a chain of small kernels. This is an intuition rather than a derivation: downsampling and upsampling change the sampling rate, the passes operate at different spatial scales and sampling phases, and the pipeline as a whole is periodically shift-variant rather than a repeated convolution with shift-invariant kernels, so the central limit theorem does not apply directly. What it explains is the trend, that chaining passes pushes the kernel towards a smooth bell shape without a flat top; a rigorous statement would rest on measured impulse responses; moreover, all averaging takes place in encoded space, a point we will return to later. For a fair comparison, the demo in Figure 1 matches the two methods by second moment: it measures the of Dual Kawase on the impulse response for each level count and offset, takes the smallest number of levels that can achieve , and interpolates the offset within .
The first principle of our method is therefore: perform a single disc convolution, without iteration. The difficulty is that computing this convolution directly costs reads per pixel; on a 1260×2800 screen with that is about reads, two to three orders of magnitude more than Dual Kawase. Everything that follows is about cutting this number down without changing the shape of the kernel.
Preserving highlights in a pseudo-HDR working space
Pixels on screen are gamma-encoded values clamped to . A street lamp in the image is and a wall might be : their encoded values differ by less than a factor of two, while their true radiances may differ by a factor of a hundred. Averaging the encoded values directly dilutes the lamp’s brightness rapidly into the surrounding pixels.
It must be stressed that true scene radiance cannot be recovered from an SDR image that has already been clipped: a pixel encoded as 1.0 may have been a lamp or merely an overexposed white wall, and that information was lost at clipping. All the method can do is introduce a prior: pixels close to saturation should be given extra brightness weight. The prior is visually well motivated (the brightest things in a picture usually are light sources), but it is a heuristic highlight expansion and cannot recover an HDR signal.
Concretely, when reading each sample, the algorithm first maps the stored value into a pseudo-HDR working space:
where the square is a cheap approximation of the sRGB transfer function (), the fractional part is an inverse Reinhard tone map4 that uses the channel maximum as luminance, and controls the strength of highlight expansion. One can verify that , and since all three channels share the same scale factor, hue is preserved. Pure white maps to ; with this is , i.e. a saturated pixel is treated as “at least 2.5 times brighter than white”.
All averaging is done in space, and results are compressed back with before being stored in 8-bit textures. For brevity, “HDR average” and “HDR value” below refer to quantities in this working space; preserving highlights means only that the samples keep their total weight in this space, which has nothing to do with physical energy conservation. Intermediate results therefore need no floating-point buffers, which is fortunate, since SurfaceFlinger’s intermediate surfaces are only 8-bit.
Whether 8 bits are enough can be computed directly. Let the stored value be with a quantisation step of ; the step in space is then
In the shadows, , the step tends to zero, for the same reason that sRGB storage concentrates code values in the dark end; at pure white () the step is about , roughly 2% of the value there. In other words, compressing back into encoded space is itself a sensible non-uniform quantisation, whose cost is concentrated at the highlight end where differences are invisible anyway.
Dense disc sampling
Why sparse sampling fails
The usual way to reduce cost is sparse sampling: place samples inside the disc along a golden-angle spiral (game engines commonly use ),
The mean spacing of the samples is about . For and , px, far larger than the lamp itself. By the sampling theorem, all frequencies above alias: a small bright point is hit by only a scattered few samples, and the bokeh disc turns into a regular dot lattice. Adding a random per-pixel rotation trades the lattice for noise, but noise is just as conspicuous against a large blurred background. Our first implementation did exactly this, and we eventually abandoned the approach.
Reading every texel at reduced resolution
The alternative is to guarantee that every texel is read, but to do so at a sufficiently low resolution. Suppose the gather is performed at level , where the disc has radius texels. If each read additionally covers a sub-block (quad), the number of reads is
a reduction by a factor of relative to brute-force convolution.
Choosing the level
The level is chosen automatically from the radius:
and if the resulting layout exceeds 160 taps, is doubled. For this keeps . The lower bound is perceptual: with a radius below 8 texels the disc is rendered as a polygon with rounded corners ( at level 1/8 has only 5 texels, and even with B-spline upsampling the edge is visibly soft). The upper bound is about cost. The lower bound of 4 on comes from the other side: reads grow as , level 1/4 is already cheap enough for , going one level finer would multiply the reads by 16, and at those radii the disc is only a few dozen pixels wide on screen anyway. The levels used in practice are therefore 1/4 for , 1/8 for , and 1/16 above that; the 160-tap limit has never been triggered in practice. (The demo in Figure 1 targets small 1200-pixel-wide images and does not impose the lower bound, so at small radii it lands on finer levels.)
When the radius crosses 64 or 128 the level switches and drops abruptly from about 16 to 8. Both sides describe a disc of the same radius , so its size does not jump, but the width of the edge transition band (about one texel, i.e. pixels) doubles, and a slight jump in edge sharpness can be noticed during a slow rack focus. This is a known defect retained in the current implementation; it could be removed by cross-fading the results of the two levels, but this has not been done.
At the other extreme, once the radius is smaller than a texel the disc loses its meaning. When compositing, the upsampled result is laid over the original image with
so that with it is fully opaque for , and as it falls back smoothly to the original image instead of switching abruptly between a 1/4-resolution blur and the original.
The pyramid, the sub-block map and the block map
Every prefiltering step is “read four texel centres, expand, average, compress back”. As a recurrence:
All three use the same shader with different scale and stride. When halving, the scale is 2 and the stride 1, so the reads land exactly on the centres of texels and of the previous level and every source pixel is read exactly once. For the scale is 1 and the stride 1; it has the same size as , and texel holds the average of the sub-block starting at . For the scale is 1 and the stride 2, and it reads , so it holds the average of the block starting at .
Ignoring 8-bit quantisation, the mean of means of equal-sized groups is still the mean, so is exactly the HDR average of the full-resolution image over an square. Note that and do not reduce resolution: they are as large as , and every texel position holds the average of the sub-block (block) starting there. This is what allows the gather to use the same set of offsets for every output position.
Disc-centre convention and coverage weights
During the gather, the disc for output texel is centred not at the centre of but at the corner shared by and . The reason is that sub-block offsets are always even: tap covers texels . With the centre on a corner, the sub-blocks tile the plane symmetrically about the centre and the layout has the 8-fold symmetry a disc should have; with the centre on a texel centre, the sub-block grid is offset by half a texel from the disc centre and the layout is asymmetric along each axis. The price is that the gather result as a whole is shifted by half a texel, which is simply subtracted from the coordinates during upsampling (see below).
The disc edge is antialiased by texel coverage. Let the disc radius at this level be and the distance from the centre of texel to the disc centre be ; its coverage is approximated by a linear ramp one texel wide:
For an axis-aligned straight edge this is exactly the area of a unit texel lying inside the edge; for a circle with a radius of several texels, the error due to curvature is small, and . The weight of a sub-block or block is the sum of the coverages of the texels it contains:
A fully covered block has weight , a fully covered sub-block , and edge sub-blocks lie between and .
This formulation is exact for fully covered sub-blocks and an approximation for partially covered sub-blocks on the edge: such a sub-block contributes , whereas the exact value is (where is the HDR value of a texel and the sub-block mean). The difference is
i.e. the covariance between coverage and image content within the sub-block. It appears only in the outermost ring of sub-blocks, and is significant only when a bright point happens to fall where coverage varies within a sub-block; its effect amounts to slightly smoothing the bokeh edge at sub-block scale. Nor does it change the total in space, but that conclusion has explicit premises: the normalisation depends only on the layout, not on image content; the domain is unbounded (or periodically extended); and quantisation is ignored. Summing over all output positions , both and at every texel position equal the image total, so the error becomes a multiple of and cancels exactly. In the actual implementation, clamp addressing at the image border and 8-bit storage both break this, though only near the border and at the scale of quantisation error.
Two boundary cases. When the radius is below about 0.2 texels, no texel centre falls inside the disc and ; in that case the gather degenerates to the centre sub-block alone with weight 1 (without this, the image would flash black as approaches 0). Image borders are not tested explicitly: taps always land on texel centres, and the texture’s clamp addressing mode repeats the edge pixels.
Selecting the 4×4 blocks
Four adjacent sub-blocks are merged into a block when all of them lie entirely inside the smallest disc (which, without chromatic aberration, is the disc itself). The block origin must lie on a lattice of spacing 4, and there are four choices of lattice phase, , each yielding a different number of mergeable blocks. Layout generation tries all four, keeps the one with the fewest total taps (remaining sub-blocks plus blocks), and then sorts taps in row-major order to favour the texture cache. Because only texels with coverage exactly 1 are merged, a block’s weight is exactly the sum of its 16 texels, and in exact arithmetic the result is algebraically equivalent to reading sub-block by sub-block. Algebraic equivalence is not bitwise identity, however: the block map is obtained by averaging once more, which adds another compression, 8-bit quantisation and expansion, and the shader accumulates in half precision, so the rounding paths differ and the two implementations may disagree in the last few bits. Going further to blocks was also tried: at it only brings 64 taps down to 61, at the cost of an extra prefiltering pass, which is not worth it.
A nonlinear trap
Using the GPU’s bilinear filtering to read the average of texels in one fetch looks like a free optimisation, but it quietly corrupts the result. An 8-bit texture stores encoded values; the hardware interpolates first, in encoded space, and only afterwards does the shader expand the value into space, whereas the correct order is to expand first and then average. Since is convex, Jensen’s inequality gives
so the wrong order systematically biases the average in space low, darkening the image, and the stronger the contrast, the larger the bias. Worse, when the tap coordinates are misaligned with the texture by a periodic half-texel offset, odd and even columns lose different amounts, and vertical stripes with a period of 16 px appear in the image. The fix is to fold the average into the prefilter: each texel is expanded in space before averaging, and the gather reads only at texel centres, bypassing hardware interpolation altogether. The same principle applies to the later SurfaceFlinger version.
Working-space brightness loss 62.9%
Cubic B-spline upsampling
The gather result lives at level , and the final step upsamples it by a factor of . Bilinear interpolation exposes the underlying grid at 4× and 8× magnification: the interpolant has a derivative discontinuity at every texel, and blocky contours and diamond patterns appear on smooth bokeh. A cubic B-spline is used instead. In one dimension, denote the samples to be upsampled by ; at position , let and ,
The B-spline is continuous, so the grid is no longer visible; and unlike interpolating cubic kernels such as Catmull–Rom, its four weights are all non-negative, so it produces no overshoot or ringing at the edges of bright bokeh.
Non-negative weights also bring an implementation convenience (Sigg & Hadwiger, GPU Gems 2, ch. 20)5: two adjacent terms can be merged into a single hardware bilinear fetch. Let and ; then
and the latter is precisely one linearly interpolated fetch at position , with guaranteeing that the fetch lands between the two texels. The two-dimensional case is separable, so the original fetches become 4 bilinear fetches. In terms of coordinates, the sample position corresponding to the full-resolution pixel centre is
where the first converts a pixel centre to a texel index, and the second removes the half-texel offset introduced by the “disc centre on a corner” convention above. (The sign of this term was originally wrong, shifting the whole result by about pixels; it was eventually located by a px translation search against a reference Gaussian blur, minimising squared error, and after the fix the residual offset is at most 1 pixel.)
This pass interpolates 8-bit encoded values, which seems to contradict the principle of the previous section, but does not. Let two adjacent samples be and the interpolation fraction ; the error in space is
which is second order in the difference between neighbours. Here, however, are encoded stored values, and the curvature is not constant (in the scalar case , which for grows from 2 in the shadows to 87.5 at white), so a small squared difference does not by itself mean a small error. It is better to express the difference in the working space. Let and let be the working-space difference between neighbours; to first order , which gives
The curvature is large at white, but so is the slope , so the same working-space difference corresponds to a smaller encoded difference, and the two cancel in : it only ranges between and . Since , the relative error is at most about , where is the relative working-space difference between neighbours.
How large is depends on where we are. The input to the gather is the unblurred original image, where adjacent texels can jump from 0 to 1, so is of order 1 and the error is of the same order as the signal; that is exactly why the gather must expand before averaging. The input to upsampling has already been smoothed by a disc of radius : translating the disc by one texel replaces about of its area, so inside a bokeh disc and on smooth backgrounds is about times the ratio of the local dynamic range to ; when that ratio is of order 1 and , and the relative error is about 0.1%. The estimate breaks down where is small compared with the local variation, typically at the edge of a bokeh disc on a dark background: there the input to upsampling rises from near 0 to the disc’s brightness within one or two texels, and is of order 1. Because is convex, encoded-space interpolation is systematically darker there, which pushes the brightness profile of the edge band inwards, as if the edge moved inwards by less than one texel; this happens only within the transition band, about pixels wide, and leaves the interior of the disc alone.
This is an asymptotic analysis in a scalar model (the three channels actually share one scale factor set by the largest channel); it gives the order of magnitude of the error, not a strict bound, and its actual size has not been checked against measured pixel differences.
The effective point spread function
Putting all the steps together, the kernel the algorithm actually applies to the image is not strictly a disc, but
where is the disc discretised with the coverage ramp, the box average introduced by the pyramid, and the B-spline upsampling by a factor of . The latter two both add extra blur. By second moments, the box has a per-axis variance of , and the cubic B-spline (the convolution of four unit boxes) has squared sample spacings, i.e. , so
For the extra variance is only 0.65%–2.6% of that of the disc itself, and barely changes the size of the bokeh. Its effect is concentrated at the edge, turning the ideal hard edge into a transition band about pixels wide, of order relative to the radius. This also explains why cannot be too small: at the transition band already takes up a fifth of the radius, and the bokeh looks “soft”.
The nature of this derivation needs stating. Writing as a convolution assumes that the whole pipeline is shift-invariant. In fact the pyramid decimates level by level, the gather is evaluated only on the grid, and the B-spline reconstructs between texels, and all three depend on sampling phase: the same point light at different sub-pixel positions within an block does not produce outputs that are translates of one another. Like Dual Kawase, this pipeline is periodically shift-variant, with period . In addition, edge sub-blocks use the sub-block mean instead of per-texel values (the covariance term above), so the edge of the effective kernel also depends on how content is distributed within a sub-block, which the formula leaves out. The variance formula above should therefore be read as a continuous-domain approximation averaged over sampling phase: it describes the order of magnitude of the bokeh’s size and edge width, and cannot be taken as a strict error bound for the full discrete pipeline. A rigorous characterisation would require measuring impulse responses at different sub-pixel phases, which this article has not done yet.
Bringing the cost down to Kawase’s level
Once correctness was settled, the first version took 2.51 ms at , about 3 times Dual Kawase. Timings were taken with the Lab’s timing harness: it replays the same shaders in a separate OpenGL ES 3 context and uses GL_TIME_ELAPSED queries to read the GPU execution time of each pass directly, unaffected by CPU scheduling and display refresh. The test device was an Adreno 825 at 1260×2800, and we report the median of 40 runs after a warm-up to let clocks ramp up. The optimisations, one by one:
- Pyramid prefiltering. The initial version went straight to the target level with a single box filter. Adjacent outputs had overlapping footprints, so every full-resolution pixel was read 4 times, each time with a
powdecode. Switching to the same level-by-level halving as Kawase, with each level averaging texel centres in space, reads every source pixel exactly once; prefiltering dropped from 1.1–2.2 ms to about 0.3 ms. - A cheap transfer function. Replacing the sRGB curve with and eliminates
pow. - Constant offsets. Tap offsets were originally read in a loop from a uniform array, with a boundary clamp on every sample. Instead, a shader is generated per integer radius, with offsets written as compile-time constants and the loop fully unrolled; weights are still passed as uniforms and recomputed on the CPU every frame. One shader serves every disc whose radius falls in (with the chromatic aberration amount rounded up to a multiple of 0.02), so the radius can vary continuously during a rack-focus animation without compiling a new shader every frame. Since samples always land on texel centres, clamping can be left to the texture’s
CLAMPaddressing mode. This made the gather about 40% faster. - 4×4 block merging. Four adjacent sub-blocks fully covered by the disc have equal weights and can be read in a single fetch from a block-average map. Because only texels with weight 1 are merged, the result is equivalent in exact arithmetic to reading sub-block by sub-block, apart from rounding differences from one extra 8-bit quantisation. The choice of phase is described above. At the tap count dropped from 97 to 76, of which 11 are whole blocks.
- Exact layout. The general shader must cover a whole radius interval and therefore reads an extra ring of zero-weight samples. Once the radius has been static for 300 ms, a layout generated specifically for that radius is compiled and swapped in, cutting taps by a further 16% (76 → 64); combined with half-precision arithmetic, the gather pass becomes about 18% faster.
Also tested or evaluated but not adopted: hexagonal bokeh (Frostbite-style6 three skewed 1D box filters; the shape is wrong), complex separable circular kernels (Garcia 20177; intermediate results contain negative values and require floating-point buffers, while SurfaceFlinger’s intermediate surfaces are only 8-bit), placing at level 1/8 (about 0.9–1.1 ms in total, faster than Kawase, but the bokeh is visibly soft), fp16 linear textures (only about 6% faster, at double the bandwidth), and half-precision arithmetic (about 3%; the gather is bound by texture reads, not arithmetic).
The final pipeline at takes about 1.15 ms, against 1.20 ms for Dual Kawase in the same measurement run, a ratio of about 0.96: the two are on par. Note that 1.15 ms was not measured directly: the exact-layout row is converted from the gather ÷ upscale time ratio measured in the same run, at the GPU clock of the row without chromatic aberration (see the caption of Figure 6), which is weaker evidence than a directly measured end-to-end GPU time; what can be said with confidence is that the Lab version is on the same level as Dual Kawase. These conclusions apply to the Lab only; the cost of the SurfaceFlinger version is given later. For reference, a textbook brute-force convolution at full resolution reads about 5000 times per pixel; at the same read throughput, a single pass would take about 0.4 s, roughly 350 times slower than our method.
Axial chromatic aberration
The refractive index of a real lens varies with wavelength, and out-of-focus bokeh often carries a coloured fringe. We model this as concentric discs with a different radius per channel:
A naive implementation reads once per channel, and after multiplying the offsets by they no longer land on texel centres, re-triggering the nonlinearity problem described above. Since the three discs are concentric, however, the layout can be unified: the sample set consists of every sub-block touched by the largest (red) disc, and blocks are used only where the smallest (blue) disc covers them completely. Each sample is read only once, and the three channels are weighted by their own coverages,
In a shader that serves a radius interval, “touched” is judged against the red disc at the upper end of the interval, , and “completely covered” against the blue disc at the lower end, , so the same layout holds for any radius and aberration amount within the interval. All samples still land on texel centres, and the result is per-pixel correct, just as without aberration. The only extra cost comes from the wider outer ring of the red disc and from fewer mergeable blocks.
| CA κ | Taps | Gather time (relative to κ = 0) |
|---|---|---|
| 0 | 76 | 1.00× |
| 0.05 | 107 | ≈ 1.40× |
| 0.10 | 113 | ≈ 1.45× |
| 0.20 | 143 | ≈ 1.90× |
Porting to SurfaceFlinger
Why it has to be in SurfaceFlinger
What the notification shade, Quick Settings and similar interfaces blur is the content of other windows. The system process that draws these interfaces, SystemUI, is like any ordinary app in that it cannot read other windows’ pixels; only SurfaceFlinger, which composites all windows onto the screen, holds all of them at once, so cross-window blur can only be done there.
None of the usual means of modifying SurfaceFlinger are available. Xposed-style frameworks on Android inject code into apps via zygote (the “parent process” of all app processes), but SurfaceFlinger is launched directly by init, the system’s first process, without going through zygote. Its GPU compositing module, RenderEngine, and the graphics library Skia are statically linked into the same stripped executable, leaving no dynamic-library interface to hook. On the other hand, the blur shaders are stored in the binary as SkSL source strings and only handed to Skia for compilation at runtime, which leaves a sufficiently clean point of entry: inject no code, change only data. That is, replace the source text of the shaders, plus a few constants that control the structure of the pipeline.
How to modify a system binary safely
Concretely, /system/bin/surfaceflinger is copied off the phone, patched on a computer by a Python script, and the patched version is put back on the phone. The system partition is read-only and verified, so the original file is not actually overwritten. Instead, a module for KernelSU (a solution that provides root access and a module mechanism at the kernel level) uses a bind mount early in boot to “mount” the patched version over the original path: from then on, any process that opens /system/bin/surfaceflinger reads the patched version, while not a single byte of the system partition itself has changed.
The patch script follows one rule: every patch site is located by content, and must match exactly once; otherwise not a single byte is written. Shaders are found by their original text (including the string terminators at both ends); the scale table is found by its 16 bytes of floating-point values; and for the few places where machine instructions must be changed, the corresponding function is located in the binary first (although the executable is stripped of the regular symbol table, it still carries a compressed minimal symbol table, .gnu_debugdata, used to print stack traces on crashes, from which the function’s address range can be obtained), and then matched by instruction sequence within that function. This way, even if a system update changes the binary’s layout, the script will merely refuse to work rather than write bytes to the wrong place.
The installation side has two layers of protection as well. First, the module only takes effect on the one original binary recorded at build time: at boot it verifies the SHA-256 of both the current system file and the patched file, and if either does not match (for example, because the system has been updated), it leaves everything as is. Second, if the patched version prevents the device from booting, the module disables itself on the next boot: before mounting it leaves a marker file, which is deleted only after boot has completed and SurfaceFlinger has run stably for 60 seconds; if a boot finds the marker still present, the previous boot did not complete normally, and the patch is not mounted.
The original pipeline
First, the thing being replaced. The blur radius that SurfaceFlinger requests from RenderEngine follows the semantics of Skia’s Gaussian blur. KawaseBlurDualFilterV2 first converts it to , then determines the iteration depth and the offset of each pass:
Following the scale table kScales , the intermediate surfaces are at 1/4, 1/8, 1/16 and 1/32 resolution respectively. The pipeline first reduces the full-resolution image to 1/4 with 4 bilinear fetches, then downsamples level by level times, then upsamples level by level back to 1/4. Each upsampling pass reads the centre and 7 points on a regular heptagon (of radius step), weighted by , with output opacity ; when it is blended (SrcOver) over the existing downsampled result at that level, which makes the depth vary continuously. Finally, drawBlurRegion maps the 1/4 result back to the screen with a bilinear ×4, using mirror tiling; when it is additionally blended with the original image by . Every single average in this process is taken in encoded space.
The patched pipeline
The patch changes only data, not control flow, so the defocus blur must be squeezed into the fixed structure above:
- The scale table becomes , and the depth limit is changed from 3 to 1. The scale table is a static array, so changing data suffices; the depth limit, however, is a constant the compiler embedded directly in the machine code. In
generateTemporaryImage, the function that executes the whole pipeline, it is an ARM64 instruction loading the floating-point immediate 3.0 into a register (fmov #3.0), immediately followed by a minimum instruction. Changing that instruction’s immediate field to 1.0 does the job. Thus , leaving a single “downsample” and a single “upsample”, and both intermediate surfaces are at 1/4 resolution. - Three SkSL strings are replaced in place: full resolution → becomes an HDR box average (
sf_quarter, 278 bytes); becomes the sub-block map (sf_half, 260 bytes); and the upsample becomes the disc gather (sf_gather). - In
drawBlurRegion, the function that maps the 1/4 result back to the screen, two tile modes (again immediates in instructions) are changed from mirror (kMirror) to clamp (kClamp): when the notification shade is pulled down the content shrinks, the blur result no longer covers the whole area, and mirroring would reflect a copy on the left and right.
Compared with the Lab version, this pipeline makes three unavoidable compromises.
First, there is no pyramid. sf_quarter reads four points at in 1/4 coordinates, corresponding to full-resolution pixel corners; each fetch yields a average via hardware bilinear filtering, and the four fetches are then averaged in space, giving a box in total. This means the innermost is still averaged in encoded space: the Jensen error is not fully eliminated, but it is confined to the scale of full-resolution pixels and is noticeable only on bright points a single pixel wide.
Second, there is no B-spline. The final upsampling is done by SF’s own drawBlurRegion and can only be bilinear ×4; fortunately, grid artefacts at 4× magnification are far less visible than at the 8× seen in the Lab. A subtler issue is half-texel alignment: the Lab removes the “disc centre on a corner” offset during upsampling, but SF’s compositing has no such parameter. The patch moves the offset to the first pass: sf_quarter first executes xy -= .5, shifting every texel of by half a 1/4-level texel. As a result, sub-block of sf_half covers full-resolution , centred exactly at , which is the centre of 1/4-level texel . In simulation, a px translation search between the SF pipeline’s output and the Lab disc finds the best offset at .
Third, there is no block map; see the next section.
Mapping radius and fade-in
All that sf_gather receives are the three uniforms SF prepares for the original upsampling pass: in_blurOffset (i.e. step), in_crossFade (i.e. ) and in_weightedCrossFade. It needs to recover from these. With , the step formula above simplifies to
which means the shader can recover the radius requested by SF exactly, without any empirical fitting. What remains is a design choice: with the notification shade fully expanded, , and we want the disc radius to be 48 px at that point, i.e. 12 texels at level 1/4, scaling linearly with :
This is where the .815 in that code comes from.
itself also handles the fade-in: , which is below 1 for (a disc smaller than about 8 px). sf_gather outputs opacity-premultiplied colour , which SF blends over with standard alpha blending (SrcOver); at this point holds exactly the box average from sf_quarter, so the result is . For , drawBlurRegion blends once more with the full-resolution original. As the radius tends to zero, the image falls back smoothly to the original, serving the same purpose as the fade-in in the Lab. in_weightedCrossFade is no longer used, but its declaration must be kept, because SF sets it by name.
8-fold symmetric unrolling
Half of the optimisations that worked in the Lab are unavailable here: the fixed pipeline has no spare pass in which to generate a block-average map, and the gather has no second input texture to read. The first version of the gather was a double loop over , and the whole pipeline took about 1.75 ms at . Analysis showed that the bottleneck was not texture reads but per-sample arithmetic: loop control, a square root for the distance, and the coverage computation.
The solution exploits the 8-fold symmetry of the disc. Under the “disc centre on a corner” convention, the distance from the centre of sub-block to the disc centre is texels, the same as for and , so they can all share one weight:
Converted back to texel units, , where is the distance of the sub-block centre: a linear ramp 2 texels wide centred at . Compared with the Lab’s per-texel summed coverage, it antialiases at sub-block granularity, which is slightly coarser, but each group needs only a single constant distance. When or a group contains only 4 distinct sub-blocks, otherwise 8; the centre sub-block is handled separately.
The distances thus become compile-time constants, the weight is computed once for every 4 or 8 reads in a group, and the only per-sample work left is the texture read itself. After unrolling, the whole pipeline dropped to about 1.22 ms at .
With chromatic aberration added, each channel has its own , with hard-coded in the shader. Groups are generated for , 26 groups in all; each group first checks the weight of the red channel (the widest disc), and returns immediately if it is zero. This branch depends only on uniforms, so all fragments in a frame take the same path and there is no divergence, yet it lets small radii skip every read outside the disc: at there are 161 reads (137 without aberration), 69 at 8, and 21 at 4. Colour and weight are accumulated separately for the three channels and normalised per channel by division at the end.
| SF blur radius | Kawase V2 (stock) | Looped gather | Symmetric unroll | Unroll + CA 0.1 |
|---|---|---|---|---|
| 102 | 0.75 | 1.75 | 1.22 | 1.35–1.47 |
| 51 | 0.45 | ≈ 0.60 | 0.66 | — |
Appendix: 1071 bytes of “art”
There was an unusual constraint here: the new shader had to be written in place over the original upsampling shader, and that string is only 1093 bytes long. The reason lies in how SurfaceFlinger refers to this text. At startup, a piece of initialisation code constructs the string object (Skia’s SkString) with three instructions: adrp and add together compute the address of the text (the former gives the 4 KB page, the latter adds the offset within the page), and another instruction passes the length 1093 as an immediate. As long as the new text is no longer than the original, it can be overwritten in place and padded with spaces at the end, and none of these three instructions need to change. Anything longer would mean moving the text elsewhere, rewriting the address and length fields of these three instructions, and extending the boundary of the executable’s read-only segment so that the new location is mapped into memory; every additional change to the binary’s structure adds to the risk of a failed boot.
The first symmetric-unrolled shader was therefore not written by hand, but emitted by a Python generator of about forty lines. The script works in three steps. First, it enumerates the groups: for every integer pair with it computes , keeps those with (groups further out have zero weight even at the maximum radius), and sorts by , giving 22 groups. Only the octant with is taken; the other seven are filled in by the symmetric expansion inside the shader. Second, for each group it emits a call S+=g(i,j,k);, writing every number in its shortest form: 2. rather than 2.0, with distances kept to one decimal place (precise enough for an antialiasing ramp 2 texels wide). Third, it embeds these calls in a fixed template and prints the total byte count for comparison with 1093.
The template itself also makes trade-offs for length: all whitespace and comments are removed; every variable is a single letter; the read position x and radius H are passed through globals, saving per-call arguments; the function g first reads four directions ( and the 90°-rotated ), and when reads the other four mirrored ones; the centre sub-block gets no code of its own but borrows g(0.,0.,0.), in which case the four directional reads are the same position, and the result is multiplied by to compensate; each group’s colour and weight are packed into the rgb and a components of a single half4 and accumulated together, and normalised in one step with S.rgb/S.a at the end. In the end, the 22 groups of samples fit into exactly 1071 bytes, 22 bytes under the limit.
It is presented below verbatim, without any formatting, merely soft-wrapped:
uniform shader child;uniform float in_blurOffset;uniform float in_crossFade;uniform float in_weightedCrossFade; half3 e( float2 p) { half3 y=child.eval( p) .rgb; y*=y;return y/(1.-.6*max(max( y.r, y.g) , y.b) ) ; } float2 x;float H; half4 g(float u,float v,float k) {float w=clamp( H-k,0.,1.) ;if( w<=0.)return half4(0.) ; float2 p=float2( u, v)*2., q=float2(-v, u)*2.; half3 s=e( x+p)+e( x-p)+e( x+q)+e( x-q) ;float n=4.;if( u>0.&&u<v) { p=p.yx; q=float2(-u, v)*2.; s+=e( x+p)+e( x-p)+e( x+q)+e( x-q) ; n=8.; }return half4( s*half( w) ,half( n*w) ) ; } half4 main( float2 xy) { x=xy;float a=in_crossFade; H=min(.815*a*sqrt( in_blurOffset*in_blurOffset+.5) ,12.)*.5+.5; half4 S=g(0.,0.,0.)*.25; S+=g(0.,1.,1.) ; S+=g(1.,1.,1.4) ; S+=g(0.,2.,2.) ; S+=g(1.,2.,2.2) ; S+=g(2.,2.,2.8) ; S+=g(0.,3.,3.) ; S+=g(1.,3.,3.2) ; S+=g(2.,3.,3.6) ; S+=g(0.,4.,4.) ; S+=g(1.,4.,4.1) ; S+=g(3.,3.,4.2) ; S+=g(2.,4.,4.5) ; S+=g(0.,5.,5.) ; S+=g(3.,4.,5.) ; S+=g(1.,5.,5.1) ; S+=g(2.,5.,5.4) ; S+=g(4.,4.,5.7) ; S+=g(3.,5.,5.8) ; S+=g(0.,6.,6.) ; S+=g(1.,6.,6.1) ; S+=g(2.,6.,6.3) ; S+=g(4.,5.,6.4) ; half3 c=S.rgb/S.a; c=sqrt( c/(1.+.6*max(max( c.r, c.g) , c.b) ) ) ;return half4( c*half( a) ,half( a) ) ; }
Later, when chromatic aberration was added, each group’s weight went from one scalar to three channels, and the number of groups grew to 26 because of the wider red disc; there was no way this code could still fit. The final version (1176 bytes, distances kept to three decimal places, the centre sub-block read only once) was moved into the zero padding at the end of the binary’s first read-only segment, the segment length was extended accordingly, and the three instructions that create the string were repointed to the new address. The structural changes mentioned above had to be made after all. What the cost bought is bokeh with chromatic aberration: at SF radius 102 the whole pipeline takes about 1.35–1.47 ms. Its full source, together with the first two passes, is laid out and annotated in the appendix at the end.
Why we did not go on to change control flow
The remaining gap (about 0.4 ms) comes from the missing block map. There is a data-only option: change kScales to so that the second intermediate surface becomes twice the size of the 1/4 surface, store three sub-block averages and one block average interleaved in each cell, and select which one to read during the gather with a coordinate offset. Calculation shows, however, that this is a net loss. The GPU executes fragment shaders in groups of pixels, and the slowest pixel in a group determines the time of the whole group; every group contains a block-average pixel that needs 16 reads, so the pass effectively costs about 64 reads per 1/4-level pixel, compared with 4 before. The extra ~60 reads outweigh the 39 reads (161 → 122) the gather would save with an aberration of 0.1. The approach that would actually pay off is an additional, separate block-average pass, which requires modifying SF’s instruction logic; the risk is out of proportion to the benefit, so we stopped here.
Verification
Whether a blur is “right” is hard to judge by eye alone, and the checking methods used throughout the process deserve a list of their own:
- Fixed test images. Three CC0 photographs (the three in Figure 1) cover point lights, hard-edged structure and high-frequency texture respectively, and every change was compared on the same set of magnified screenshots.
- Translation search. Integer-pixel translations between the output and a reference (a Gaussian blur or the Lab disc), minimising squared error. This is how the sign error in the B-spline coordinates mentioned above (an offset of about px) was found; phase correlation fails here, because the correlation peak of blurred images is too broad.
- Offline reproduction and per-pixel readback. The stripe problem went through three misdiagnoses (nearest-neighbour sampling, layer resolution, coordinate offset) before it was finally traced to encoded-space interpolation, by reproducing the pipeline step by step in numpy and reading the gather result back from the GPU for per-pixel comparison.
- Numerical differences between variants. Every optimisation was compared pixel-wise against the previous version: the maximum difference between the half-precision exact layout and the single-precision interval layout is 1/255; between SF’s unrolled and looped versions, the maximum is 5/255 and the mean 0.35/255; block merging is algebraically equivalent to reading sub-block by sub-block in exact arithmetic but adds one 8-bit quantisation, and that rounding difference was not measured separately.
- Consistent timing. Wall-clock times and frame statistics are too noisy because of synchronisation and presentation, so all timings use GPU time queries in a separate context, take the median after warm-up, and are compared only within the same run.
Known approximations and limitations
Collecting the approximations mentioned throughout the text:
- Partially covered sub-blocks are weighted by “sum of coverages × sub-block mean”, with an error equal to the covariance of coverage and content within the sub-block; the SF version is coarser, replacing per-texel coverage with a 2-texel ramp on the sub-block centre distance.
- All intermediate results are 8-bit and shader arithmetic is half precision; in SF the highlight expansion strength is fixed at .
- The upsampling stage (the B-spline in the Lab, bilinear in SF) interpolates encoded values, with an error second order in adjacent differences; in SF’s first pass, the innermost average is likewise in encoded space.
- The pyramid and B-spline give the edge a transition band about pixels wide; the band doubles in width where the level switches, which is visible during a slow rack focus.
- Interval shaders read an extra ring of zero-weight samples until the radius settles; chromatic aberration is quantised in steps of 0.02.
- Image borders are handled by clamping, so edge pixels are stretched rather than showing genuine “off-screen” content.
- The whole scene is treated as a plane at a single depth, with no depth map and hence no occlusion between foreground and background; for the purpose of “blurring the windows behind”, this is exactly the desired behaviour.
Related work
Real-time defocus has a long research history. The work most relevant here falls into three groups.
Iterated small kernels. Kawase’s multi-pass small-kernel filter2 and its dual variant3 approximate large-radius blur with very few reads, and are the common basis of frosted glass on today’s mobile systems; they are what this article directly replaces. As discussed above, their effective kernels tend towards a smooth bell shape, with no flat top and no hard edge.
Separable approximations. A disc kernel is not separable, so direct convolution costs grow with . McIntosh et al.8 combine separable filters to simulate the bokeh of square, hexagonal and octagonal apertures efficiently; Frostbite’s hexagonal bokeh6 achieves a similar effect with three skewed one-dimensional box filters; Garcia7 decomposes the disc into a sum of complex components, each of them separable, approximating a circular aperture with one-dimensional convolutions. These methods bring the cost down to linear in , but they either produce a polygon rather than a circle, or have intermediate results with negative values and complex components that need floating-point buffers.
Synthetic depth of field in mobile photography. Wadhwa et al.9 estimate depth on a single-camera phone from person segmentation and dual-pixel autofocus data, then apply depth-dependent blur to produce shallow depth-of-field photographs. That work targets post-capture processing of a single image and relies on per-pixel depth; this article deals with the whole screen in every frame of the compositor, with no depth and no spare frame time.
What distinguishes this article from the above lies in the constraints rather than the model: 8-bit intermediate buffers rule out complex separable kernels; SurfaceFlinger’s fixed pipeline structure (three shaders, one downsample and one upsample) rules out schemes that need extra passes or extra inputs; and a cost in the same range as Dual Kawase rules out direct full-resolution convolution. Under these constraints, the choice made here is a dense gather at reduced resolution, trading pyramid prefiltering, coverage weighting and a pseudo-HDR working space for a flat-topped, hard-edged disc.
Conclusion
At 120 Hz the per-frame GPU budget is 8.33 ms. The defocus blur (SF radius 102, aberration 0.1) takes about 1.4 ms; together with 0.3–0.5 ms for SF to composite the remaining layers, this still leaves more than 6 ms for the app’s own rendering, while SystemUI typically renders in 1–3 ms while the notification shade is being pulled down.
In retrospect, there is no new mathematics in this algorithm: disc convolution, inverse tone mapping, pyramids and symmetry are all textbook material. What decided the outcome were a few engineering judgements: refusing to iterate in order to preserve the shape of the kernel; refusing sparse sampling in order to avoid aliasing; putting every single average in the right space; and, within a fixed pipeline and a 1093-byte string, finding exactly the place where these ideas would fit.
Appendix: SurfaceFlinger shader source
Below are the three shaders (SkSL) that finally went into SurfaceFlinger, with chromatic aberration, one for each pass of “The patched pipeline”. The binary holds a compact form with whitespace removed and single-letter names (278, 260 and 1176 bytes respectively); here they have only been laid out, renamed and commented, and every operation matches the original. The 26 group(…) lines in the third shader are emitted, sorted by distance, by the generator script and need no hand editing before they are written into the binary.
All three share the same pair of colour transforms. expand decodes the 8-bit encoded value with (squaring is cheaper than pow(c, 2.2)) and then applies the inverse tone map with ; compress is its inverse. Every average is taken between the two.
Pass 1, sf_quarter: full resolution → 1/4
// Full resolution → s₀ (1/4): each output texel is the HDR average of a full-resolution 4×4 box.
// Replaces the first downsample of the stock KawaseBlurDualFilterV2.
uniform shader child; // full-resolution image; SF has already mapped xy to 1/4 coordinates
const half BOOST = 0.6; // highlight boost b: a pixel near 1 is expanded by up to 1 / (1 − b) = 2.5×
// Read one point, decode it and expand it to HDR
half3 expand(float2 p) {
half3 y = child.eval(p).rgb;
y *= y; // sRGB → linear, γ = 2 approximation
return y / (1.0 - BOOST * max(max(y.r, y.g), y.b)); // inverse tone map
}
// HDR → 8-bit encoded value
half3 compress(half3 x) {
return sqrt(x / (1.0 + BOOST * max(max(x.r, x.g), x.b)));
}
half4 main(float2 xy) {
// Shift everything by half a 1/4-level texel, so the next pass's sub-blocks are centred
// exactly on 1/4-level texel centres. The Lab removes this offset in the final upsample;
// SF's compositing has no such parameter, so it has to move to the first pass.
xy -= 0.5;
// (±¼, ±¼) are full-resolution pixel corners, so hardware bilinear gives a 2×2 average
// per read; the four reads are averaged again in HDR, making a 4×4 box.
// The innermost 2×2 is still an encoded-space average: Jensen's error is confined to that scale.
half3 c = expand(xy + float2( 0.25, 0.25))
+ expand(xy + float2(-0.25, -0.25))
+ expand(xy + float2( 0.25, -0.25))
+ expand(xy + float2(-0.25, 0.25));
return half4(compress(c * 0.25), 1.0);
}
Pass 2, sf_half: the sub-block map
// s₀ → s₁ (both 1/4): the sub-block map Q. Texel p holds the HDR average of the 2×2 sub-block
// {p, p + (1,0), p + (0,1), p + (1,1)} whose top-left it is, so the gather reads a sub-block at once.
// Replaces the stock second downsample (with kScales = {4, 4, 4, 4} it no longer reduces resolution).
uniform shader child; // s₀
const half BOOST = 0.6;
half3 expand(float2 p) {
half3 y = child.eval(p).rgb;
y *= y;
return y / (1.0 - BOOST * max(max(y.r, y.g), y.b));
}
half3 compress(half3 x) {
return sqrt(x / (1.0 + BOOST * max(max(x.r, x.g), x.b)));
}
half4 main(float2 xy) {
// xy is a texel centre, so integer offsets read neighbouring texel centres: no bilinear mixing
half3 c = expand(xy)
+ expand(xy + float2(1.0, 1.0))
+ expand(xy + float2(1.0, 0.0))
+ expand(xy + float2(0.0, 1.0));
return half4(compress(c * 0.25), 1.0);
}
Pass 3, sf_gather: the disc gather
// s₁ → s₀ (1/4): the disc gather over the sub-block map, with axial chromatic aberration.
// Replaces the stock upsample pass. Sub-blocks 2(±i, ±j) and 2(±j, ±i) lie at the same distance
// from the centre (2√(i² + j²) texels) and share one weight: the disc unrolls over its 8-fold
// symmetry into 26 groups whose distances are all compile-time constants.
uniform shader child; // s₁: the sub-block map
uniform float in_blurOffset; // the stock step
uniform float in_crossFade; // the stock α
uniform float in_weightedCrossFade; // unused, but SF sets it by name, so it must stay declared
const half BOOST = 0.6;
const float R_MAX = 12.0; // largest green disc radius, 1/4-level texels: 48 px at ρ = 102
const float RADIUS_K = 0.815; // ≈ (48 / 102)·√3, see "Mapping radius and fade-in"
// Globals set by main and updated by group(), so the calls take no extra arguments
float2 gCenter; // this fragment's position in s₁
float3 gHalf; // per-channel H = (R + 1) / 2, in sub-blocks (2 texels)
half3 gColor; // per-channel Σ weight × colour
float3 gWeight; // per-channel Σ weight
half3 expand(float2 p) {
half3 y = child.eval(p).rgb;
y *= y;
return y / (1.0 - BOOST * max(max(y.r, y.g), y.b));
}
half3 compress(half3 x) {
return sqrt(x / (1.0 + BOOST * max(max(x.r, x.g), x.b)));
}
// Accumulate one group of symmetric sub-blocks. 0 ≤ i ≤ j; k = √(i² + j²), in sub-blocks,
// is computed by the generator script.
void group(float i, float j, float k) {
// Coverage: a linear ramp 2 texels wide centred on d = R, clamp((R + 1 − d) / 2, 0, 1), d = 2k
float3 w = clamp(gHalf - k, 0.0, 1.0);
// Red's disc is the widest: if red is zero, all three are, and the group is skipped.
// The condition depends only on uniforms, so every fragment in a frame takes the same path.
if (w.r <= 0.0) return;
float2 p = float2(i, j) * 2.0; // 2(i, j)
float2 q = float2(-j, i) * 2.0; // rotated 90°
half3 s = expand(gCenter + p) + expand(gCenter - p)
+ expand(gCenter + q) + expand(gCenter - q);
float n = 4.0;
// When i = 0 (on an axis) or i = j (on a diagonal), the mirror image across the diagonal
// coincides with the group itself and it has only 4 distinct sub-blocks; otherwise read the
// mirrored 4 as well.
if (i > 0.0 && i < j) {
p = p.yx; // 2(j, i)
q = float2(-i, j) * 2.0; // rotated 90°
s += expand(gCenter + p) + expand(gCenter - p)
+ expand(gCenter + q) + expand(gCenter - q);
n = 8.0;
}
gColor += s * half3(w);
gWeight += n * w;
}
half4 main(float2 xy) {
gCenter = xy;
float alpha = in_crossFade;
// Recover SF's requested radius exactly from the step formula at n = 1,
// α·√(step² + ½) = ρ / (4√3), and map it linearly to the green disc radius at 1/4
float R = min(RADIUS_K * alpha * sqrt(in_blurOffset * in_blurOffset + 0.5), R_MAX);
// Axial chromatic aberration κ = 0.1: red's disc is 1.1×, blue's 0.9×
gHalf = R * float3(1.1, 1.0, 0.9) * 0.5 + 0.5;
// The centre sub-block (k = 0) is read once, with weight clamp(H, 0, 1) = min(H, 1)
gWeight = min(gHalf, 1.0);
gColor = expand(gCenter) * half3(gWeight);
// 26 groups in order of distance, k < H_max = (12 × 1.1 + 1) / 2 = 7.1
// i j k = √(i² + j²)
group(0.0, 1.0, 1.000);
group(1.0, 1.0, 1.414);
group(0.0, 2.0, 2.000);
group(1.0, 2.0, 2.236);
group(2.0, 2.0, 2.828);
group(0.0, 3.0, 3.000);
group(1.0, 3.0, 3.162);
group(2.0, 3.0, 3.606);
group(0.0, 4.0, 4.000);
group(1.0, 4.0, 4.123);
group(3.0, 3.0, 4.243);
group(2.0, 4.0, 4.472);
group(0.0, 5.0, 5.000);
group(3.0, 4.0, 5.000);
group(1.0, 5.0, 5.099);
group(2.0, 5.0, 5.385);
group(4.0, 4.0, 5.657);
group(3.0, 5.0, 5.831);
group(0.0, 6.0, 6.000);
group(1.0, 6.0, 6.083);
group(2.0, 6.0, 6.325);
group(4.0, 5.0, 6.403);
group(3.0, 6.0, 6.708);
group(0.0, 7.0, 7.000);
group(1.0, 7.0, 7.071);
group(5.0, 5.0, 7.071);
// Normalise per channel and encode back to 8 bits
half3 c = compress(gColor / half3(gWeight));
// Premultiplied output (α·c, α). SF draws it SrcOver onto s₀ (pass 1's 4×4 box average),
// giving α·disc + (1 − α)·box: a smooth fade-in at small radii.
return half4(c * half(alpha), half(alpha));
}
References
- Potmesil, M., & Chakravarty, I. (1981). A lens and aperture camera model for synthetic image generation. Computer Graphics (Proc. SIGGRAPH ‘81), 15(3), 297–305.
- Kawase, M. (2003). Frame buffer postprocessing effects in DOUBLE-S.T.E.A.L (Wreckless). Game Developers Conference.
- Bjørge, M. (2015). Bandwidth-efficient rendering. SIGGRAPH 2015 Course: Moving Mobile Graphics.
- Reinhard, E., Stark, M., Shirley, P., & Ferwerda, J. (2002). Photographic tone reproduction for digital images. ACM Transactions on Graphics, 21(3), 267–276.
- Sigg, C., & Hadwiger, M. (2005). Fast third-order texture filtering. In M. Pharr (Ed.), GPU Gems 2 (ch. 20, pp. 313–329). Addison-Wesley.
- White, J., & Barré-Brisebois, C. (2011). More performance! Five rendering ideas from Battlefield 3 and Need for Speed: The Run. SIGGRAPH 2011 Course: Advances in Real-Time Rendering in Games.
- Garcia, K. (2017). Circular separable convolution depth of field. ACM SIGGRAPH 2017 Talks.
- McIntosh, L., Riecke, B. E., & DiPaola, S. (2012). Efficiently simulating the bokeh of polygonal apertures in a post-process depth of field shader. Computer Graphics Forum, 31(6), 1810–1822.
- Wadhwa, N., Garg, R., Jacobs, D. E., Feldman, B. E., Kanazawa, N., Carroll, R., Movshovitz-Attias, Y., Barron, J. T., Pritch, Y., & Levoy, M. (2018). Synthetic depth-of-field with a single-camera mobile phone. ACM Transactions on Graphics, 37(4), Article 64.
This research was done in collaboration with Claude.
