Skip to content

Video Driver Architecture

opencode-agent[bot] edited this page Nov 1, 2026 · 4 revisions

Video Driver Architecture

JNode's video driver subsystem provides a framebuffer abstraction layer that enables hardware-accelerated and software-rendered 2D graphics through the Surface and FrameBufferAPI interfaces.

Overview

The video driver architecture sits at the lowest level of JNode's GUI stack, providing direct access to the graphics hardware through a layered design. At the top level, applications interact with Java AWT graphics that ultimately delegate to Surface objects. Each Surface wraps either a physical video device (framebuffer) or an in-memory image buffer.

Location: gui/src/driver/org/jnode/driver/video/

Key Components

Class/File Package Purpose
Surface org.jnode.driver.video Interface defining a paintable 2D surface
AbstractSurface org.jnode.driver.video.util Generic Surface implementation with shape rendering
FrameBufferAPI org.jnode.driver.video Interface for framebuffer device discovery and configuration
AbstractFrameBufferDriver org.jnode.driver.video Base driver class implementing FrameBufferAPI
VESADriver / VESACore org.jnode.driver.video.vesa VBE-compliant framebuffer driver
NVidiaAcceleration org.jnode.driver.video.nvidia Hardware acceleration for NVidia GPUs
RadeonAcceleration org.jnode.driver.video.ati.radeon Hardware acceleration for ATI/AMD GPUs
BitmapGraphics org.jnode.awt.util Low-level pixel manipulation on video RAM

The Surface Interface

Surface (gui/src/driver/org/jnode/driver/video/Surface.java) is the central abstraction for a paintable region. It defines methods for:

  • Shape operations: draw(Shape, ...) and fill(Shape, ...) with AffineTransform, clipping, and color
  • Region copying: copyArea(x, y, w, h, dx, dy) for blitting
  • Image rendering: drawCompatibleRaster(...) and drawAlphaRaster(...) for bitmap blitting
  • Pixel access: getRGBPixel / setRGBPixel / getRGBPixels for direct pixel manipulation
  • Screen update: update(x, y, w, h) flushes changes to the display

Rendering modes are defined as constants:

  • PAINT_MODE (0x00): Opaque overwrite
  • XOR_MODE (0x01): XOR blend with existing pixels

AbstractSurface

AbstractSurface (org.jnode.driver.video.util/AbstractSurface.java) provides the generic rendering engine:

  • Bresenham line drawing in drawLine(x1, y1, x2, y2, color, mode)
  • PathIterator traversal for arbitrary shape rendering
  • Bezier and quadratic curves via the Curves utility
  • Rectangle optimization for axis-aligned rectangles (via fillRect)
  • drawPixel and convertColor are abstract — subclasses implement device-specific pixel writing and color conversion

The fill algorithm decomposes arbitrary shapes by iterating pixel coordinates and using shape.contains(x, y), which is efficient for convex shapes but can be slow for complex paths.

// Simplified fill logic
Rectangle bounds = shape.getBounds();
for (int row = 0; row < bounds.height; row++) {
    for (int col = 0; col < bounds.width; col++) {
        int x = bounds.x + col;
        int y = bounds.y + row;
        if (shape.contains(x, y) && (clip == null || clip.contains(x, y))) {
            drawPixel(x, y, color, mode);
        }
    }
}

FrameBufferAPI and Driver Model

FrameBufferAPI defines how framebuffer devices expose their capabilities:

public interface FrameBufferAPI extends DeviceAPI {
    FrameBufferConfiguration[] getConfigurations();
    FrameBufferConfiguration getCurrentConfiguration();
    Surface open(FrameBufferConfiguration config) throws ...;
    boolean isOpen();
    void requestOwnership(FrameBufferAPIOwner owner);
    void releaseOwnership(FrameBufferAPIOwner owner);
    Surface getCurrentSurface() throws NotOpenException;
}

AbstractFrameBufferDriver extends Driver and implements FrameBufferAPI:

  • Registers itself as FrameBufferAPI in startDevice()
  • Renames the device to fb-<deviceId> via DeviceManager
  • Manages a stack of FrameBufferAPIOwner instances for exclusive access
  • requestOwnership pushes the new owner and notifies the previous owner via ownershipLost()
  • releaseOwnership pops the stack and notifies the new top via ownershipGained()

