SDL: Enable creation of yuv SDL_Surfaces (#6735)

From 92cd2c0a740375f2069abd12420c5a3c88101add Mon Sep 17 00:00:00 2001
From: Sylvain Becker <[EMAIL REDACTED]>
Date: Fri, 2 Dec 2022 21:53:48 +0100
Subject: [PATCH] Enable creation of yuv SDL_Surfaces (#6735)

---
 .../tests/testoverlay2/testoverlay2.vcxproj   |   7 +-
 WhatsNew.txt                                  |   2 +-
 src/render/SDL_yuv_sw.c                       |  28 +-
 src/video/SDL_pixels.c                        |  12 +-
 src/video/SDL_surface.c                       |  34 +-
 src/video/SDL_yuv.c                           |  48 +++
 src/video/SDL_yuv_c.h                         |   3 +
 test/CMakeLists.txt                           |   2 +-
 test/testoverlay2.c                           | 352 +++++++++++-------
 9 files changed, 329 insertions(+), 159 deletions(-)

diff --git a/VisualC/tests/testoverlay2/testoverlay2.vcxproj b/VisualC/tests/testoverlay2/testoverlay2.vcxproj
index 44ceb2107dee..6f710eaeefef 100644
--- a/VisualC/tests/testoverlay2/testoverlay2.vcxproj
+++ b/VisualC/tests/testoverlay2/testoverlay2.vcxproj
@@ -194,6 +194,12 @@
       <CopyLocalSatelliteAssemblies>false</CopyLocalSatelliteAssemblies>
       <ReferenceOutputAssembly>true</ReferenceOutputAssembly>
     </ProjectReference>
+    <ProjectReference Include="..\..\SDL_test\SDL_test.vcxproj">
+      <Project>{da956fd3-e143-46f2-9fe5-c77bebc56b1a}</Project>
+      <Private>false</Private>
+      <CopyLocalSatelliteAssemblies>false</CopyLocalSatelliteAssemblies>
+      <ReferenceOutputAssembly>true</ReferenceOutputAssembly>
+    </ProjectReference>
   </ItemGroup>
   <ItemGroup>
     <CustomBuild Include="..\..\..\test\moose.dat">
@@ -218,7 +224,6 @@
   <ItemGroup>
     <ClCompile Include="..\..\..\test\testoverlay2.c" />
     <ClCompile Include="..\..\..\test\testutils.c" />
-    <ClCompile Include="..\..\..\test\testyuv_cvt.c" />
   </ItemGroup>
   <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
   <ImportGroup Label="ExtensionTargets">
diff --git a/WhatsNew.txt b/WhatsNew.txt
index 1b25fc9f833d..bbcef46f86cc 100644
--- a/WhatsNew.txt
+++ b/WhatsNew.txt
@@ -29,7 +29,7 @@ General:
     * SDL_HINT_VIDEO_X11_XINERAMA
     * SDL_HINT_VIDEO_X11_XVIDMODE
 * SDL_stdinc.h no longer includes stdio.h, stdlib.h, etc., it only provides the SDL C runtime functionality
-* Added SDL_CreateSurface() and SDL_CreateSurfaceFrom() which replace the SDL_CreateRGBSurface*()
+* Added SDL_CreateSurface() and SDL_CreateSurfaceFrom() which replace the SDL_CreateRGBSurface*(), and can also be used to create YUV surfaces
 * Removed unused 'flags' parameter from SDL_ConvertSurface and SDL_ConvertSurfaceFormat
 * Removed 'SDL_GL_CONTEXT_EGL' from OpenGL configuration attributes
 * SDL_GetTicks() now returns a 64-bit value and the tick values should be directly compared instead of using the SDL_TICKS_PASSED macro
diff --git a/src/render/SDL_yuv_sw.c b/src/render/SDL_yuv_sw.c
index a50538b42f64..f1a37c4f0a5b 100644
--- a/src/render/SDL_yuv_sw.c
+++ b/src/render/SDL_yuv_sw.c
@@ -25,6 +25,7 @@
 #if SDL_HAVE_YUV
 
 #include "SDL_yuv_sw_c.h"
+#include "../video/SDL_yuv_c.h"
 
 SDL_SW_YUVTexture *
 SDL_SW_CreateYUVTexture(Uint32 format, int w, int h)
@@ -56,31 +57,8 @@ SDL_SW_CreateYUVTexture(Uint32 format, int w, int h)
     swdata->w = w;
     swdata->h = h;
     {
-        const int sz_plane = w * h;
-        const int sz_plane_chroma = ((w + 1) / 2) * ((h + 1) / 2);
-        const int sz_plane_packed = ((w + 1) / 2) * h;
-        int dst_size = 0;
-        switch (format) {
-        case SDL_PIXELFORMAT_YV12: /**< Planar mode: Y + V + U  (3 planes) */
-        case SDL_PIXELFORMAT_IYUV: /**< Planar mode: Y + U + V  (3 planes) */
-            dst_size = sz_plane + sz_plane_chroma + sz_plane_chroma;
-            break;
-
-        case SDL_PIXELFORMAT_YUY2: /**< Packed mode: Y0+U0+Y1+V0 (1 plane) */
-        case SDL_PIXELFORMAT_UYVY: /**< Packed mode: U0+Y0+V0+Y1 (1 plane) */
-        case SDL_PIXELFORMAT_YVYU: /**< Packed mode: Y0+V0+Y1+U0 (1 plane) */
-            dst_size = 4 * sz_plane_packed;
-            break;
-
-        case SDL_PIXELFORMAT_NV12: /**< Planar mode: Y + U/V interleaved  (2 planes) */
-        case SDL_PIXELFORMAT_NV21: /**< Planar mode: Y + V/U interleaved  (2 planes) */
-            dst_size = sz_plane + sz_plane_chroma + sz_plane_chroma;
-            break;
-
-        default:
-            SDL_assert(0 && "We should never get here (caught above)");
-            break;
-        }
+        size_t dst_size;
+        SDL_CalculateYUVSize(format, w, h, &dst_size, NULL);
         swdata->pixels = (Uint8 *)SDL_SIMDAlloc(dst_size);
         if (!swdata->pixels) {
             SDL_SW_DestroyYUVTexture(swdata);
diff --git a/src/video/SDL_pixels.c b/src/video/SDL_pixels.c
index 216bfaacfe9f..e6c62124df6a 100644
--- a/src/video/SDL_pixels.c
+++ b/src/video/SDL_pixels.c
@@ -140,11 +140,14 @@ SDL_PixelFormatEnumToMasks(Uint32 format, int *bpp, Uint32 *Rmask,
 {
     Uint32 masks[4];
 
-    /* This function doesn't work with FourCC pixel formats */
+#if SDL_HAVE_YUV
+    /* Partial support for SDL_Surface with FOURCC */
+#else
     if (SDL_ISPIXELFORMAT_FOURCC(format)) {
-        SDL_SetError("FOURCC pixel formats are not supported");
+        SDL_SetError("SDL not built with YUV support");
         return SDL_FALSE;
     }
+#endif
 
     /* Initialize the values here */
     if (SDL_BYTESPERPIXEL(format) <= 2) {
@@ -180,6 +183,11 @@ SDL_PixelFormatEnumToMasks(Uint32 format, int *bpp, Uint32 *Rmask,
         return SDL_TRUE;
     }
 
+    if (SDL_ISPIXELFORMAT_FOURCC(format)) {
+        /* Not a format that uses masks */
+        return SDL_TRUE;
+    }
+
     if (SDL_PIXELTYPE(format) != SDL_PIXELTYPE_PACKED8 &&
         SDL_PIXELTYPE(format) != SDL_PIXELTYPE_PACKED16 &&
         SDL_PIXELTYPE(format) != SDL_PIXELTYPE_PACKED32) {
diff --git a/src/video/SDL_surface.c b/src/video/SDL_surface.c
index 5162d9a6295d..0a25af374fe7 100644
--- a/src/video/SDL_surface.c
+++ b/src/video/SDL_surface.c
@@ -26,6 +26,7 @@
 #include "SDL_pixels_c.h"
 #include "SDL_yuv_c.h"
 #include "../render/SDL_sysrender.h"
+#include "../video/SDL_yuv_c.h"
 
 /* Check to make sure we can safely check multiplication of surface w and pitch and it won't overflow size_t */
 SDL_COMPILE_TIME_ASSERT(surface_size_assumptions,
@@ -142,6 +143,15 @@ SDL_CreateSurface(int width, int height, Uint32 format)
             return NULL;
         }
 
+        if (SDL_ISPIXELFORMAT_FOURCC(surface->format->format)) {
+            /* Get correct size and pitch for YUV formats */
+            if (SDL_CalculateYUVSize(surface->format->format, surface->w, surface->h, &size, &surface->pitch) < 0) {
+                SDL_OutOfMemory();
+                SDL_FreeSurface(surface);
+                return NULL;
+            }
+        }
+
         surface->pixels = SDL_SIMDAlloc(size);
         if (!surface->pixels) {
             SDL_FreeSurface(surface);
@@ -176,8 +186,8 @@ SDL_CreateSurface(int width, int height, Uint32 format)
  */
 SDL_Surface *
 SDL_CreateSurfaceFrom(void *pixels,
-                         int width, int height, int pitch,
-                         Uint32 format)
+                      int width, int height, int pitch,
+                      Uint32 format)
 {
     SDL_Surface *surface;
     size_t minimalPitch;
@@ -1093,6 +1103,23 @@ SDL_ConvertSurface(SDL_Surface *surface, const SDL_PixelFormat *format)
         return NULL;
     }
 
+    if (SDL_ISPIXELFORMAT_FOURCC(format->format) || SDL_ISPIXELFORMAT_FOURCC(surface->format->format)) {
+
+        ret = SDL_ConvertPixels(surface->w, surface->h,
+                                surface->format->format, surface->pixels, surface->pitch,
+                                convert->format->format, convert->pixels, convert->pitch);
+
+        if (ret < 0) {
+            SDL_FreeSurface(convert);
+            return NULL;
+        }
+
+        /* Save the original copy flags */
+        copy_flags = surface->map->info.flags;
+
+        goto end;
+    }
+
     /* Copy the palette if any */
     if (format->palette && convert->format->palette) {
         SDL_memcpy(convert->format->palette->colors,
@@ -1258,6 +1285,9 @@ SDL_ConvertSurface(SDL_Surface *surface, const SDL_PixelFormat *format)
             }
         }
     }
+
+end:
+
     SDL_SetClipRect(convert, &surface->clip_rect);
 
     /* Enable alpha blending by default if the new surface has an
diff --git a/src/video/SDL_yuv.c b/src/video/SDL_yuv.c
index ea87cb4f9aa7..773a375daff2 100644
--- a/src/video/SDL_yuv.c
+++ b/src/video/SDL_yuv.c
@@ -52,6 +52,54 @@ SDL_YUV_CONVERSION_MODE SDL_GetYUVConversionModeForResolution(int width, int hei
     return mode;
 }
 
+/*
+ * Calculate YUV size. 
+ * Output 'pitch' that can be used with SDL_ConvertPixels()
+ *
+ * return 0 on success, -1 on error
+ */
+int SDL_CalculateYUVSize(Uint32 format, int w, int h, size_t *size, int *pitch)
+{
+    const int sz_plane = w * h;
+    const int sz_plane_chroma = ((w + 1) / 2) * ((h + 1) / 2);
+    const int sz_plane_packed = ((w + 1) / 2) * h;
+    int dst_size = 0;
+    switch (format) {
+    case SDL_PIXELFORMAT_YV12: /**< Planar mode: Y + V + U  (3 planes) */
+    case SDL_PIXELFORMAT_IYUV: /**< Planar mode: Y + U + V  (3 planes) */
+        dst_size = sz_plane + sz_plane_chroma + sz_plane_chroma;
+        if (pitch) {
+            *pitch = w;
+        }
+        break;
+
+    case SDL_PIXELFORMAT_YUY2: /**< Packed mode: Y0+U0+Y1+V0 (1 plane) */
+    case SDL_PIXELFORMAT_UYVY: /**< Packed mode: U0+Y0+V0+Y1 (1 plane) */
+    case SDL_PIXELFORMAT_YVYU: /**< Packed mode: Y0+V0+Y1+U0 (1 plane) */
+        dst_size = 4 * sz_plane_packed;
+        if (pitch) {
+            *pitch = ((w + 1) / 2) * 4;
+        }
+        break;
+
+    case SDL_PIXELFORMAT_NV12: /**< Planar mode: Y + U/V interleaved  (2 planes) */
+    case SDL_PIXELFORMAT_NV21: /**< Planar mode: Y + V/U interleaved  (2 planes) */
+        dst_size = sz_plane + sz_plane_chroma + sz_plane_chroma;
+        if (pitch) {
+            *pitch = w;
+        }
+        break;
+
+    default:
+        return -1;
+    }
+
+    if (size) {
+        *size = dst_size;
+    }
+    return 0;
+}
+
 #if SDL_HAVE_YUV
 
 static int GetYUVConversionType(int width, int height, YCbCrType *yuv_type)
diff --git a/src/video/SDL_yuv_c.h b/src/video/SDL_yuv_c.h
index 7bb06fe50478..d37c4b9e1feb 100644
--- a/src/video/SDL_yuv_c.h
+++ b/src/video/SDL_yuv_c.h
@@ -30,6 +30,9 @@ extern int SDL_ConvertPixels_YUV_to_RGB(int width, int height, Uint32 src_format
 extern int SDL_ConvertPixels_RGB_to_YUV(int width, int height, Uint32 src_format, const void *src, int src_pitch, Uint32 dst_format, void *dst, int dst_pitch);
 extern int SDL_ConvertPixels_YUV_to_YUV(int width, int height, Uint32 src_format, const void *src, int src_pitch, Uint32 dst_format, void *dst, int dst_pitch);
 
+
+extern int SDL_CalculateYUVSize(Uint32 format, int w, int h, size_t *size, int *pitch);
+
 #endif /* SDL_yuv_c_h_ */
 
 /* vi: set ts=4 sw=4 expandtab: */
diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt
index f192eef55415..1cccd35280ef 100644
--- a/test/CMakeLists.txt
+++ b/test/CMakeLists.txt
@@ -175,7 +175,7 @@ elseif(HAVE_X11)
     target_link_libraries(testnative PRIVATE X11)
 endif()
 
-add_sdl_test_executable(testoverlay2 NEEDS_RESOURCES TESTUTILS testoverlay2.c testyuv_cvt.c)
+add_sdl_test_executable(testoverlay2 NEEDS_RESOURCES TESTUTILS testoverlay2.c)
 add_sdl_test_executable(testplatform NONINTERACTIVE testplatform.c)
 add_sdl_test_executable(testpower NONINTERACTIVE testpower.c)
 add_sdl_test_executable(testfilesystem NONINTERACTIVE testfilesystem.c)
diff --git a/test/testoverlay2.c b/test/testoverlay2.c
index 617db739055c..39a4c701a60f 100644
--- a/test/testoverlay2.c
+++ b/test/testoverlay2.c
@@ -22,9 +22,8 @@
 #include <emscripten/emscripten.h>
 #endif
 
-#include <SDL3/SDL.h>
-
-#include "testyuv_cvt.h"
+#include <SDL3/SDL_test.h>
+#include <SDL3/SDL_test_common.h>
 #include "testutils.h"
 
 #define MOOSEPIC_W 64
@@ -142,47 +141,91 @@ SDL_Color MooseColors[84] = {
 };
 /* *INDENT-ON* */ /* clang-format on */
 
-Uint8 MooseFrame[MOOSEFRAMES_COUNT][MOOSEFRAME_SIZE * 2];
-SDL_Texture *MooseTexture;
+static SDLTest_CommonState *state;
+static Uint32 next_fps_check, frames;
+static const Uint32 fps_check_delay = 5000;
+
+SDL_Surface *MooseYUVSurfaces[MOOSEFRAMES_COUNT];
+SDL_Texture *MooseTexture = NULL;
 SDL_Rect displayrect;
 int window_w;
 int window_h;
-SDL_Renderer *renderer;
 int paused = 0;
-int i;
-SDL_bool done = SDL_FALSE;
+int done = 0;
 static int fpsdelay;
+SDL_bool streaming = SDL_TRUE;
+Uint8 *RawMooseData = NULL;
 
 /* Call this instead of exit(), so we can clean up SDL: atexit() is evil. */
 static void
 quit(int rc)
 {
-    SDL_Quit();
-    exit(rc);
+    int i;
+
+    /* If rc is 0, just let main return normally rather than calling exit.
+     * This allows testing of platforms where SDL_main is required and does meaningful cleanup.
+     */
+        
+    SDL_free(RawMooseData);
+
+    for (i = 0; i < MOOSEFRAMES_COUNT; i++) {
+         SDL_FreeSurface(MooseYUVSurfaces[i]);
+    }
+
+    SDLTest_CommonQuit(state);
+
+
+    if (rc != 0) {
+        exit(rc);
+    }
 }
 
-static void
-PrintUsage(char *argv0)
+void MoveSprites(SDL_Renderer *renderer)
 {
-    SDL_Log("Usage: %s [arg] [arg] [arg] ...\n", argv0);
-    SDL_Log("\n");
-    SDL_Log("Where 'arg' is any of the following options:\n");
-    SDL_Log("\n");
-    SDL_Log("    -fps <frames per second>\n");
-    SDL_Log("    -nodelay\n");
-    SDL_Log("    -format <fmt> (one of the: YV12, IYUV, YUY2, UYVY, YVYU)\n");
-    SDL_Log("    -scale <scale factor> (initial scale of the overlay)\n");
-    SDL_Log("    -help (shows this help)\n");
-    SDL_Log("\n");
-    SDL_Log("Press ESC to exit, or SPACE to freeze the movie while application running.\n");
-    SDL_Log("\n");
+    static int i = 0;
+
+    if (streaming) {
+        if (!paused) {
+            i = (i + 1) % MOOSEFRAMES_COUNT;
+            SDL_UpdateTexture(MooseTexture, NULL, MooseYUVSurfaces[i]->pixels, MooseYUVSurfaces[i]->pitch);
+        }
+        SDL_RenderClear(renderer);
+        SDL_RenderCopy(renderer, MooseTexture, NULL, &displayrect);
+        SDL_RenderPresent(renderer);
+    } else {
+        SDL_Texture *tmp;
+
+        /* Test SDL_CreateTextureFromSurface */
+        if (!paused) {
+            i = (i + 1) % MOOSEFRAMES_COUNT;
+        }
+
+        tmp = SDL_CreateTextureFromSurface(renderer, MooseYUVSurfaces[i]);
+        if (tmp == NULL) {
+            SDL_Log("Error %s", SDL_GetError());
+            quit(7);
+        }
+
+        SDL_RenderClear(renderer);
+        SDL_RenderCopy(renderer, tmp, NULL, &displayrect);
+        SDL_RenderPresent(renderer);
+        SDL_DestroyTexture(tmp);
+    }
 }
 
+
 void loop()
 {
+    Uint32 now;
+    int i;
     SDL_Event event;
+        
+    SDL_Renderer *renderer = state->renderers[0]; /* only 1 window */
 
+    /* Check for events */
     while (SDL_PollEvent(&event)) {
+        SDLTest_CommonEvent(state, &event, &done);
+
         switch (event.type) {
         case SDL_WINDOWEVENT:
             if (event.window.event == SDL_WINDOWEVENT_RESIZED) {
@@ -209,9 +252,6 @@ void loop()
             if (event.key.keysym.sym != SDLK_ESCAPE) {
                 break;
             }
-        case SDL_QUIT:
-            done = SDL_TRUE;
-            break;
         }
     }
 
@@ -219,94 +259,145 @@ void loop()
     SDL_Delay(fpsdelay);
 #endif
 
-    if (!paused) {
-        i = (i + 1) % MOOSEFRAMES_COUNT;
-
-        SDL_UpdateTexture(MooseTexture, NULL, MooseFrame[i], MOOSEPIC_W);
+    for (i = 0; i < state->num_windows; ++i) {
+        if (state->windows[i] == NULL) {
+            continue;
+        }
+        MoveSprites(state->renderers[i]);
     }
-    SDL_RenderClear(renderer);
-    SDL_RenderCopy(renderer, MooseTexture, NULL, &displayrect);
-    SDL_RenderPresent(renderer);
-
 #ifdef __EMSCRIPTEN__
     if (done) {
         emscripten_cancel_main_loop();
     }
 #endif
+
+    frames++;
+    now = SDL_GetTicks();
+    if (SDL_TICKS_PASSED(now, next_fps_check)) {
+        /* Print out some timing information */
+        const Uint32 then = next_fps_check - fps_check_delay;
+        const double fps = ((double)frames * 1000) / (now - then);
+        SDL_Log("%2.2f frames per second\n", fps);
+        next_fps_check = now + fps_check_delay;
+        frames = 0;
+    }
 }
 
+
 int main(int argc, char **argv)
 {
-    Uint8 *RawMooseData;
     SDL_RWops *handle;
-    SDL_Window *window;
+    int i;
     int j;
     int fps = 12;
     int nodelay = 0;
     int scale = 5;
     char *filename = NULL;
+    int yuv_format = SDL_PIXELFORMAT_YV12;
 
-    /* Enable standard application logging */
-    SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
-
-    if (SDL_Init(SDL_INIT_VIDEO) < 0) {
-        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s\n", SDL_GetError());
-        return 3;
+    /* Initialize test framework */
+    state = SDLTest_CommonCreateState(argv, SDL_INIT_VIDEO);
+    if (state == NULL) {
+        return 1;
     }
-
-    while (argc > 1) {
-        if (SDL_strcmp(argv[1], "-fps") == 0) {
-            if (argv[2]) {
-                fps = SDL_atoi(argv[2]);
-                if (fps == 0) {
-                    SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
-                                 "The -fps option requires an argument [from 1 to 1000], default is 12.\n");
+    
+    SDL_zeroa(MooseYUVSurfaces);
+
+    for (i = 1; i < argc;) {
+        int consumed;
+        
+        consumed = SDLTest_CommonArg(state, i);
+        if (consumed == 0) {
+            consumed = -1;
+            if (SDL_strcmp(argv[i], "--fps") == 0) {
+                if (argv[i + 1]) {
+                    consumed = 2;
+                    fps = SDL_atoi(argv[i + 1]);
+                    if (fps == 0) {
+                        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "The --fps option requires an argument [from 1 to 1000], default is 12.\n");
+                        quit(10);
+                    }
+                    if ((fps < 0) || (fps > 1000)) {
+                        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "The --fps option must be in range from 1 to 1000, default is 12.\n");
+                        quit(10);
+                    }
+                } else {
+                    SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "The --fps option requires an argument [from 1 to 1000], default is 12.\n");
                     quit(10);
                 }
-                if ((fps < 0) || (fps > 1000)) {
-                    SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
-                                 "The -fps option must be in range from 1 to 1000, default is 12.\n");
-                    quit(10);
-                }
-                argv += 2;
-                argc -= 2;
-            } else {
-                SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
-                             "The -fps option requires an argument [from 1 to 1000], default is 12.\n");
-                quit(10);
-            }
-        } else if (SDL_strcmp(argv[1], "-nodelay") == 0) {
-            nodelay = 1;
-            argv += 1;
-            argc -= 1;
-        } else if (SDL_strcmp(argv[1], "-scale") == 0) {
-            if (argv[2]) {
-                scale = SDL_atoi(argv[2]);
-                if (scale == 0) {
-                    SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
-                                 "The -scale option requires an argument [from 1 to 50], default is 5.\n");
+            } else if (SDL_strcmp(argv[i], "--nodelay") == 0) {
+                consumed = 1;
+                nodelay = 1;
+            } else if (SDL_strcmp(argv[i], "--nostreaming") == 0) {
+                consumed = 1;
+                streaming = SDL_FALSE;
+            } else if (SDL_strcmp(argv[i], "--scale") == 0) {
+                consumed = 2;
+                if (argv[i + 1]) {
+                    scale = SDL_atoi(argv[i + 1]);
+                    if (scale == 0) {
+                        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "The --scale option requires an argument [from 1 to 50], default is 5.\n");
+                        quit(10);
+                    }
+                    if ((scale < 0) || (scale > 50)) {
+                        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "The --scale option must be in range from 1 to 50, default is 5.\n");
+                        quit(10);
+                    }
+                } else {
+                    SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "The --fps option requires an argument [from 1 to 1000], default is 12.\n");
                     quit(10);
                 }
-                if ((scale < 0) || (scale > 50)) {
-                    SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
-                                 "The -scale option must be in range from 1 to 50, default is 5.\n");
+            } else if (SDL_strcmp(argv[i], "--yuvformat") == 0) {
+                consumed = 2;
+                if (argv[i + 1]) {
+                    char *fmt = argv[i + 1];
+
+                    if (SDL_strcmp(fmt, "YV12") == 0) {
+                        yuv_format = SDL_PIXELFORMAT_YV12;
+                    } else if (SDL_strcmp(fmt, "IYUV") == 0) {
+                        yuv_format = SDL_PIXELFORMAT_IYUV;
+                    } else if (SDL_strcmp(fmt, "YUY2") == 0) {
+                        yuv_format = SDL_PIXELFORMAT_YUY2;
+                    } else if (SDL_strcmp(fmt, "UYVY") == 0) {
+                        yuv_format = SDL_PIXELFORMAT_UYVY;
+                    } else if (SDL_strcmp(fmt, "YVYU") == 0) {
+                        yuv_format = SDL_PIXELFORMAT_YVYU;
+                    } else if (SDL_strcmp(fmt, "NV12") == 0) {
+                        yuv_format = SDL_PIXELFORMAT_NV12;
+                    } else if (SDL_strcmp(fmt, "NV21") == 0) {
+                        yuv_format = SDL_PIXELFORMAT_NV21;
+                    } else {
+                        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "The --yuvformat option requires one of the: YV12 (default), IYUV, YUY2, UYVY, YVYU, NV12, NV21)\n");
+                        quit(10);
+                    }
+                } else {
+                    SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "The --yuvformat option requires one of the: YV12 (default), IYUV, YUY2, UYVY, YVYU, NV12, NV21)\n");
                     quit(10);
                 }
-                argv += 2;
-                argc -= 2;
-            } else {
-                SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
-                             "The -fps option requires an argument [from 1 to 1000], default is 12.\n");
-                quit(10);
             }
-        } else if ((SDL_strcmp(argv[1], "-help") == 0) || (SDL_strcmp(argv[1], "-h") == 0)) {
-            PrintUsage(argv[0]);
-            quit(0);
-        } else {
-            SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Unrecognized option: %s.\n", argv[1]);
-            quit(10);
+
+        }
+        if (consumed < 0) {
+            static const char *options[] = {
+                "[--fps <frames per second>]",
+                "[--nodelay]",
+                "[--yuvformat <fmt>] (one of the: YV12 (default), IYUV, YUY2, UYVY, YVYU, NV12, NV21)", 
+                "[--scale <scale factor>] (initial scale of the overlay)",
+                "[--nostreaming] path that use SDL_CreateTextureFromSurface() not STREAMING texture",
+                NULL
+            };
+            SDLTest_CommonLogUsage(state, argv[0], options);
+            quit(1);
         }
-        break;
+        i += consumed;
+    }
+
+    /* Force window size */
+    state->window_w = MOOSEPIC_W * scale;
+    state->window_h = MOOSEPIC_H * scale;
+
+    if (!SDLTest_CommonInit(state)) {
+        quit(2);
     }
 
     RawMooseData = (Uint8 *)SDL_malloc(MOOSEFRAME_SIZE * MOOSEFRAMES_COUNT);
@@ -319,14 +410,12 @@ int main(int argc, char **argv)
     filename = GetResourceFilename(NULL, "moose.dat");
     if (filename == NULL) {
         SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Out of memory\n");
-        SDL_free(RawMooseData);
-        return -1;
+        quit(2);
     }
     handle = SDL_RWFromFile(filename, "rb");
     SDL_free(filename);
     if (handle == NULL) {
         SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Can't find the file moose.dat !\n");
-        SDL_free(RawMooseData);
         quit(2);
     }
 
@@ -337,52 +426,57 @@ int main(int argc, char **argv)
     /* Create the window and renderer */
     window_w = MOOSEPIC_W * scale;
     window_h = MOOSEPIC_H * scale;
-    window = SDL_CreateWindow("Happy Moose",
-                              SDL_WINDOWPOS_UNDEFINED,
-                              SDL_WINDOWPOS_UNDEFINED,
-                              window_w, window_h,
-                              SDL_WINDOW_RESIZABLE);
-    if (window == NULL) {
-        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't set create window: %s\n", SDL_GetError());
-        SDL_free(RawMooseData);
-        quit(4);
-    }
 
-    renderer = SDL_CreateRenderer(window, -1, 0);
-    if (renderer == NULL) {
-        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't set create renderer: %s\n", SDL_GetError());
-        SDL_free(RawMooseData);
-        quit(4);
+    if (state->num_windows != 1) {
+        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Only one window allowed\n");
+        quit(1);
     }
 
-    MooseTexture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_YV12, SDL_TEXTUREACCESS_STREAMING, MOOSEPIC_W, MOOSEPIC_H);
-    if (MooseTexture == NULL) {
-        SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't set create texture: %s\n", SDL_GetError());
-        SDL_free(RawMooseData);
-        quit(5);
+    for (i = 0; i < state->num_windows; ++i) {
+        SDL_Renderer *renderer = state->renderers[i];
+
+        if (streaming) {
+            MooseTexture = SDL_CreateTexture(renderer, yuv_format, SDL_TEXTUREACCESS_STREAMING, MOOSEPIC_W, MOOSEPIC_H);
+            if (MooseTexture == NULL) {
+                SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't set create texture: %s\n", SDL_GetError());
+                quit(5);
+            }
+        }
     }
+
     /* Uncomment this to check vertex color with a YUV texture */
     /* SDL_SetTextureColorMod(MooseTexture, 0xff, 0x80, 0x80); */
 
     for (i = 0; i < MOOSEFRAMES_COUNT; i++) {
-        Uint8 MooseFrameRGB[MOOSEFRAME_SIZE * 3];
-        Uint8 *rgb;
-        Uint8 *frame;
-
-        rgb = MooseFrameRGB;
-        frame = RawMooseData + i * MOOSEFRAME_SIZE;
-        for (j = 0; j < MOOSEFRAME_SIZE; ++j) {
-            rgb[0] = MooseColors[frame[j]].r;
-            rgb[1] = MooseColors[frame[j]].g;
-            rgb[2] = MooseColors[frame[j]].b;
-            rgb += 3;
+        /* Create RGB SDL_Surface */
+        SDL_Surface *mooseRGBSurface = SDL_CreateSurface(MOOSEPIC_W, MOOSEPIC_H, SDL_PIXELFORMAT_RGB24);
+        if (mooseRGBSurface == NULL) {
+            quit(6);
         }
-        ConvertRGBtoYUV(SDL_PIXELFORMAT_YV12, MooseFrameRGB, MOOSEPIC_W * 3, MooseFrame[i], MOOSEPIC_W, MOOSEPIC_H,
-                        SDL_GetYUVConversionModeForResolution(MOOSEPIC_W, MOOSEPIC_H),
-                        0, 100);
+
+        /* Load Moose into a RGB SDL_Surface */
+        {
+            Uint8 *rgb = mooseRGBSurface->pixels;
+            Uint8 *frame = RawMooseData + i * MOOSEFRAME_SIZE;
+            for (j = 0; j < MOOSEFRAME_SIZE; ++j) {
+                rgb[0] = MooseColors[frame[j]].r;
+                rgb[1] = MooseColors[frame[j]].g;
+                rgb[2] = MooseColors[frame[j]].b;
+                rgb += 3;
+            }
+        }
+
+        /* Convert to YUV SDL_Surface */
+        MooseYUVSurfaces[i] = SDL_ConvertSurfaceFormat(mooseRGBSurface, yuv_format);
+        if (MooseYUVSurfaces[i] == NULL) {
+            quit(7);
+        }
+
+        SDL_FreeSurface(mooseRGBSurface);
     }
 
     SDL_free(RawMooseData);
+    RawMooseData = NULL;
 
     /* set the start frame */
     i = 0;
@@ -400,6 +494,11 @@ int main(int argc, char **argv)
     /* Ignore key up events, they don't even get filtered */
     SDL_EventState(SDL_KEYUP, SDL_IGNORE);
 
+    /* Main render loop */
+    frames = 0;
+    next_fps_check = SDL_GetTicks() + fps_check_delay;
+    done = 0;
+
     /* Loop, waiting for QUIT or RESIZE */
 #ifdef __EMSCRIPTEN__
     emscripten_set_main_loop(loop, nodelay ? 0 : fps, 1);
@@ -409,7 +508,6 @@ int main(int argc, char **argv)
     }
 #endif
 
-    SDL_DestroyRenderer(renderer);
     quit(0);
     return 0;
 }