Porting Snes9x

# How to Port Snes9x to a New Platform

Version: 1.59.2

## Introduction

This is brief description of the steps to port Snes9x to the new platform. It describes what code you have to write and what functions exist that you can make use of. It also gives some insights as to how Snes9x actually works, although that will be subject of another document yet to be written.

## System Requirements

A C++ compiler. For the most part Snes9x really isn't written in C++, it just uses the C++ compiler as a “better C” compiler to get inline functions and so on. GCC is good for compiling Snes9x (http://gcc.gnu.org/).

A fast CPU. SNES emulation is very compute intensive; two, or sometimes three CPUs to emulate, an 8-channel 16-bit stereo sound digital signal processor with real-time sample decompression, filter and echo effects, two custom graphics processor chips that can produce transparency, scaling, rotation and window effects in 32768 colors, and finally hardware DMA all take their toll on the host CPU.

Enough RAM. Snes9x uses 8MB to load SNES ROM images and several MB for emulating sound, graphics, custom chips, and so on.

A 16-bit color (two bytes per pixel) or deeper display, at least 512*478 pixels in resolution. Pixel format conversion may be required before you place the rendered SNES screen on to the display.

Snes9x outputs 16-bit stereo digital sound data. Ports may convert it from there to 8-bit or mono. Some ports can use interrupts or callbacks from the sound system to know when more sound data is required, most other ports have to periodically poll the host sound system to see if more data is required; if it is then the sound mixing code is called to fill the sound buffer with SNES sound data, which then can be passed on to the host sound system. Sound data is generated as an array of bytes (`uint8`) for 8-bit sound or shorts (`int16`) for 16-bit data. Stereo sound data generates twice as many samples, with each channel's samples interleaved, first left's then right's.

For the user to be able to control and play SNES games, some form of input device is required, a joypad or keyboard, for example. The real SNES can have 2 eight-button digital joypads connected to it or 5 joypads when an optional multi-player adaptor is connected, although most games only require a single joypad. Access to all eight buttons and the direction pad, of course, are usually required by most games. Snes9x does emulate the multi-player adaptor hardware, if you were wondering, but its still up to you to provide the emulation of the individual joypads.

The real SNES also has a SNES mouse, Super Scope and Justifier (light-gun) available as optional extras. Snes9x can emulate all of these using some form of pointing device, usually the host system's mouse.

Some SNES game cartridges contains a small amount of extra RAM and a battery, so ROMs could save a player's progress through a game for games that takes many hours to play from start to finish. Snes9x simulates this S-RAM by saving the contents of the area of memory occupied by the S-RAM into a file then automatically restoring it again the next time the user plays the same game. If the hardware you're porting to doesn't have a storage media available then you could be in trouble.

