coreif

package module
v0.8.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 22, 2026 License: GPL-3.0 Imports: 0 Imported by: 12

README

eblitui-coreif

Shared core interfaces for the eblitui emulator UI framework. This module defines the contract between emulator cores and UI implementations, allowing each to be developed independently.

Emulator cores implement these interfaces to describe their capabilities. UI implementations consume them to drive rendering, audio, input, save management, and settings without knowing the details of any specific system.

Package

package coreif
import "github.com/user-none/eblitui/coreif"

Interfaces

CoreFactory

Entry point for the UI. Provides system metadata and creates emulator instances.

  • SystemInfo() SystemInfo - Returns system metadata used by the UI to configure screens, input mapping, settings menus, and data paths.
  • CreateEmulator() Emulator - Creates a new emulator instance. Content is provided afterwards via Emulator.SetRom (cartridge) or Emulator.SetDisc (disc). Video standard detection is handled internally by the core.
Emulator (required)

The core interface every emulator adapter must implement. Covers the per-frame emulation loop: run a frame, read video and audio output, set input, and manage region and timing.

Method Description
RunFrame() Execute one frame of emulation
GetFramebuffer() []byte Current frame as RGBA pixel data
GetFramebufferStride() int Bytes per row in the framebuffer
GetActiveHeight() int Current active display height in pixels
GetAudioSamples() []int16 Stereo 16-bit PCM audio samples for the frame
SetInput(player int, buttons uint32) Set controller state as a button bitmask
GetTiming() Timing FPS and scanline count for the current region
SetOption(key string, value string) Apply a core option change by key
SetRom(data []byte) Provide cartridge ROM data (disc cores ignore)
SetDisc(disc DiscReader) Provide a streaming disc reader (cartridge cores ignore)
SetBIOS(key string, data []byte) error Provide BIOS data; returns an error if invalid for the key
AspectProvider (optional)

Lets a core supply its pixel aspect ratio per frame when it depends on the video mode (e.g. consoles that switch horizontal resolution). When implemented, the UI uses this instead of the static SystemInfo.PixelAspectRatio. Must be cheap (cached; recomputed only on a mode change).

  • PixelAspectRatio() float64 - The current pixel aspect ratio.
SaveStater (optional)

Enables save states, rewind, and auto-save. Implement on the Emulator struct to opt in.

  • Serialize() ([]byte, error) - Capture the complete emulator state.
  • Deserialize(data []byte) error - Restore from previously serialized data.
  • SerializeSize() int - Size of a serialized state in bytes.
BatterySaver (optional)

Enables SRAM persistence for battery-backed saves.

  • HasSRAM() bool - Whether the loaded ROM uses battery-backed save.
  • GetSRAM() []byte - Copy of the current SRAM contents.
  • SetSRAM(data []byte) - Load SRAM contents into the emulator.
Memory (optional)

Canonical native bus address based access to the console's emulated RAM. The region table is the access boundary: only the listed canonical ranges are reachable, and accesses outside them transfer nothing. Bus decode detail (mirrors, CPU partitions) is the core's alone and never surfaces here. Calls happen between RunFrame invocations.

  • ReadMemory(addr uint32, buf []byte) uint32 - Read from a native bus address into buf. Returns the number of bytes actually read.
  • WriteMemory(addr uint32, data []byte) uint32 - Write data to a native bus address. Returns the number of bytes actually written.
  • Regions() []BusRegion - The accessible bus regions in canonical addresses. Static per machine.
  • ReadMemoryFlat(off uint32, buf []byte) uint32 - Read from the console's flat memory convention (the RetroAchievements layout). Reads are contiguous across region boundaries within the flat space. The layout is the core's alone; consumers needing the flat view (RetroAchievements, cht files) read through this and hold no layout knowledge.
  • WriteMemoryFlat(off uint32, data []byte) uint32 - Write data to the console's flat memory convention, matching ReadMemoryFlat's layout and boundary behavior.

BusRegion carries the region's name, canonical native start, and size.

DiscReader

A streaming reader over a CD/disc image, passed to Emulator.SetDisc for disc-based cores. Every signature uses only stdlib types, so a concrete reader satisfies it structurally without importing this package.

  • ReadSector(lba int) ([]byte, error) - Raw 2352-byte sector at the LBA.
  • NumTracks() int - Number of tracks on the disc.
  • Track(i int) (number int, typ string, frames int, pregap int, startLBA int, control uint8)
    • TOC fields for track index i in [0, NumTracks).
  • Close() error - Release the underlying resources.
DiscIdentifier (optional)

