proposal: ebiten: add Image.ReadPixelsAsync
Operating System
- Windows
- macOS
- Linux
- FreeBSD
- OpenBSD
- Android
- iOS
- Nintendo Switch
- PlayStation 5
- Xbox
- Web Browsers
This is a cross-platform API proposal; backend support and limitations need investigation.
What feature would you like to be added?
Propose an asynchronous pixel readback API:
func (i *Image) ReadPixelsAsync(dst []byte) <-chan errorThe main use case is recording gameplay: request a capture during drawing, continue rendering, and encode the captured pixels after they become available.
Proposed semantics
- The call enqueues the capture in drawing order before returning, without waiting for GPU completion. The captured pixels include preceding drawing operations and exclude subsequent changes to the image.
- Pixel format, buffer length, and sub-image behavior follow ReadPixels. Invalid arguments panic synchronously.
- The returned channel is buffered with capacity one and receives exactly one result: nil on success or an operational error. It remains open, following the single-result convention of singleflight.Group.DoChan. Callers receive once rather than ranging over it.
- The caller must not read, modify, or reuse dst until receiving the result. After receiving either success or failure, Ebitengine will no longer access dst. On failure, the contents are unspecified.
- Ebitengine retains resources needed for pending captures even if the source image is subsequently modified or disposed. Ignoring the result channel must not prevent completion or resource cleanup.
- Pending requests must eventually receive a result, including when device failure or game shutdown prevents successful completion.
No context parameter is proposed initially. A recorder can stop submitting captures and drain its bounded set of pending results. A caller may stop waiting using select and a context, but must still receive the readback result before reusing dst. Cancellation could be considered separately if abandoning pending work becomes a concrete requirement.
Direction of implementation
Split the internal readback operation into submission and completion:
- Insert a texture-to-staging-buffer copy at the requested position in the graphics command stream. Preserve ordering through buffered writes, drawing batches, atlas operations, and resource disposal.
- Submit the GPU work without synchronously waiting for the copy to finish. Avoid routing asynchronous requests through the current readback path that immediately flushes and requires synchronization.
- Track GPU completion with fences or backend-specific completion mechanisms, allowing subsequent rendering commands to be submitted while the transfer is pending.
- Once ready, copy the pixels from staging memory into dst, publish the result, and recycle the staging resources. Graphics operations and completion checks must respect each backend's thread/context requirements; waiting must not hold locks needed for rendering or completion.
Possible backend mechanisms include OpenGL pixel pack buffers with fences, Metal texture-to-buffer blits with command-buffer completion, and Direct3D staging/readback resources with completion tracking. Web and console capabilities need individual investigation. Unsupported backends should have an explicit policy rather than silently introducing a synchronous GPU wait.
This avoids an immediate CPU wait for GPU completion; it does not promise zero GPU cost or stalls. Copy dependencies, memory bandwidth, and resource transitions still apply.
For continuous recording, reuse staging resources and keep the number of captures in flight bounded. The recorder can maintain a small pool of destination buffers and skip captures when all are occupied, or wait when offline recording requires every frame. Capture timestamps should describe the requested frame rather than completion time.
Faster-than-real-time recording with a VM guest
Another use case is offline video export of a game running as an exp/vmhost guest. The host controls guest ticks and frame requests, so it can replay recorded or scripted inputs without real-time pacing. The guest forwards graphics commands and the host performs the actual rendering; recording can therefore live entirely in the host without adding capture code to the game.
For a 60-TPS game exported at 60 FPS, the host would repeat:
- Inject the input for the next tick and call
AdvanceTicks(1). - Call
AdvanceFrame(),WaitFrame(), andCompositeFrame()to obtain that frame in the host-owned image. - Call
ReadPixelsAsyncon that image and associate the request with the output frame index. - Proceed with the next guest tick and frame while earlier readbacks complete. Deliver completed buffers to the encoder in frame order.
Output timestamps come from simulated time (for example, frame index divided by 60), not wall-clock time or readback completion time. Other tick/frame rates require an appropriate mapping between simulation ticks and output frames.
The current VM frame requests coalesce and allow only one guest frame in flight. Each output frame must be composited and its capture enqueued before requesting the next; advancing many ticks and requesting a single frame only captures the final state. Multiple host-side readbacks could still remain pending after those ordered submissions.
A bounded pool of capture buffers limits memory use. For offline export, a full pool should apply backpressure instead of dropping frames. Submission and completion processing must continue to make progress while draining the pool, including when multiple guest frames are processed within one host Update; a recorder must not block the host thread waiting for completion that requires that same thread to run.
Synchronous ReadPixels can already support this workflow and may achieve faster-than-real-time export for sufficiently light workloads. The proposed API would improve throughput by allowing rendering, readback, and encoding to overlap. It cannot guarantee a particular export speed: simulation, GPU work, transfers, and encoding remain costs.
Audio recording would require separate host-side work: pull the guest's individual PCM streams according to simulated time, apply volume, mix them, and synchronize them with video. Audio consumption must be interleaved with simulation, especially when game logic observes playback position. Tick control does not virtualize time.Now(), sleeps, networking, or other external timing, so faithful accelerated replay also depends on the game's behavior. VM recording is currently a desktop use case; it does not change the cross-platform scope of ReadPixelsAsync.
Building a recorder, encoder integration, audio mixer, or general virtual clock is outside this API proposal. This use case motivates ordered asynchronous readback on the host-owned image.
Related: #2945. Removing At is not a prerequisite, but its proposed error-returning ReadPixels is consistent with reporting readback failures directly.
Why is this needed?
ReadPixels currently requires synchronization to make the requested pixels available before returning. Calling it in a goroutine does not remove that synchronization, and goroutine scheduling alone does not fix the capture's position relative to subsequent drawing.
The proposed API separates ordered submission from completion, allowing rendering, readback, and video encoding to overlap.
Explicit asynchronous APIs have Go precedents: net/rpc.Client.Go exposes completion through a channel, and golang.org/x/sync/singleflight.Group.DoChan returns a channel carrying a future result. Here, the reason for exposing asynchronous submission is deterministic capture ordering.
Authored and filed by OpenAI Codex on behalf of @hajimehoshi.
Source: hajimehoshi/ebiten