sdl2-compat: Calculate the pixel format in SDL_ConvertSurface()

From f361c2a96658bd2e81892a65e4ca4fcf00e92f05 Mon Sep 17 00:00:00 2001
From: Sam Lantinga <[EMAIL REDACTED]>
Date: Sun, 2 Feb 2025 15:42:54 -0800
Subject: [PATCH] Calculate the pixel format in SDL_ConvertSurface()

SDL2 ignored the format->format value and always used the masks instead.

This fixes SDL_ConvertSurface() in Dwarf Fortress, which is called with a format corresponding to SDL_PIXELFORMAT_ABGR8888, but with the format member left uninitialized.

Fixes https://github.com/libsdl-org/sdl2-compat/issues/295
---
 src/sdl2_compat.c | 9 ++++++++-
 1 file changed, 8 insertions(+), 1 deletion(-)

diff --git a/src/sdl2_compat.c b/src/sdl2_compat.c
index 2539ba3..08e5b53 100644
--- a/src/sdl2_compat.c
+++ b/src/sdl2_compat.c
@@ -2984,6 +2984,7 @@ SDL_DECLSPEC SDL2_Surface * SDLCALL
 SDL_ConvertSurface(SDL2_Surface *surface, const SDL2_PixelFormat *format, Uint32 flags)
 {
     SDL_Palette *palette = NULL;
+    SDL_PixelFormat pixel_format;
     SDL2_Surface *result;
 
     (void) flags; /* SDL3 removed the (unused) `flags` argument */
@@ -2997,6 +2998,12 @@ SDL_ConvertSurface(SDL2_Surface *surface, const SDL2_PixelFormat *format, Uint32
         return NULL;
     }
 
+    pixel_format = SDL3_GetPixelFormatForMasks(format->BitsPerPixel, format->Rmask, format->Gmask, format->Bmask, format->Amask);
+    if (pixel_format == SDL_PIXELFORMAT_UNKNOWN) {
+        SDL3_InvalidParamError("format");
+        return NULL;
+    }
+
     if (format->palette) {
         // This conversion is going to assign the new surface this palette,
         // but it might be on the stack, so always allocate a new one to be
@@ -3009,7 +3016,7 @@ SDL_ConvertSurface(SDL2_Surface *surface, const SDL2_PixelFormat *format, Uint32
         SDL3_SetPaletteColors(palette, format->palette->colors, 0, ncolors);
     }
 
-    result = Surface3to2(SDL3_ConvertSurfaceAndColorspace(Surface2to3(surface), (SDL_PixelFormat)format->format, palette, SDL_COLORSPACE_SRGB, 0));
+    result = Surface3to2(SDL3_ConvertSurfaceAndColorspace(Surface2to3(surface), pixel_format, palette, SDL_COLORSPACE_SRGB, 0));
 
     if (palette) {
         SDL3_DestroyPalette(palette);