An optional interface a CoreFactory may implement so the UI can derive a disc's identifying information without instantiating an emulator. Used to group multi-disc games and resolve metadata for disc-based systems.

  • DiscInfo(disc DiscReader) (info DiscInfo, ok bool) - The disc's derived information and true when it can be read.

DiscInfo carries only disc-derived facts; it has no knowledge of any external catalog serial conventions.

Field Type Description
ProductNumber string The disc's product number; identical across a game's discs, so also used as the library/grouping key.
DiscNumber int 1-based position of this disc within the game.
DiscTotal int Total number of discs the game spans.
Title string On-disc game title, used as a display-name fallback.

Types

Timing

Frame rate and scanline configuration returned by Emulator.GetTiming().

Field Type Description
FPS int Frames per second
Scanlines int Scanlines per frame

CPU clocks are core-internal and not exposed through this type.

Button

Describes a system-specific button for input mapping.

Field Type Description
Name string Display name (e.g. "A", "Start")
ID int Bit position in the uint32 bitmask

D-pad directions always occupy bits 0-3 via the constants ButtonUp, ButtonDown, ButtonLeft, and ButtonRight. System-specific buttons start at bit 4.

CoreOption

Describes a configurable core setting for use in settings menus.

Field Type Description
Key string Unique identifier passed to SetOption
Label string UI display name
Description string Help text
Type CoreOptionType CoreOptionBool, CoreOptionSelect, or CoreOptionRange
Default string Default value
Values []string Choices (Select type only)
Min int Minimum (Range type only)
Max int Maximum (Range type only)
Step int Step size (Range type only)
Category CoreOptionCategory Settings section: CoreOptionCategoryAudio, CoreOptionCategoryVideo, CoreOptionCategoryInput, CoreOptionCategoryCore
PerGame bool Whether the option can be overridden per game
SystemInfo

System metadata returned by CoreFactory.SystemInfo(). The UI uses this to configure display, input, audio, settings, data paths, and RetroAchievements integration.

Field Type Description
Name string Emulator name (e.g. "emmd")
ConsoleName string Full console name (e.g. "Sega Genesis")
Extensions []string Supported ROM file extensions
ScreenWidth int Native screen width in pixels
MaxScreenHeight int Maximum screen height in pixels
AspectRatio float64 Display aspect ratio
SampleRate int Audio sample rate in Hz
Buttons []Button System-specific buttons
Players int Number of supported players
CoreOptions []CoreOption Configurable core settings
RDBName string RetroAchievements database name
ThumbnailRepo string Thumbnail repository name
RumbleRepoDir string Console directory in the rumble repository
DataDirName string Data directory name for saves and config
ConsoleID int Console identifier for RetroAchievements
CoreName string Core implementation name
CoreVersion string Core version string
Disc bool True if content is a disc image (provided via SetDisc)

Implementing a Core

A core implementation consists of two parts:

  1. A factory that implements CoreFactory to provide system metadata and create emulator instances.
  2. An emulator struct that implements Emulator and whichever optional interfaces the core supports.

Optional interfaces are detected at runtime via type assertion, so cores only need to implement what they support.

Documentation

Index

Constants

View Source
const (
	ButtonUp    = 0
	ButtonDown  = 1
	ButtonLeft  = 2
	ButtonRight = 3
)

Standard d-pad button bit positions (always bits 0-3).

Variables

This section is empty.

Functions

func DisplayAspectRatio

func DisplayAspectRatio(width, height int, par float64) float64

DisplayAspectRatio computes the PAR-corrected display aspect ratio from frame dimensions and the system's pixel aspect ratio.

Types

type AspectProvider added in v0.6.0

type AspectProvider interface {
	// PixelAspectRatio returns the current pixel aspect ratio.
	PixelAspectRatio() float64
}

AspectProvider is an optional interface a core may implement when its pixel aspect ratio depends on the video mode (e.g. consoles that switch horizontal resolution). When implemented, the UI uses this per-frame value instead of the static SystemInfo.PixelAspectRatio. Implementations must be cheap to call: the value should be cached and recomputed only on a mode change, not derived per call.

type BIOSOption

type BIOSOption struct {
	Key      string        // Unique key, e.g. "main_bios"
	Label    string        // Display label, e.g. "System BIOS"
	Required bool          // true = core cannot run without it
	Variants []BIOSVariant // Known BIOS dumps
}

BIOSOption describes a BIOS slot that a core supports.

func (BIOSOption) HasKnownHashes

func (o BIOSOption) HasKnownHashes() bool

HasKnownHashes returns true if any variant has a non-empty SHA256. When true, files must match a known hash to be accepted.

type BIOSVariant