Snes9x also implements freeze-game files which can record the state of the SNES hardware and RAM at a particular point in time and can restore it to that exact state at a later date - the result is that users can save a game at any point, not just at save-game or password points provided by the original game coders. Each freeze file is over 400k in size. To help save disk space, Snes9x can be compiled with zlib (http://www.zlib.net/), which is used to GZIP compress the freeze files, reducing the size to typically below 100k. zlib is also used to load GZIP or ZIP compressed ROM images. Additionally, Snes9x supports JMA archives compressed with NSRT (http://nsrt.edgeemu.com/).

## Compile-Time Options

### `DEBUGGER`

Enables extra code to assist you in debugging SNES ROMs. The debugger has only ever been a quick-hack and user-interface to debugger facilities is virtually non-existent. Most of the debugger information is output via stdout and enabling the debugger slows the whole emulator down slightly. However, the debugger options available are very powerful; you could use it to help get your port working. You probably still want to ship the finished version with the debugger disabled, it will only confuse non-technical users.

### `RIGHTSHIFT_IS_SAR`

Define this if your compiler uses shift right arithmetic for signed values. For example, GCC and Visual C++ use shift right arithmetic.

### `ZLIB / UNZIP_SUPPORT / JMA_SUPPORT`

Define these if you want to support GZIP/ZIP/JMA compressed ROM images and GZIP compressed freeze-game files.

### `USE_OPENGL`

Define this and set `Settings.OpenGLEnable` to `true`, then you'll get the rendered SNES image as one OpenGL texture.

### Typical Options Common for Most Platforms

`ZLIB
UNZIP_SUPPORT
JMA_SUPPORT
RIGHTSHIFT_IS_SAR
`

## Editing port.h

You may need to edit `port.h` to fit Snes9x to your system.

If the byte ordering of your system is least significant byte first, make sure `LSB_FIRST` is defined, otherwise make sure it's not defined.

You'll need to make sure what pixel format your system uses for 16-bit colors (`RGB565`, `RGB555`, `BGR565` or `BGR555`), and if it's not `RGB565`, define `PIXEL_FORMAT` to it so that Snes9x will use it to render the SNES screen. For example, Windows uses `RGB565`, Mac OS X uses `RGB555`. If your system supports more than one pixel format, you can define `GFX_MULTI_FORMAT` and change Snes9x's pixel format dynamically by calling `S9xSetRenderPixelFormat` function. If your system is 24 or 32-bit only, then don't define anything; instead write a conversion routine that will take a complete rendered 16-bit SNES screen in `RGB565` format and convert to the format required to be displayed on your system.

`port.h` also typedefs some types; `uint8` for an unsigned 8-bit quantity, `uint16` for an unsigned 16-bit quantity, `uint32` for a 32-bit unsigned quantity and `bool8` for a `true`/`false` type. Signed versions are also typedef'ed.

## Controllers Management

Read `controls.h`, `crosshair.h`, `controls.txt` and `control-inputs.txt` for details. This section is the minimal explanation to get the SNES controls workable.

The real SNES allows several different types of devices to be plugged into the game controller ports. The devices Snes9x emulates are a joypad, multi-player adaptor known as the Multi Player 5 or Multi Tap (allowing a further 4 joypads to be plugged in), a 2-button mouse, a light gun known as the Super Scope, and a light gun known as the Justifier.

In your initialization code, call `S9xUnmapAllControl` function.

Map any IDs to each SNES controller's buttons and pointers. (ID 249-255 are reserved).

Typically, use `S9xMapPointer` function for the pointer of the SNES mouse, Super Scope and Justifier, `S9xMapButton` function for other buttons. Set `poll` to `false` for the joypad buttons, `true` for the other buttons and pointers.

`S9xMapButton(k1P_A_Button, s9xcommand_t cmd = S9xGetCommandT("Joypad1 A"), false);`

In your main emulation loop, before `S9xMainLoop` function is called, check your system's keyboard/joypad, and call `S9xReportButton` function to report the states of the SNES joypad buttons to Snes9x. Checking and reporting input immediately before `S9xMainLoop` is preferred to minimize input latency.

`void MyMainLoop (void)
{
MyReportButttons();
S9xMainLoop();
}`

`void MyReportButtons (void)
{
S9xReportButton(k1P_A_Button, (key_is_pressed ? true : false));
}`

Prepare your `S9xPollButton` and `S9xPollPointer` function to reply Snes9x's request for other buttons/cursors states.

Call `S9xSetController` function. It connects each input device to each SNES input port.
Here's typical controller settings that is used by the real SNES games:

Joypad
`S9xSetController(0, CTL_JOYPAD, 0, 0, 0, 0);
S9xSetController(1, CTL_JOYPAD, 1, 0, 0, 0);`

Mouse (port 1)
`S9xSetController(0, CTL_MOUSE, 0, 0, 0, 0);
S9xSetController(1, CTL_JOYPAD, 1, 0, 0, 0);`

Mouse (port 2)
`S9xSetController(0, CTL_JOYPAD, 0, 0, 0, 0);
S9xSetController(1, CTL_MOUSE, 1, 0, 0, 0);`

Super Scope
`S9xSetController(0, CTL_JOYPAD, 0, 0, 0, 0);
S9xSetController(1, CTL_SUPERSCOPE, 0, 0, 0, 0);`

Multi Player 5
`S9xSetController(0, CTL_JOYPAD, 0, 0, 0, 0);
S9xSetController(1, CTL_MP5, 1, 2, 3, 4);`

Justifier
`S9xSetController(0, CTL_JOYPAD, 0, 0, 0, 0);
S9xSetController(1, CTL_JUSTIFIER, 0, 0, 0, 0);`

Justifier (2 players)
`S9xSetController(0, CTL_JOYPAD, 0, 0, 0, 0);
S9xSetController(1, CTL_JUSTIFIER, 1, 0, 0, 0);`

## Existing Interface Functions

### `bool8 Memory.Init (void)`

Allocates and initializes several major lumps of memory, for example the SNES ROM and RAM arrays, tile cache arrays, etc. Returns `false` if memory allocation fails.

### `void Memory.Deinit (void)`

Deallocates the memory allocations made by `Memory.Init` function.

### `bool8 S9xGraphicsInit (void)`

Allocates and initializes several lookup tables used to speed up SNES graphics rendering. Call after you have initialized the `GFX.Screen` and `GFX.Pitch` values. Returns `false` if memory allocation fails.

### `void S9xGraphicsDeinit (void)`

Deallocates the memory allocations made by `S9xGraphicsInit` function.

### `bool8 S9xInitAPU (void)`

Allocates and initializes several arrays used by the sound CPU and sound generation code. Returns `false` if memory allocation fails.

### `void S9xDeinitAPU (void)`

Deallocates the allocations made by `S9xInitAPU` function.

### `bool8 S9xInitSound (int buffer_ms)`

Allocates memory for mixing and queueing SNES sound data, does more sound code initialization and opens the host system's sound device by calling `S9xOpenSoundDevice`, a function you must provide. Before calling this function you must set up `Settings.SoundSync`, `Settings.SoundPlaybackRate`, and `Settings.SoundInputRate`. (see section below)
`buffer_ms`, given in milliseconds, is the memory buffer size for queueing sound data. Leave this at 0 to use the suggested default.

### `void S9xReset (void)`

Resets the SNES emulated hardware back to the state it was in at “switch-on” except the S-RAM area is preserved (“hardware reset”). The effect is it resets the current game back to the start. This function is automatically called by `Memory.LoadROM` function.

### `void S9xSoftReset (void)`

Similar to `S9xReset` function, but “software reset” as you press the SNES reset button.

### `bool8 Memory.LoadROM (const char *filepath)`

Attempts to load the specified ROM image filename into the emulated ROM area. There are many different SNES ROM image formats and the code attempts to auto-detect as many different types as it can and in a vast majority of the cases gets it right.
There are several ROM image options in the `Settings`structure; allow the user to set them before calling `Memory.LoadROM` function, or make sure they are all reset to default values before each call to `Memory.LoadROM` function. See `Settings.ForceXXX` in `snes9x.h`.

### `bool8 Memory.LoadMultiCart (const char *cartApath, const char *cartBpath)`

Attempts to load multiple ROM images into the emulated ROM area, for the multiple cartridge systems such as Sufami Turbo, Same Game, etc.

### `bool8 Memory.LoadSRAM (const char *filepath)`

Call this function to load the associated S-RAM save file (if any). The filename should be based on the ROM image name to allow easy linkage. The current ports change the directory and the filename extension of the ROM filename to derive the S-RAM filename.

### `bool8 Memory.SaveSRAM (const char *filepath)`

Call this function to save the emulated S-RAM area into a file so it can be restored again the next time the user wants to play the game. Remember to call this when just before the emulator exits or when the user has been playing a game and is about to load another one.

### `void S9xMainLoop (void)`

The emulator main loop. Call this from your own main loop that calls this function (if a ROM image is loaded and the game is not paused), processes any pending host system events, then goes back around the loop again until the emulator exits. `S9xMainLoop` function normally returns control to your main loop once every emulated frame, when it reaches the start of scan-line zero. However it may take a few frames when a huge memory transfer is being emulated. The function can return more often if the `DEBUGGER` compile-time flag is defined and the CPU has hit a break point, or the `DEBUG_MODE_FLAG` bit is set in `CPU.Flags` or instruction single-stepping is enabled.

### `void S9xMixSamples (uint8 *buffer, int sample_count)`

Call this function from your host sound system handling code to fill `buffer` with ready-mixed SNES sound data. The buffer will be filled with an array of `sample_count` `int16`. Samples are in pairs, first a left channel sample followed by the right channel sample.
If there are fewer queued samples than you request by `sample_count`, the function fills `buffer` with silent sound data and returns `false`.

### `int S9xGetSampleCount (void)`

Returns the number of sound samples available in the buffer for your configured playback settings.

### `void S9xSetSamplesAvailableCallback (void (*) samples_available (void *), void *data)`

Call this function to set up a callback that is run when sound samples are made available. `samples_available` is a function you provide that returns `void` and takes a pointer as an argument. `data` is a pointer that you may wish to pass to your callback or can be `NULL`. Inside this function is the only time that it is safe to access Snes9x's sound data. Ideally, all samples reported available will be removed from Snes9x's buffer when this function is called and moved to either the sound driver output or a separate buffer that can be locked in a thread-safe fashion. If you are using a callback-oriented sound API, it is recommended to set up a separate buffer that can accumulate at least enough samples to fulfill more than one host sound driver callback request.
If you wish to disable a callback you have set up or need to temporarily shut down your sound system, you may pass `NULL` for both arguments.

### `bool8 S9xSyncSound (void)`

Call this function to synchronize the sound buffers to the game state. This will call the `samples_available` function to try and move sound data out of Snes9x. If Snes9x is unable to make enough space to accumulate the sound data for a whole video frame, this function will return `false`. In this case, you may wish to wait until your host sound system uses the available samples, and `S9xSyncSound` returns `true` before continuing to execute `S9xMainLoop`.

### `bool8 S9xSetSoundMute (bool8 mute)`

Call with a `true` parameter to cause the `S9xMixSamples` to fill the output buffer with silence, instead of filling the output buffer with sound data. Useful if your sound system is interrupt or callback driven and the game has been paused either directly or indirectly because the user is interacting with the emulator's user interface in some way.

### `bool8 S9xFreezeGame (const char *filepath)`

Call this function to record the current SNES hardware state into a file, the file can be loaded back using `S9xUnfreezeGame` function at a later date effectively restoring the current game to exact same spot. Call this function while you're processing any pending system events when `S9xMainLoop` function has returned control to you in your main loop.

### `bool8 S9xUnfreezeGame (const char *filepath)`

Restore the SNES hardware back to the exactly the state it was in when `S9xFreezeGame` function was used to generate the file specified. You have to arrange the correct ROM is already loaded using `Memory.LoadROM` function, an easy way to arrange this is to base freeze-game filenames on the ROM image name. The UNIX/Linux ports load freeze-game files when the user presses a function key, with the names romfilename.000 for F1, romfilename.001 for F2, etc. Games are frozen in the first place when the user presses Shift-function key. You could choose some other scheme.

### `void S9xDumpSPCSnapshot (void)`

Call this funtion to make a so-called SPC file, a snapshot of SNES sound state. Actual dump occurs at the first key-on event after this function is called.

### `void S9xSetInfoString (const char *string)`

Call this function if you want to show a message onto the SNES screen.

### Other Available Functions

See `movie.h` and `movie.cpp` to support the Snes9x movie feature.
See `cheats.h`, `cheats.cpp` and `cheats2.cpp` to support the cheat feature.

## Interface Functions You Need to Implement

### `bool8 S9xOpenSnapshotFile (const char *filepath, bool8 read_only, STREAM *file)`

This function opens a freeze-game file. `STREAM` is defined as a `gzFile` if `ZLIB` is defined else it's defined as `FILE *`. The `read_only` parameter is set to `true` when reading a freeze-game file and `false` when writing a freeze-game file. Open the file `filepath` and return its pointer `file`.

### `void S9xCloseSnapshotFile (STREAM file)`

This function closes the freeze-game file opened by `S9xOpenSnapshotFile` function.

### `void S9xExit (void)`

Called when some fatal error situation arises or when the “q” debugger command is used.

### `bool8 S9xInitUpdate (void)`

Called just before Snes9x begins to render an SNES screen. Use this function if you should prepare before drawing, otherwise let it empty.

### `bool8 S9xDeinitUpdate (int width, int height)`

Called once a complete SNES screen has been rendered into the `GFX.Screen` memory buffer, now is your chance to copy the SNES rendered screen to the host computer's screen memory. The problem is that you have to cope with different sized SNES rendered screens: 256*224, 256*239, 512*224, 512*239, 512*448 and 512*478.

### `void S9xMessage (int type, int number, const char *message)`

When Snes9x wants to display an error, information or warning message, it calls this function. Check in `messages.h` for the types and individual message numbers that Snes9x currently passes as parameters.
The idea is display the message string so the user can see it, but you choose not to display anything at all, or change the message based on the message number or message type.
Eventually all debug output will also go via this function, trace information already does.

### `bool8 S9xOpenSoundDevice (void)`

`S9xInitSound` function calls this function to actually open the host sound device.

### `const char *S9xGetFilename (const char *extension, enum s9x_getdirtype dirtype)`

When Snes9x needs to know the name of the cheat/IPS file and so on, this function is called. Check `extension` and `dirtype`, and return the appropriate filename. The current ports return the ROM file path with the given extension.

### `const char *S9xGetFilenameInc (const char *extension, enum s9x_getdirtype dirtype)`

Almost the same as `S9xGetFilename` function, but used for saving SPC files etc. So you have to take care not to delete the previously saved file, by increasing the number of the filename; romname.000.spc, romname.001.spc, ...

### `const char *S9xGetDirectory (enum s9x_getdirtype dirtype)`

Called when Snes9x wants to know the directory `dirtype`.

### `const char *S9xChooseFilename (bool8 read_only)`

If your port can match Snes9x's built-in `LoadFreezeFile`/`SaveFreezeFile` command (see `controls.cpp`), you may choose to use this function. Otherwise return `NULL`.

### `const char *S9xChooseMovieFilename (bool8 read_only)`

If your port can match Snes9x's built-in `BeginRecordingMovie`/`LoadMovie` command (see `controls.cpp`), you may choose to use this function. Otherwise return `NULL`.

### `const char *S9xBasename (const char *path)`

Called when Snes9x wants to know the name of the ROM image. Typically, extract the filename from `path` and return it.

### `void S9xAutoSaveSRAM (void)`

If `Settings.AutoSaveDelay` is not zero, Snes9x calls this function when the contents of the S-RAM has been changed. Typically, call `Memory.SaveSRAM` function from this function.

### `void S9xToggleSoundChannel (int c)`

If your port can match Snes9x's built-in `SoundChannelXXX` command (see `controls.cpp`), you may choose to use this function. Otherwise return `NULL`. Basically, turn on/off the sound channel `c` (0-7), and turn on all channels if `c` is 8.

### `void S9xSetPalette (void)`

Called when the SNES color palette has changed. Use this function if your system needs to change its color palette to match the SNES's. Otherwise, leave it empty.

### `void S9xSyncSpeed (void)`

Called at the end of `S9xMainLoop` function, when emulating one frame has been done. You should adjust the frame rate in this function.

## Global Variables

### `uint16 *GFX.Screen`

A `uint16` array pointer to (at least) 2*512*478 bytes buffer where Snes9x puts the rendered SNES screen. However, if your port will not support hires mode (`Settings.SupportHiRes = false`), then a 2*256*239 bytes buffer is allowed. You should allocate the space by yourself. As well you can change the `GFX.Screen` value after `S9xDeinitUpdate` function is called so that double-buffering will be easy.

### `uint32 GFX.Pitch`

Bytes per line (not pixels per line) of the `GFX.Screen` buffer. Typically set it to 1024. When the SNES screen is 256 pixels width and `Settings.OpenGLEnable` is `false`, last half 512 bytes per line are unused. When `Settings.OpenGLEnable` is `true`, `GFX.Pitch` is ignored.

### Settings structure

There are various switches in the `Settings` structure. See `snes9x.h` for details. At least the settings below are required for good emulation.

`memset(&Settings, 0, sizeof(Settings));
Settings.MouseMaster = true;
Settings.SuperScopeMaster = true;
Settings.JustifierMaster = true;
Settings.MultiPlayer5Master = true;
Settings.FrameTimePAL = 20000;
Settings.FrameTimeNTSC = 16667;
Settings.SoundPlaybackRate = 32000;
Settings.SoundInputRate = 31947;
Settings.SupportHiRes = true;
Settings.Transparency = true;
Settings.AutoDisplayMessages = true;
Settings.InitialInfoStringTimeout = 120;
Settings.HDMATimingHack = 100;
Settings.BlockInvalidVRAMAccessMaster = true;`

### `Settings.SoundInputRate`

Adjusts the sound rate through resampling. For every `Settings.SoundInputRate` samples generated by the SNES, `Settings.SoundPlaybackRate` samples will be produced.

On a NTSC SNES, the video refresh rate is usually 60.09881Hz, while the audio output is 32000Hz. This means for every video frame displayed, 532.4565 sound frames are produced. A modern computer display or television will usually provide one of two video rates, 60.00Hz exactly or 59.94Hz to support broadcast television. The sound output, however, is usually fixed at exact values like 32000Hz, 44100Hz, or 48000Hz. This means that the closest video-to-sound ratio we can achieve, with 60.00Hz and 32000Hz, is 1.0/533.3333. This discrepancy means if we wait for vertical sync and update once per refresh, we will experience a sound deficit of 0.87 samples every frame, eventually causing a sound underrun and producing audio problems.

Settings.SoundInputRate can be set to a value such that the ratio with the video rate matches the SNES output. A 60.00Hz display, for example, should be set to 60.00 / 60.09881 * 32000, which is about 31947. The Snes9x resampler will then stretch the sound samples to fit this ratio. It may be beneficial to provide an option for users to configure `Settings.SoundInputRate` to suit their own systems. Setting `Settings.SoundInputRate` to a value that matches the actual output rate (i.e. 31915hz for 59.94Hz) or lower will allow the users to eliminate crackling. A range of 31000hz to 33000hz should be inclusive enough for all displays. Use of this setting paired with the `S9xSyncSound` function can eliminate sound discontinuity. However, this concept is difficult for most users to understand. If possible, read the display's refresh rate and automatically calculate the appropriate input rate by default. In practice, few displays exceed a target of 60.00Hz, so a good default would be no greater than 31947Hz, but probably lower.

### `Settings.DynamicRateControl` and `S9xUpdateDynamicRate(int numerator, int denominator)`

To eliminate buffer overflows and underflows, dynamic rate control can be implemented and used. While this can accommodate for Settings.SoundInputRate not being set correctly, it works better the closer that value is to ideal.

To implement, set `Settings.DynamicRateControl` to `true`. At the beginning of your `samples_available` callback, check the hardware output buffer's fill level. Report the amount of free space in the buffer as a fraction of total buffer size to `S9xUpdateDynamicRate`, and Snes9x will try and keep the buffer close to 50% full. To tune this, `Settings.DynamicRateLimit` can be changed. A larger value will increase the range of frequencies it can use, but will also cause more noticeable pitch changes.

Original document (c) Copyright 1998 Gary Henderson; Updated most recently by: 2019/2/26 BearOso