SDL: Optimized SDL_DuplicatePixels()

From c3e821fa803e5733ebf03e0178fd44d356de6080 Mon Sep 17 00:00:00 2001
From: Sam Lantinga <[EMAIL REDACTED]>
Date: Sat, 3 Feb 2024 10:32:55 -0800
Subject: [PATCH] Optimized SDL_DuplicatePixels()

---
 src/video/SDL_surface.c | 24 +++++++++++++++---------
 1 file changed, 15 insertions(+), 9 deletions(-)

diff --git a/src/video/SDL_surface.c b/src/video/SDL_surface.c
index f3c289085a44..11f7906f6a87 100644
--- a/src/video/SDL_surface.c
+++ b/src/video/SDL_surface.c
@@ -1554,17 +1554,23 @@ static void SDL_DestroySurfaceOnStack(SDL_Surface *surface)
 
 SDL_Surface *SDL_DuplicatePixels(int width, int height, Uint32 format, SDL_Colorspace colorspace, void *pixels, int pitch)
 {
-    SDL_Surface surface;
-    SDL_PixelFormat fmt;
-    SDL_BlitMap blitmap;
-    SDL_Surface *result = NULL;
-
-    if (SDL_CreateSurfaceOnStack(width, height, format, colorspace, pixels, pitch, &surface, &fmt, &blitmap)) {
-        result = SDL_DuplicateSurface(&surface);
+    SDL_Surface *surface = SDL_CreateSurface(width, height, format);
+    if (surface) {
+        int length = width * SDL_BYTESPERPIXEL(format);
+        Uint8 *src = (Uint8 *)pixels;
+        Uint8 *dst = (Uint8 *)surface->pixels;
+        int rows = height;
+        while (rows--) {
+            SDL_memcpy(dst, src, length);
+            dst += surface->pitch;
+            src += pitch;
+        }
 
-        SDL_DestroySurfaceOnStack(&surface);
+        if (colorspace != SDL_GetDefaultColorspaceForFormat(format)) {
+            SDL_SetNumberProperty(SDL_GetSurfaceProperties(surface), SDL_PROP_SURFACE_COLORSPACE_NUMBER, colorspace);
+        }
     }
-    return result;
+    return surface;
 }
 
 int SDL_ConvertPixelsAndColorspace(int width, int height,