type BIOSVariant struct {
	Label    string // Display name, e.g. "US v1.0"
	SHA256   string // Expected SHA256 hex
	Filename string // Default filename for system directory lookup
}

BIOSVariant describes a known BIOS dump.

type BatterySaver

type BatterySaver interface {
	// HasSRAM reports whether the loaded ROM uses battery-backed save.
	HasSRAM() bool

	// GetSRAM returns a copy of the current SRAM contents.
	GetSRAM() []byte

	// SetSRAM loads SRAM contents into the emulator.
	SetSRAM(data []byte)
}

BatterySaver enables SRAM persistence for battery-backed saves.

type BusRegion added in v0.8.0

type BusRegion struct {
	Name  string
	Start uint32 // native bus address of the region's first byte
	Size  uint32 // region size in bytes
}

BusRegion describes one region of the console's native address bus in canonical addresses.

type Button

type Button struct {
	Name       string
	ID         int    // Bit position in the uint32 bitmask (4+)
	DefaultKey string // Default keyboard key for desktop UI (e.g., "J", "Enter")
	DefaultPad string // Default gamepad button for desktop UI (e.g., "A", "Start")
}

Button describes a system-specific button with its display name and bit position in the input bitmask.

type CoreFactory

type CoreFactory interface {
	// SystemInfo returns system metadata for UI configuration.
	SystemInfo() SystemInfo

	// CreateEmulator creates a new emulator instance. Content is provided
	// afterwards via Emulator.SetRom (cartridge) or Emulator.SetDisc (disc).
	CreateEmulator() Emulator
}

CoreFactory creates emulator instances and provides system metadata.

type CoreOption

type CoreOption struct {
	Key         string
	Label       string
	Description string
	Type        CoreOptionType
	Default     string
	Values      []string           // Options for Select type
	Min         int                // Minimum for Range type
	Max         int                // Maximum for Range type
	Step        int                // Step size for Range type
	Category    CoreOptionCategory // Settings section routing
	PerGame     bool               // Whether this can be overridden per game
}

CoreOption describes a configurable core setting.

type CoreOptionCategory

type CoreOptionCategory int

CoreOptionCategory identifies the settings section for a core option.

const (
	CoreOptionCategoryAudio CoreOptionCategory = iota
	CoreOptionCategoryVideo
	CoreOptionCategoryInput
	CoreOptionCategoryCore
)

type CoreOptionType

type CoreOptionType int

CoreOptionType identifies the kind of core option.

const (
	CoreOptionBool CoreOptionType = iota
	CoreOptionSelect
	CoreOptionRange
)

type DiscIdentifier added in v0.6.0

type DiscIdentifier interface {
	// DiscInfo returns the disc's derived information and true when it
	// can be read.
	DiscInfo(disc DiscReader) (info DiscInfo, ok bool)
}

DiscIdentifier is an optional interface a CoreFactory may implement so the UI can derive a disc's identifying information without instantiating an emulator. Used to group discs and resolve metadata for disc-based systems.

type DiscInfo added in v0.6.0

type DiscInfo struct {
	// ProductNumber is the disc's product number. It is the same for
	// every disc of a multi-disc game, so the UI also uses it as the
	// library/grouping key.
	ProductNumber string

	// DiscNumber is the 1-based position of this disc within the game.
	DiscNumber int

	// DiscTotal is the total number of discs the game spans.
	DiscTotal int

	// Title is the on-disc game title, used as a display-name fallback.
	Title string
}

DiscInfo holds the disc-derived facts the UI needs to group a game's discs and resolve metadata. It contains only values read off the disc itself; it carries no knowledge of any external catalog (e.g. RDB) serial conventions.

type DiscReader added in v0.6.0

type DiscReader interface {
	// ReadSector returns the raw 2352-byte sector at the given LBA.
	ReadSector(lba int) ([]byte, error)

	// NumTracks returns the number of tracks on the disc.
	NumTracks() int

	// Track returns the TOC fields for track index i in [0, NumTracks).
	Track(i int) (number int, typ string, frames int, pregap int, startLBA int, control uint8)

	// NumTrackIndexes returns the count of index entries (index numbers >= 1)
	// for track index i in [0, NumTracks). Index 0 (the pregap) is not reported
	// here; it is implied for any FAD below the first entry.
	NumTrackIndexes(i int) int

	// TrackIndex returns the nth index entry of track index i. n is a 0-based
	// ordinal into the exposed list in [0, NumTrackIndexes(i)), not the index
	// number; entry 0 is the lowest-numbered exposed index (normally INDEX 01).
	// The returned lba is the absolute disc LBA of the index.
	TrackIndex(i, n int) (indexNumber int, lba int)

	// Close releases the underlying resources.
	Close() error
}