VESA Driver

VESADriver extends AbstractFrameBufferDriver:

  • Reads VBE info blocks (VbeInfoBlock, ModeInfoBlock) from BIOS memory mapped at boot
  • Creates a VESACore that extends AbstractSurface and implements HardwareCursorAPI
  • VESACore claims video RAM via ResourceManager.claimMemoryResource()
  • Supports 8/16/24/32 bpp modes with different BitmapGraphics implementations per depth
  • The actual pixel operations delegate to BitmapGraphics which performs byte/short/int writes to video RAM
public final void drawPixel(int x, int y, int color, int mode) {
    bitmapGraphics.drawPixels(x, y, 1, color, mode);
}

Hardware Acceleration

Hardware acceleration is plugged in via device-specific *Acceleration classes:

NVidiaAcceleration

NVidiaAcceleration (gui/src/driver/org/jnode/driver/video/nvidia/NVidiaAcceleration.java) drives NVidia GPU acceleration:

  • Uses MMIO (Memory-Mapped I/O) via NVidiaVgaIO to access GPU registers
  • Programs the PFIFO command queue (256 32-bit words) for 2D operations
  • Key operations:
    • setupRectangle(color) / fillRectangle(x, y, w, h) — rectangle fills
    • setupInvertRectangle() / invertRectangle(x, y, w, h) — XOR inversion
    • accInit(...) — initializes the graphics engine, context tables, tile/pitch registers
  • Supports NV04, NV10, NV20, NV30 architectures

RadeonAcceleration

RadeonAcceleration (gui/src/driver/org/jnode/driver/video/ati/radeon/RadeonAcceleration.java) provides ATI/AMD GPU acceleration:

  • Uses register MMIO via RadeonVgaIO
  • Programs the CP (Command Processor) FIFO
  • Key operations:
    • screenToScreenCopy(srcX, srcY, w, h, dstX, dstY) — fast blit using DP_MIX with ROP3_SRCCOPY

Pattern: Acceleration classes are separate from the Surface

Unlike VESA (where VESACore IS the Surface), hardware-accelerated drivers like NVidia and Radeon separate acceleration logic:

  • NVidiaCore / RadeonCore extends AbstractSurface for rendering
  • NVidiaAcceleration / RadeonAcceleration provides the low-level GPU programming
  • The acceleration object is typically held as a field in the Core class and called from within overridden methods

Hardware Cursor

HardwareCursorAPI extends the framebuffer with cursor support:

public interface HardwareCursorAPI extends DeviceAPI {
    void setCursorPosition(int x, int y);
    void setCursorVisible(boolean visible);
    void setCursorImage(HardwareCursor cursor);
}
  • SoftwareCursor wraps BitmapGraphics with software cursor rendering (sprite over surface)
  • Hardware cursor support is provided by NVidiaHardwareCursor, RadeonHardwareCursor which program the GPU's cursor sprite registers

JNodeCursors builds the ARROW cursor for 16x16, 20x20 and 32x32 sizes. 8242fe59d moved the hotspot from (0,0) to the visual arrow tip: (2,4) at 16x16, (3,7) at 20x20 and (6,14) at 32x32. The hotspot is the pixel a click maps to; leaving it at the top-left corner makes the pointer appear offset from the actual click point by roughly the sprite's border.

SoftwareCursor — Save/Restore Decorator

VESACore extends AbstractSurface implements HardwareCursorAPI (VESACore.java:57) never programs a VBE hardware cursor. It wraps the real per-bpp BitmapGraphics in a SoftwareCursor (VESACore.java:79, constructed at :162, rebound per bpp by setMode() at :227/233/239/245, and forwarded to at :589/606/570).

SoftwareCursor extends BitmapGraphics (SoftwareCursor.java:34) and wraps another BitmapGraphics, so it is a decorator: every mutator hides the cursor, delegates, and re-shows it in a finally. HardwareCursorImage.T = 0x00000000 (HardwareCursorImage.java:36) is the transparency sentinel.

The framebuffer is a claimed MemoryResource mapped straight onto VRAM and updateScreen(...) is a stub (VESACore.java:271-273), so every write is immediately visible — no page flip, no back buffer, no vblank sync. Any stray write is instantly on-screen corruption, which is why the cursor save/restore has to be exact.

The Corruption Bugs (fixed 2026-09-24)

Defect Mechanism
Stale right-edge pixels (primary) When the cursor hangs off the right edge, only the prefix cursorX..maxX of each width-wide row was saved; the remaining slots retained values from a previous position or image size, and hideCursor() restored that garbage permanently.
No "is drawn" state showCursor()/hideCursor() were not idempotent. hideCursor() restored a backup even when the cursor had never been drawn (e.g. right after setCursorImage).
Cursor drawn while hidden setBitmapGraphics, setCursorImage and setCursorPosition all called showCursor() unconditionally, so moving the mouse with the cursor hidden blitted the sprite and never restored it.
Wrong-size save buffer if (screenBackup == null) never reallocated for a new HardwareCursorImage size → ArrayIndexOutOfBoundsException swallowed by setCursorImage's catch (Throwable).
No negative-coordinate handling Only maxX/maxY were clamped; a cursor at x<0 drove drawPixels with negative coordinates.
One drawPixels per pixel 400 calls per show and per hide for a 20×20 arrow, 800 per mouse move.
Reads returned cursor pixels doGetPixel/doGetPixels delegated straight through (the literal comments said // TODO don't take cursor pixels).
copyArea checked only the destination intersectsCursor was passed source coordinates, so the cursor bitmap itself was copied as source data and smeared.
fillRect not overridden at all The inherited BitmapGraphics.fillRect (BitmapGraphics.java:144-149, commented "this method is not used because it makes JNode unstable") looped drawPixels on the wrapped graphics with no hide/show, baking the cursor into the framebuffer.
Hotspot drift setCursorPosition compared cursorArea.getX()/getY() (sprite top-left) against incoming hotspot coordinates.
No mutual exclusion MouseHandler.pointerStateChanged (:315) and setCursor (:293) call setCursorPosition from the pointer-driver thread while the AWT paint thread mutates the same BitmapGraphics; interleaving inside a hide→draw→show sequence restored over freshly-painted pixels.

The Fix

  • New private boolean cursorDrawn (:39). showCursor() (:306-337) opens with if (!cursorVisible || (cursorImage == null) || cursorDrawn) return; and sets the flag at :336; hideCursor() (:339-344) only restores when the flag is set. Both are now idempotent.
  • Correct row-wise save (:320-333): per image row, clamp to the screen, then one bulk read with a reused private Rectangle readArea field (:42):
    readArea.setBounds(firstX, y, lastX - firstX, 1);
    final int[] row = graphics.doGetPixels(readArea);
    System.arraycopy(row, 0, screenBackup, imageY * width + firstX - cursorX, row.length);
    The imageY * width + firstX - cursorX offset now covers every slot of the clipped row, which kills the stale-edge bug.
  • Correct buffer sizing (:313-315): reallocate whenever screenBackup.length != width * height.
  • Visibility gate: if (cursorVisible) { showCursor(); } at :64-66, :241-243, :270-272.
  • Hotspot-aware change detection (:255-259) using cursorArea.getX() + cursorImage.getHotSpotX().
  • New private void drawRun(int x, int y, int count, int color) (:346-350) — the new blit primitive, guarded by if (count > 0).
  • Rewritten putPixels(int[] pixels, int[] background) (:352-389) — clamps each row/column, flushes on out-of-screen columns, and run-length batches contiguous same-colour pixels into a single drawPixels call. This is the change that turned 800 calls per mouse move into a handful.
  • Source and destination intersection in copyArea (:71-85), with try { ... } finally { ... } around the delegate.
  • Reads now hide first — doGetPixel (:88-100) and doGetPixels(Rectangle) (:103-115).
  • New fillRect override (:196-208) — the previously missing member.
  • Every method is synchronized (:48, 71, 88, 103, 118, 134, 150, 166, 181, 196, 210, 214, 218, 250, 279), and all bodies use try { ... } finally { showCursor(); } so an exception mid-blit still restores the cursor.

VESACore Synchronization and fillRect

All drawing and pixel entry points were made synchronized: copyArea:293, drawCompatibleRaster:311, fillRectangle:335, fillRect:350, drawPixel:395, drawLine:409, drawHorizontalLine:423, setCursorImage:589, setCursorVisible:606, drawAlphaRaster:601, getRGBPixel:609, getRGBPixels:614 (draw:282 and fill:325 already were). Pairing the surface lock with the SoftwareCursor lock makes blit + cursor save/restore atomic.

fillRect (:350-370) was rewritten with full four-edge clipping and delegation:

public final synchronized void fillRect(int x, int y, int width, int height, int color, int mode) {
    if (width <= 0 || height <= 0) return;
    if (x < 0) { width += x; x = 0; }
    if (y < 0) { height += y; y = 0; }
    if (x >= this.width || y >= this.height) return;
    width  = Math.min(width,  this.width  - x);
    height = Math.min(height, this.height - y);
    if (width > 0 && height > 0) { bitmapGraphics.fillRect(x, y, width, height, color, mode); }
}

Previously only the left/top edges were clipped (width = Math.max(0, x + width)) and a bottom-up per-line drawPixels loop ran with the comment // TODO optimize it like in VMWareCore ?. The far/right and far/bottom edges were never clamped, so a rect overflowing the screen wrote into neighbouring scanlines and, on the last row, past the end of the claimed MemoryResource. Right/bottom clamping plus delegation to AbstractBitmapGraphics.fillRect (a per-row doDrawPixels → single mem.setShort/setInt run) removes the smear and resolves the TODO.

Bitmap Rendering Paths

gui/src/awt/org/jnode/awt/util/AbstractBitmapGraphics.java is the base for every per-bpp graphics class (see JNode-Graphics2D).

drawPixels Count Clamping

// :275-289 (post-fix)
public final void drawPixels(int x, int y, int count, int color, int mode) {
    if (count <= 0) { return; }
    if (x < 0) { count += x; x = 0; }
    if ((x >= 0) && (x < width) && (y >= 0) && (y < height)) {
        count = Math.min(count, width - x);
        if (count > 0) { doDrawPixels(x, y, count, color, mode); }
    }
}

This is the core framebuffer-corruption fix on the bitmap side. Pre-fix, count was passed through unclamped and the only safety net was catch (IndexOutOfBoundsException) { log.error(...) }, which is now removed. doDrawPixels in each bpp class ends in mem.setShort(ofs, (short) color, count) / mem.setInt(...) / xorShort(...), and MemoryResourceImpl.setShort(int,short,int) (MemoryResourceImpl.java:929-932) only bounds-checks via testMemPtr(memPtr, count * 2) (:766-774). An unclamped count therefore wrote silently into the next scanline — pure visual corruption with no exception — and only raised at the very end of VRAM.

fillRect Became a Real Clipper

Pre-fix it drew only when the rect was fully inside the surface (x + width < this.width && y + height < this.height); otherwise it fell through to a commented-out super.fillRect(...) and drew nothing, so any partially-offscreen rect (a window dragged past the screen edge) silently vanished. Post-fix (:291-315) it clamps all four edges exactly like drawPixels, then emits one doDrawPixels run per row.

doFillRect Bulk Fast Path

fillRect() clamps the rectangle at the AbstractBitmapGraphics level and then calls a new overridable doFillRect(x, y, width, height, color, mode). The base implementation is the old row loop:

protected void doFillRect(...) {
    for (int i = 0; i < height; i++) {
        doDrawPixels(x, y + i, width, color, mode);
    }
}

All four bitmap depths override it with a contiguous-write path when the destination rows have no padding:

Depth Condition Bulk operation
8 bpp bytesPerLine == width setByte / xorByte for width * height
16 bpp bytesPerLine == (width << 1) setShort / xorShort for width * height
24 bpp bytesPerLine == width * 3 setInt24 / xorInt24 for width * height
32 bpp bytesPerLine == (width << 2) setInt / xorInt for width * height

If the rows are padded, each override falls back to one bulk write per row (rowOfs = ofs + i * bytesPerLine). Both PAINT_MODE and XOR mode are supported. The fast path is only valid after fillRect() has clamped width/height; an unclamped contiguous write would spill into the next scanline exactly like an unclamped drawPixels run.

BitmapGraphics16bpp Hot Path Cleanup

gui/src/awt/org/jnode/awt/util/BitmapGraphics16bpp.java dropped its org.jnode.vm.Unsafe import and removed Unsafe.debug(...) calls from the constructor (:37-40), doDrawImage (:47), doGetPixel (:89), doGetPixels (:93), doDrawLine (:117) and doDrawPixels (:127), plus the log.error("Wrong image colors…") in doDrawImage (:70) and the log.error("Not implemented") in the doDrawImage(…, bgColor) overload (:83-87). doDrawAlphaRaster keeps its log.error("Not implemented") (:79). Remaining hot primitives: doDrawPixels:127-136 → mem.setShort/mem.xorShort; doDrawLine:117-125; doGetPixels:93-115; getBytesForWidth:139-141 = width << 1; getOffset:43-45 = offset + y * bytesPerLine + (x << 1).

Gotchas

  1. VESA driver requires GRUB to set the video mode — if GRUB hasn't switched to a VBE mode, VESADriver.startDevice() throws "grub haven't switched to graphic mode".

  2. AbstractSurface pixel iteration is slow for complex shapes — the fill(Shape, ...) method checks every pixel in the bounding box. Complex shapes with many interior points can be expensive.

  3. Ownership stack is LIFO — requestOwnership pushes on a stack; multiple owners can chain, with the new owner displacing the old one.

  4. BitmapGraphics depth switches — VESACore creates different BitmapGraphics subclasses per bit depth (8/16/24/32). The convertColor method must handle each depth's pixel format.

  5. NVidia acceleration needs architecture detection — NVidiaAcceleration checks architecture >= NV10A or >= NV20A to use different register sets, requiring careful handling of legacy NV04 vs modern GPUs.

  6. FrameBufferConfiguration equality — VESADriver.open() compares configs by reference (config.equals(configs[i])); a new VESAConfiguration instance won't match the stored one.

  7. There is no page flip. VESACore writes directly into a claimed MemoryResource and updateScreen() is a stub, so every write is instantly visible. Cursor save/restore and edge clipping are the only defence against on-screen corruption — hence the synchronized surface and the cursorDrawn flag.

  8. Clipping a count is not optional. MemoryResourceImpl only bounds-checks the end of a bulk write, so a drawPixels run that overflows a scanline corrupts the next row with no exception. Clamp in AbstractBitmapGraphics.drawPixels / fillRect, not in each doDrawPixels.

  9. The doFillRect fast path assumes a clamped rectangle. It is called only from fillRect() after edge clamping. Calling it with an unclamped width/height turns the contiguous write into a multi-row overwrite.

  10. Contiguity is per-depth, not a byte count. Compare bytesPerLine with getBytesForWidth(width)'s exact formula (width, width << 1, width * 3, width << 2); a stale or rounded bytesPerLine must take the row loop.

  11. SoftwareCursor is a BitmapGraphics decorator, not a separate surface. Anything that must not be captured by the cursor backup (copyArea source, reads, fillRect) has to hide it first; forgetting that is the classic bug.

  12. The mouse thread and the AWT paint thread share the graphics. MouseHandler calls setCursorPosition from the pointer-driver thread, so any non-atomic hide→draw→show sequence needs synchronized on both VESACore and SoftwareCursor.

  13. jnode-cli.jar shadows ant.jar by plugin-list order, not by descriptor. See Shell-Commands — the same ordering caveat applies to any source-level class override.

Related Pages

  • GUI-AWT — The overall GUI subsystem and AWT implementation
  • JNode-Graphics2D — Graphics2D implementations bridging AWT to Surface, paint clipping
  • Driver-Framework — How video drivers are registered and bound to devices
  • Device-Manager — Device discovery and API registration
  • Resource-Management — How video RAM is allocated via ResourceManager
  • DesktopFrame — The desktop window manager and taskbar that drive surface repaints

Clone this wiki locally