Files
ci-libretro-fceumm/src/palette.c
U-DESKTOP-SPFP6AQ\twistedtechre 6359a0b36e core: stride-aware savestate, iNES2 helpers, -Wundef, -Wmissing-prototypes
Audit pass 5 - five distinct cleanups bundled into one omnibus.

1. Element-stride byte-swapping for savestate fields (state.h, state.c,
   fceu-endian.{h,c})

   The SFORMAT 's' field was previously {bit 31 = RLSB, bits 0..30 =
   byte size}. RLSB triggers FlipByteOrder() on MSB hosts, which
   reverses the entire entry buffer end-to-end. That is correct for a
   single primitive (size <= 8 bytes) but wrong for an array of
   multi-byte primitives - reversing the whole buffer would swap
   element 0 with element N-1 and reverse their bytes too, scrambling
   the data.

   The previous workaround was either splitting an N-element array
   into N separate single-primitive entries with distinct chunk IDs
   (n106 PlayIndex split into IDX0..IDX7) or skipping the entry
   entirely on big-endian hosts (the GEKKO #ifndef in vrc6.c / vrc7.c).
   Both approaches mean BE saves are not portable to LE and vice
   versa, and force the same workaround at every new array site.

   This pass adds proper stride support:

     * SFORMAT 's' encoding is now {bit 31 = RLSB, bits 24..30 =
       stride in bytes (0 = legacy/unset), bits 0..23 = byte size}.
       16 MiB max size, well above any actual savestate field.
     * FCEUSTATE_RLSB_ARRAY(stride) macro for the new pattern.
     * FlipByteOrderStrided() byte-swaps each element of an array
       independently. Round-trip identity verified: [01 00 00 00 ...]
       -> [00 00 00 01 ...] -> [01 00 00 00 ...].
     * state.c's SubWrite / ReadStateChunk / CheckS use new helpers
       sf_size() / sf_stride() / sf_flip() that mask the size out of
       the new bit layout and dispatch to the strided variant when
       stride < size.

   Backwards compatible: legacy single-primitive entries (size == 1,
   2, 4, 8) leave the stride bits at zero, which sf_stride() reads
   as "stride equals size" and falls through to FlipByteOrder() as
   before. No on-disk format change. Existing single-primitive RLSB
   sites are unchanged.

   The infrastructure is now in place so any future SFORMAT entry
   that is an array of multi-byte primitives can be expressed as a
   single entry (e.g. "{ buf, sizeof(buf) | FCEUSTATE_RLSB_ARRAY(4),
   "BUF." }") without splitting or skipping. The existing PlayIndex
   split and GEKKO #ifndefs are intentionally left untouched -
   migrating them would alter the on-disk savestate format and is a
   separate decision.

2. iNES1-vs-iNES2 sizing helpers (cart.h)

   Twelve sites across the codebase encoded the same conditional:

     info->iNES2 ? (info->PRGRamSize + info->PRGRamSaveSize) : default

   Sometimes for PRGRAM, sometimes for CHRRAM, sometimes in bytes,
   sometimes after dividing by 1024. The pattern is verbose and easy
   to write inconsistently.

   Added two inline helpers in cart.h:
     - CartInfo_PRGRAM_bytes(info, default_bytes)
     - CartInfo_CHRRAM_bytes(info, default_bytes)

   Migrated 9 of the 13 sites: cartram.c (2), 162.c, 163.c, 134.c,
   399.c, 478.c, 480.c, 484.c. The remaining 4 are non-helper-fitting
   variants (164.c special masking, 2 cartram SaveGameLen sites with
   different fallback semantics, mmc3.c Boogerman submapper detection).

3. -Wundef enabled permanently (Makefile.libretro)

   Zero warnings out of the box - no #if-on-undefined-macro footguns
   in the codebase. Now part of WARNING_DEFINES alongside the existing
   -Wsign-compare.

4. -Wmissing-prototypes enabled permanently (Makefile.libretro)

   Started at 198 warnings, cleared all of them:

     * Mass-static-ified ~96 functions across 75 files that were
       defined non-static but only used within their own translation
       unit. (See static_prototype_fixer.py in the development notes.)
     * K&R-style empty-parens prototypes "()" replaced with explicit
       "(void)" across all asic_*.{c,h} files - GCC treats "()" as
       "any args" and refuses to match it against a separate K&R
       definition.
     * Added missing forward declarations to public headers:
         - fds.h (FDSLoad)
         - nsf.h (NSFLoad)
         - ines.h (iNESLoad)
         - unif.h (UNIFLoad)
         - latch.h (LatchHardReset, K&R fix)
         - eeprom_93Cx6.h (eeprom_93Cx6_read, K&R fix)
       Each header gained an "#include "file.h"" where needed.
     * fds_apu.c now includes its own fds_apu.h header (was missing).
     * fds_apu.h: removed unused FDSSoundRead declaration (the function
       is internal-static).
     * cartram.h: removed unused CartRAM_close declaration (the function
       is internal-static).
     * input.h: added a centralised block of FCEU_Init* prototypes
       (Zapper, Mouse, Powerpad, Arkanoid, VirtualBoy, FKB, SuborKB,
       PEC586KB, HS, Mahjong, FamilyTrainerA/B, OekaKids, TopRider,
       BarcodeWorld, BattleBox, QuizKing, FTrainerA/B, SpaceShadow,
       LCDCompZapper, ArkanoidFC) plus FCEU_ZapperSetTolerance. These
       were previously declared as "extern" inside src/input.c.
     * Static-ified FP_FASTAPASS callbacks in 106.c, 65.c, 67.c,
       asic_h3001.c, asic_vrc3.c (those with no external callers);
       left non-static for those that have header decls or are
       referenced from sibling .c files (asic_mmc1, asic_vrc6,
       asic_vrc7, flashrom).
     * For a small set of cross-file functions where adding a header
       was disproportionate to the value (MMC5_hb, NSFMMC5_Close,
       GetKeyboard, FCEU_GetJoyJoy), placed a forward declaration
       immediately above the definition. This satisfies
       -Wmissing-prototypes (which checks for any prior declaration
       in scope) without churning the public-header layout.

5. -Wshadow partial cleanup (not enabled permanently)

   Fixed five real shadows that were either bugs or actively
   misleading:

     * src/boards/476.c: removed an inner "int i" that shadowed the
       outer loop counter.
     * src/boards/mmc5.c MMC5_hb: parameter "scanline" renamed to
       "sl_param" (was shadowing the global "scanline").
     * src/boards/n106.c DoNamcoSound: parameter "Wave" renamed to
       "WaveBuf" (was shadowing the global Wave audio buffer); also
       updated the forward declaration and the matching parameter
       on sound.h's NeoFill function pointer typedef.
     * src/boards/vrc7.c UpdateOPLNEO: same Wave -> WaveBuf rename.
     * src/ntsc/nes_ntsc_impl.h: renamed an inner loop counter "n"
       that shadowed an outer "n".
     * src/drivers/libretro/libretro.c FCEUD_RegionOverride: local
       "pal" renamed to "is_pal" (was shadowing the typedef "pal" from
       palette.h).
     * src/palette.c FCEUI_SetPaletteArray: parameter "pal" renamed
       to "data" (same shadow); driver.h declaration updated to match.

   -Wshadow itself is NOT enabled permanently because the remaining
   warnings are deliberate parameter naming conventions (XBuf in
   draw functions, X in cpu hooks) and third-party blargg ntsc code.

In addition, four files were touched as part of an MSVC-build fix
that came up mid-pass: src/fds.c, src/nsf.c, src/ines.c, and
src/drivers/libretro/libretro_dipswitch.c had snprintf() calls
introduced in pass 4 that fail to link on pre-MSVC2015 toolchains
when STATIC_LINKING=1 (the libretro-common compat_snprintf.c shim
isn't compiled in those configurations). Replaced each snprintf with
either sprintf-into-bounded-buffer (the format strings have known
maximum output) or strlcpy/strlcat for the dipswitch key-build case.
All output is still bounded; truncation happens via strl*'s normal
truncation semantics where applicable.

All added code is C89-clean (top-of-block declarations only, no
mixed decls, no // comments, INLINE macro from fceu-types.h instead
of bare "inline"). Builds clean under -std=gnu11 with -Wno-write-
strings -Wsign-compare -Wundef -Wmissing-prototypes; zero errors,
zero warnings.

Determinism audit (audit_determinism.py): no rand/time/long
double/threads issues introduced.
2026-05-04 04:44:52 +02:00

238 lines
6.1 KiB
C

/* FCE Ultra - NES/Famicom Emulator
*
* Copyright notice for this file:
* Copyright (C) 2002,2003 Xodnizel
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <stdlib.h>
#include <math.h>
#include <string/stdstring.h>
#include <file/file_path.h>
#include <streams/file_stream.h>
#include "fceu-types.h"
#include "fceu.h"
#include "general.h"
#include "driver.h"
#include "palette.h"
#include "palettes/palettes.h"
/* These are dynamically filled/generated palettes: */
static pal palette_game[512]; /* Custom palette for an individual game. */
static pal palette_user[512]; /* Custom "global" palette. */
uint8_t palette_game_available = false;
uint8_t palette_user_available = false;
static void ChoosePalette(void);
static void WritePalette(void);
uint8_t default_palette_selected = 0;
pal *palo;
static pal *default_palette[8] =
{
palette,
rp2c04_0001,
rp2c04_0002,
rp2c04_0003,
rp2c04_0004,
rp2c03,
};
static void ApplyDeemphasisClassic(int entry, uint8_t *r, uint8_t *g, uint8_t *b) {
static const float rtmul[] = { 1.239f, 0.794f, 1.019f, 0.905f, 1.023f, 0.741f, 0.75f };
static const float gtmul[] = { 0.915f, 1.086f, 0.98f, 1.026f, 0.908f, 0.987f, 0.75f };
static const float btmul[] = { 0.743f, 0.882f, 0.653f, 1.277f, 0.979f, 0.101f, 0.75f };
int nr, ng, nb, d;
int deemph_bits = entry >> 6;
if (deemph_bits == 0) return;
d = deemph_bits - 1;
nr = *r;
ng = *g;
nb = *b;
nr = (int)(nr * rtmul[d]);
ng = (int)(ng * gtmul[d]);
nb = (int)(nb * btmul[d]);
if (nr > 0xFF) nr = 0xFF;
if (ng > 0xFF) ng = 0xFF;
if (nb > 0xFF) nb = 0xFF;
*r = (uint8_t)nr;
*g = (uint8_t)ng;
*b = (uint8_t)nb;
}
static void ApplyDeemphasisComplete(pal *pal512) {
int i, p, idx;
/* for each deemph level beyond 0 */
for (i = 0, idx = 0; i < 8; i++) {
/* for each palette entry */
for (p = 0; p < 64; p++, idx++) {
pal512[idx] = pal512[p];
ApplyDeemphasisClassic(idx, &pal512[idx].r, &pal512[idx].g, &pal512[idx].b);
}
}
}
void FCEUI_SetPaletteArray(uint8_t *data, int nEntries) {
if (!data || !nEntries)
palette_user_available = false;
else {
int x;
palette_user_available = true;
for (x = 0; x < nEntries; x++) {
palette_user[x].r = *((uint8_t*)data + x + x + x);
palette_user[x].g = *((uint8_t*)data + x + x + x + 1);
palette_user[x].b = *((uint8_t*)data + x + x + x + 2);
}
if (nEntries != 512) {
ApplyDeemphasisComplete(palette_user);
}
}
FCEU_ResetPalette();
}
static uint8_t lastd = 0;
void SetNESDeemph(uint8_t d, int force) {
static const uint16_t rtmul[7] = { 32768 * 1.239, 32768 * .794, 32768 * 1.019, 32768 * .905, 32768 * 1.023, 32768 * .741, 32768 * .75 };
static const uint16_t gtmul[7] = { 32768 * .915, 32768 * 1.086, 32768 * .98, 32768 * 1.026, 32768 * .908, 32768 * .987, 32768 * .75 };
static const uint16_t btmul[7] = { 32768 * .743, 32768 * .882, 32768 * .653, 32768 * 1.277, 32768 * .979, 32768 * .101, 32768 * .75 };
uint32_t r, g, b;
int x;
/* If it's not forced(only forced when the palette changes),
don't waste cpu time if the same deemphasis bits are set as the last call. */
if (!force) {
if (d == lastd)
return;
} else { /* Only set this when palette has changed. */
r = rtmul[6];
g = rtmul[6];
b = rtmul[6];
for (x = 0; x < 0x40; x++) {
uint32_t m, n, o;
m = palo[x].r;
n = palo[x].g;
o = palo[x].b;
m = (m * r) >> 15;
n = (n * g) >> 15;
o = (o * b) >> 15;
if (m > 0xff) m = 0xff;
if (n > 0xff) n = 0xff;
if (o > 0xff) o = 0xff;
FCEUD_SetPalette(x | 0xC0, m, n, o);
}
}
if (!d) return; /* No deemphasis, so return. */
r = rtmul[d - 1];
g = gtmul[d - 1];
b = btmul[d - 1];
for (x = 0; x < 0x40; x++) {
uint32_t m, n, o;
m = palo[x].r;
n = palo[x].g;
o = palo[x].b;
m = (m * r) >> 15;
n = (n * g) >> 15;
o = (o * b) >> 15;
if (m > 0xff) m = 0xff;
if (n > 0xff) n = 0xff;
if (o > 0xff) o = 0xff;
FCEUD_SetPalette(x | 0x40, m, n, o);
}
lastd = d;
}
void FCEU_LoadGamePalette(void) {
uint8_t ptmp[64 * 8 * 3];
RFILE *fp = NULL;
char *fn = NULL;
palette_game_available = false;
fn = FCEU_MakeFName(FCEUMKF_PALETTE, 0, 0);
if (!string_is_empty(fn) && path_is_valid(fn))
fp = filestream_open(fn,
RETRO_VFS_FILE_ACCESS_READ,
RETRO_VFS_FILE_ACCESS_HINT_NONE);
if (fp) {
int x;
int ssize = filestream_get_size(fp);
int nEntries = ssize / 3;
filestream_read(fp, ptmp, ssize);
filestream_close(fp);
for (x = 0; x < nEntries; x++) {
palette_game[x].r = ptmp[x + x + x];
palette_game[x].g = ptmp[x + x + x + 1];
palette_game[x].b = ptmp[x + x + x + 2];
}
if (nEntries != 512)
ApplyDeemphasisComplete(palette_game);
palette_game_available = true;
}
free(fn);
}
void FCEU_ResetPalette(void) {
if (GameInfo) {
ChoosePalette();
WritePalette();
}
}
static void ChoosePalette(void) {
if (GameInfo->type == GIT_NSF) {
palo = default_palette[0];
} else if (palette_user_available) {
palo = palette_user;
} else if (palette_game_available) {
palo = palette_game;
} else {
palo = default_palette[default_palette_selected];
ApplyDeemphasisComplete(palo);
}
}
void WritePalette(void) {
int x;
int unvaried = sizeof(unvpalette) / sizeof(unvpalette[0]);
for (x = 0; x < unvaried; x++)
FCEUD_SetPalette(x, unvpalette[x].r, unvpalette[x].g, unvpalette[x].b);
for (x = unvaried; x < 256; x++)
FCEUD_SetPalette(x, 205, 205, 205);
for (x = 0; x < 64; x++)
FCEUD_SetPalette(128 + x, palo[x].r, palo[x].g, palo[x].b);
SetNESDeemph(lastd, 1);
for (x = 0; x < 512; x++) {
FCEUD_SetPalette(256 + x, palo[x].r, palo[x].g, palo[x].b);
}
}