DiscReader is a streaming reader over a CD/disc image. Every signature uses only stdlib types and no named aggregate, so a concrete reader satisfies this interface structurally without importing this package.

type Emulator

type Emulator interface {
	// RunFrame executes one frame of emulation.
	RunFrame()

	// GetFramebuffer returns the current frame as RGBA pixel data.
	GetFramebuffer() []byte

	// GetFramebufferStride returns bytes per row in the framebuffer.
	GetFramebufferStride() int

	// GetActiveHeight returns the current active display height in pixels.
	GetActiveHeight() int

	// GetAudioSamples returns stereo 16-bit PCM audio samples for the frame.
	GetAudioSamples() []int16

	// SetInput sets controller state as a button bitmask for the given player.
	SetInput(player int, buttons uint32)

	// GetTiming returns FPS and scanline count for the current region.
	GetTiming() Timing

	// SetOption applies a core option change identified by key.
	SetOption(key string, value string)

	// SetRom provides cartridge ROM data. Called after CreateEmulator and
	// before Start(). Disc-based cores ignore this and receive content via
	// SetDisc instead.
	SetRom(data []byte)

	// SetDisc provides a streaming disc reader for disc-based cores. Called
	// after CreateEmulator and before Start(). Cartridge cores ignore this.
	SetDisc(disc DiscReader)

	// SetBIOS provides BIOS data for the given key. Called after
	// CreateEmulator and before Start(). Cores without BIOS ignore this.
	// Returns an error if the data is invalid for the given key.
	SetBIOS(key string, data []byte) error

	// Start finalizes emulator state after all options are applied.
	// Must be called after SetOption and before the first RunFrame.
	Start()

	// Close releases any resources held by the emulator.
	Close()
}

Emulator is the core interface that every emulator adapter must implement.

type Memory added in v0.8.0

type Memory interface {
	// ReadMemory reads from a native bus address into buf and returns
	// the number of bytes read.
	ReadMemory(addr uint32, buf []byte) uint32

	// WriteMemory writes data to a native bus address and returns the
	// number of bytes written.
	WriteMemory(addr uint32, data []byte) uint32

	// Regions describes the accessible bus regions in canonical
	// addresses. The table is static per machine.
	Regions() []BusRegion

	// ReadMemoryFlat reads from the console's flat memory convention
	// (the RetroAchievements layout) into buf and returns the number
	// of bytes read. Reads are contiguous across region boundaries
	// within the flat space.
	ReadMemoryFlat(off uint32, buf []byte) uint32

	// WriteMemoryFlat writes data to the console's flat memory
	// convention and returns the number of bytes written, matching
	// ReadMemoryFlat's layout and boundary behavior.
	WriteMemoryFlat(off uint32, data []byte) uint32
}

Memory provides canonical native bus address based access to the console's emulated RAM.

type MetadataVariant

type MetadataVariant struct {
	Name          string // Display name, e.g. "Neo Geo Pocket"
	RDBName       string // e.g. "SNK - Neo Geo Pocket"
	ThumbnailRepo string // e.g. "SNK_-_Neo_Geo_Pocket"
	RumbleRepoDir string // e.g. "ngp"
	ConsoleID     int    // RetroAchievements console ID override; 0 = use SystemInfo.ConsoleID
}

MetadataVariant pairs an RDB database with its thumbnail repository. Systems that span multiple libretro databases (e.g. NGP + NGPC) have multiple variants so metadata lookups can search all of them.

type SaveStater

type SaveStater interface {
	// Serialize captures the complete emulator state.
	Serialize() ([]byte, error)

	// Deserialize restores emulator state from previously serialized data.
	Deserialize(data []byte) error
}

SaveStater enables save states, rewind, and auto-save.

type SystemInfo

type SystemInfo struct {
	Name             string
	ConsoleName      string
	Extensions       []string
	ScreenWidth      int
	MaxScreenHeight  int
	PixelAspectRatio float64
	SampleRate       int
	Buttons          []Button
	Players          int
	CoreOptions      []CoreOption
	MetadataVariants []MetadataVariant
	DataDirName      string
	ConsoleID        int
	CoreName         string
	CoreVersion      string
	SerializeSize    int
	BigEndianMemory  bool // true for big-endian CPUs (e.g. 68K)
	Disc             bool // true if content is a disc image (use SetDisc)
	BIOSOptions      []BIOSOption
}

SystemInfo describes an emulator system for UI configuration.

type Timing

type Timing struct {
	FPS       int
	Scanlines int
}

Timing holds the frame rate and scanline count for the current region. CPU clocks are core-internal and not exposed here.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL