SDL_stb.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. /*
  2. Simple DirectMedia Layer
  3. Copyright (C) 1997-2026 Sam Lantinga <slouken@libsdl.org>
  4. This software is provided 'as-is', without any express or implied
  5. warranty. In no event will the authors be held liable for any damages
  6. arising from the use of this software.
  7. Permission is granted to anyone to use this software for any purpose,
  8. including commercial applications, and to alter it and redistribute it
  9. freely, subject to the following restrictions:
  10. 1. The origin of this software must not be misrepresented; you must not
  11. claim that you wrote the original software. If you use this software
  12. in a product, an acknowledgment in the product documentation would be
  13. appreciated but is not required.
  14. 2. Altered source versions must be plainly marked as such, and must not be
  15. misrepresented as being the original software.
  16. 3. This notice may not be removed or altered from any source distribution.
  17. */
  18. #include "SDL_internal.h"
  19. #include "SDL_stb_c.h"
  20. #include "SDL_surface_c.h"
  21. #ifdef SDL_HAVE_STB
  22. ////////////////////////////////////////////////////////////////////////////
  23. #define malloc SDL_malloc
  24. #define realloc SDL_realloc
  25. #define free SDL_free
  26. #undef memcpy
  27. #define memcpy SDL_memcpy
  28. #undef memset
  29. #define memset SDL_memset
  30. #undef strcmp
  31. #define strcmp SDL_strcmp
  32. #undef strncmp
  33. #define strncmp SDL_strncmp
  34. #define strtol SDL_strtol
  35. #define abs SDL_abs
  36. #define pow SDL_pow
  37. #define ldexp SDL_scalbn
  38. #define STB_IMAGE_STATIC
  39. #define STBI_NO_THREAD_LOCALS
  40. #define STBI_FAILURE_USERMSG
  41. #if defined(SDL_NEON_INTRINSICS)
  42. #define STBI_NEON
  43. #endif
  44. #define STBI_ONLY_PNG
  45. #define STBI_ONLY_JPEG
  46. #define STBI_NO_GIF
  47. #define STBI_NO_HDR
  48. #define STBI_NO_LINEAR
  49. #define STBI_NO_STDIO
  50. #define STBI_ASSERT SDL_assert
  51. #define STB_IMAGE_IMPLEMENTATION
  52. #include "stb_image.h"
  53. ////////////////////////////////////////////////////////////////////////////
  54. #define MZ_ASSERT(x) SDL_assert(x)
  55. //#undef memcpy
  56. //#define memcpy SDL_memcpy
  57. //#undef memset
  58. //#define memset SDL_memset
  59. #if SDL_BYTEORDER == SDL_LIL_ENDIAN
  60. #define MINIZ_LITTLE_ENDIAN 1
  61. #else
  62. #define MINIZ_LITTLE_ENDIAN 0
  63. #endif
  64. #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 0
  65. #define MINIZ_SDL_NOUNUSED
  66. #include "miniz.h"
  67. #undef memset
  68. #endif // SDL_HAVE_STB
  69. #ifdef SDL_HAVE_STB
  70. static bool SDL_ConvertPixels_MJPG_to_NV12(int width, int height, const void *src, int src_pitch, void *dst, int dst_pitch)
  71. {
  72. int w = 0, h = 0, format = 0;
  73. stbi__context s;
  74. stbi__start_mem(&s, src, src_pitch);
  75. stbi__result_info ri;
  76. SDL_zero(ri);
  77. ri.bits_per_channel = 8;
  78. ri.channel_order = STBI_ORDER_RGB;
  79. ri.num_channels = 0;
  80. stbi__nv12 nv12;
  81. nv12.w = width;
  82. nv12.h = height;
  83. nv12.pitch = dst_pitch;
  84. nv12.y = (stbi_uc *)dst;
  85. nv12.uv = nv12.y + (nv12.h * nv12.pitch);
  86. void *pixels = stbi__jpeg_load(&s, &w, &h, &format, 4, &nv12, &ri);
  87. if (!pixels) {
  88. return false;
  89. }
  90. return true;
  91. }
  92. #endif // SDL_HAVE_STB
  93. bool SDL_ConvertPixels_STB(int width, int height,
  94. SDL_PixelFormat src_format, SDL_Colorspace src_colorspace, SDL_PropertiesID src_properties, const void *src, int src_pitch,
  95. SDL_PixelFormat dst_format, SDL_Colorspace dst_colorspace, SDL_PropertiesID dst_properties, void *dst, int dst_pitch)
  96. {
  97. #ifdef SDL_HAVE_STB
  98. if (src_format == SDL_PIXELFORMAT_MJPG && dst_format == SDL_PIXELFORMAT_NV12) {
  99. return SDL_ConvertPixels_MJPG_to_NV12(width, height, src, src_pitch, dst, dst_pitch);
  100. }
  101. bool result;
  102. int w = 0, h = 0, format = 0;
  103. int len = (src_format == SDL_PIXELFORMAT_MJPG) ? src_pitch : (height * src_pitch);
  104. void *pixels = stbi_load_from_memory(src, len, &w, &h, &format, 4);
  105. if (!pixels) {
  106. return false;
  107. }
  108. if (w == width && h == height) {
  109. result = SDL_ConvertPixelsAndColorspace(w, h, SDL_PIXELFORMAT_RGBA32, SDL_COLORSPACE_SRGB, 0, pixels, width * 4, dst_format, dst_colorspace, dst_properties, dst, dst_pitch);
  110. } else {
  111. result = SDL_SetError("Expected image size %dx%d, actual size %dx%d", width, height, w, h);
  112. }
  113. stbi_image_free(pixels);
  114. return result;
  115. #else
  116. return SDL_SetError("SDL not built with STB image support");
  117. #endif
  118. }
  119. #ifdef SDL_HAVE_STB
  120. static int IMG_LoadSTB_IO_read(void *user, char *data, int size)
  121. {
  122. size_t amount = SDL_ReadIO((SDL_IOStream*)user, data, size);
  123. return (int)amount;
  124. }
  125. static void IMG_LoadSTB_IO_skip(void *user, int n)
  126. {
  127. SDL_SeekIO((SDL_IOStream*)user, n, SDL_IO_SEEK_CUR);
  128. }
  129. static int IMG_LoadSTB_IO_eof(void *user)
  130. {
  131. SDL_IOStream *src = (SDL_IOStream*)user;
  132. return SDL_GetIOStatus(src) == SDL_IO_STATUS_EOF;
  133. }
  134. static SDL_Surface *SDL_LoadSTB_IO(SDL_IOStream *src)
  135. {
  136. Sint64 start;
  137. Uint8 magic[26];
  138. int w, h, format;
  139. stbi_uc *pixels;
  140. stbi_io_callbacks rw_callbacks;
  141. SDL_Surface *surface = NULL;
  142. bool use_palette = false;
  143. unsigned int palette_colors[256];
  144. // src has already been validated
  145. start = SDL_TellIO(src);
  146. if (SDL_ReadIO(src, magic, sizeof(magic)) == sizeof(magic)) {
  147. const Uint8 PNG_COLOR_INDEXED = 3;
  148. if (magic[0] == 0x89 &&
  149. magic[1] == 'P' &&
  150. magic[2] == 'N' &&
  151. magic[3] == 'G' &&
  152. magic[12] == 'I' &&
  153. magic[13] == 'H' &&
  154. magic[14] == 'D' &&
  155. magic[15] == 'R' &&
  156. magic[25] == PNG_COLOR_INDEXED) {
  157. use_palette = true;
  158. }
  159. }
  160. SDL_SeekIO(src, start, SDL_IO_SEEK_SET);
  161. /* Load the image data */
  162. rw_callbacks.read = IMG_LoadSTB_IO_read;
  163. rw_callbacks.skip = IMG_LoadSTB_IO_skip;
  164. rw_callbacks.eof = IMG_LoadSTB_IO_eof;
  165. w = h = format = 0; /* silence warning */
  166. if (use_palette) {
  167. /* Unused palette entries will be opaque white */
  168. SDL_memset(palette_colors, 0xff, sizeof(palette_colors));
  169. pixels = stbi_load_from_callbacks_with_palette(
  170. &rw_callbacks,
  171. src,
  172. &w,
  173. &h,
  174. palette_colors,
  175. SDL_arraysize(palette_colors)
  176. );
  177. } else {
  178. pixels = stbi_load_from_callbacks(
  179. &rw_callbacks,
  180. src,
  181. &w,
  182. &h,
  183. &format,
  184. STBI_default
  185. );
  186. }
  187. if (!pixels) {
  188. SDL_SeekIO(src, start, SDL_IO_SEEK_SET);
  189. return NULL;
  190. }
  191. if (use_palette) {
  192. surface = SDL_CreateSurfaceFrom(
  193. w,
  194. h,
  195. SDL_PIXELFORMAT_INDEX8,
  196. pixels,
  197. w
  198. );
  199. if (surface) {
  200. bool has_colorkey = false;
  201. int colorkey_index = -1;
  202. bool has_alpha = false;
  203. SDL_Palette *palette = SDL_CreateSurfacePalette(surface);
  204. if (palette) {
  205. int i;
  206. Uint8 *palette_bytes = (Uint8 *)palette_colors;
  207. for (i = 0; i < palette->ncolors; i++) {
  208. palette->colors[i].r = *palette_bytes++;
  209. palette->colors[i].g = *palette_bytes++;
  210. palette->colors[i].b = *palette_bytes++;
  211. palette->colors[i].a = *palette_bytes++;
  212. if (palette->colors[i].a != SDL_ALPHA_OPAQUE) {
  213. if (palette->colors[i].a == SDL_ALPHA_TRANSPARENT && !has_colorkey) {
  214. has_colorkey = true;
  215. colorkey_index = i;
  216. } else {
  217. /* Partial opacity or multiple colorkeys */
  218. has_alpha = true;
  219. }
  220. }
  221. }
  222. }
  223. if (has_alpha) {
  224. SDL_SetSurfaceBlendMode(surface, SDL_BLENDMODE_BLEND);
  225. } else if (has_colorkey) {
  226. SDL_SetSurfaceColorKey(surface, true, colorkey_index);
  227. }
  228. /* FIXME: This sucks. It'd be better to allocate the surface first, then
  229. * write directly to the pixel buffer:
  230. * https://github.com/nothings/stb/issues/58
  231. * -flibit
  232. */
  233. surface->flags &= ~SDL_SURFACE_PREALLOCATED;
  234. }
  235. } else if (format == STBI_grey || format == STBI_rgb || format == STBI_rgb_alpha) {
  236. surface = SDL_CreateSurfaceFrom(
  237. w,
  238. h,
  239. (format == STBI_rgb_alpha) ? SDL_PIXELFORMAT_RGBA32 :
  240. (format == STBI_rgb) ? SDL_PIXELFORMAT_RGB24 :
  241. SDL_PIXELFORMAT_INDEX8,
  242. pixels,
  243. w * format
  244. );
  245. if (surface) {
  246. /* Set a grayscale palette for gray images */
  247. if (surface->format == SDL_PIXELFORMAT_INDEX8) {
  248. SDL_Palette *palette = SDL_CreateSurfacePalette(surface);
  249. if (palette) {
  250. int i;
  251. for (i = 0; i < palette->ncolors; i++) {
  252. palette->colors[i].r = (Uint8)i;
  253. palette->colors[i].g = (Uint8)i;
  254. palette->colors[i].b = (Uint8)i;
  255. }
  256. }
  257. }
  258. /* FIXME: This sucks. It'd be better to allocate the surface first, then
  259. * write directly to the pixel buffer:
  260. * https://github.com/nothings/stb/issues/58
  261. * -flibit
  262. */
  263. surface->flags &= ~SDL_SURFACE_PREALLOCATED;
  264. }
  265. } else if (format == STBI_grey_alpha) {
  266. surface = SDL_CreateSurface(w, h, SDL_PIXELFORMAT_RGBA32);
  267. if (surface) {
  268. Uint8 *src_ptr = pixels;
  269. Uint8 *dst = (Uint8 *)surface->pixels;
  270. int skip = surface->pitch - (surface->w * 4);
  271. int row, col;
  272. for (row = 0; row < h; ++row) {
  273. for (col = 0; col < w; ++col) {
  274. Uint8 c = *src_ptr++;
  275. Uint8 a = *src_ptr++;
  276. *dst++ = c;
  277. *dst++ = c;
  278. *dst++ = c;
  279. *dst++ = a;
  280. }
  281. dst += skip;
  282. }
  283. stbi_image_free(pixels);
  284. }
  285. } else {
  286. SDL_SetError("Unknown image format: %d", format);
  287. }
  288. if (!surface) {
  289. /* The error message should already be set */
  290. stbi_image_free(pixels); /* calls SDL_free() */
  291. SDL_SeekIO(src, start, SDL_IO_SEEK_SET);
  292. }
  293. return surface;
  294. }
  295. #endif // SDL_HAVE_STB
  296. bool SDL_IsPNG(SDL_IOStream *src)
  297. {
  298. Sint64 start;
  299. Uint8 magic[4];
  300. bool is_PNG;
  301. is_PNG = false;
  302. start = SDL_TellIO(src);
  303. if (start >= 0) {
  304. if (SDL_ReadIO(src, magic, sizeof(magic)) == sizeof(magic)) {
  305. if (magic[0] == 0x89 &&
  306. magic[1] == 'P' &&
  307. magic[2] == 'N' &&
  308. magic[3] == 'G') {
  309. is_PNG = true;
  310. }
  311. }
  312. SDL_SeekIO(src, start, SDL_IO_SEEK_SET);
  313. }
  314. return is_PNG;
  315. }
  316. SDL_Surface *SDL_LoadPNG_IO(SDL_IOStream *src, bool closeio)
  317. {
  318. SDL_Surface *surface = NULL;
  319. CHECK_PARAM(!src) {
  320. SDL_InvalidParamError("src");
  321. goto done;
  322. }
  323. if (!SDL_IsPNG(src)) {
  324. SDL_SetError("File is not a PNG file");
  325. goto done;
  326. }
  327. #ifdef SDL_HAVE_STB
  328. surface = SDL_LoadSTB_IO(src);
  329. #else
  330. SDL_SetError("SDL not built with STB image support");
  331. #endif // SDL_HAVE_STB
  332. done:
  333. if (src && closeio) {
  334. SDL_CloseIO(src);
  335. }
  336. return surface;
  337. }
  338. SDL_Surface *SDL_LoadPNG(const char *file)
  339. {
  340. SDL_IOStream *stream = SDL_IOFromFile(file, "rb");
  341. if (!stream) {
  342. return NULL;
  343. }
  344. return SDL_LoadPNG_IO(stream, true);
  345. }
  346. bool SDL_SavePNG_IO(SDL_Surface *surface, SDL_IOStream *dst, bool closeio)
  347. {
  348. bool retval = false;
  349. Uint8 *plte = NULL;
  350. Uint8 *trns = NULL;
  351. bool free_surface = false;
  352. // Make sure we have something to save
  353. CHECK_PARAM(!SDL_SurfaceValid(surface)) {
  354. SDL_InvalidParamError("surface");
  355. goto done;
  356. }
  357. CHECK_PARAM(!dst) {
  358. SDL_InvalidParamError("dst");
  359. goto done;
  360. }
  361. #ifdef SDL_HAVE_STB
  362. int plte_size = 0;
  363. int trns_size = 0;
  364. if (SDL_ISPIXELFORMAT_INDEXED(surface->format)) {
  365. if (!surface->palette) {
  366. SDL_SetError("Indexed surfaces must have a palette");
  367. goto done;
  368. }
  369. if (surface->format != SDL_PIXELFORMAT_INDEX8) {
  370. surface = SDL_ConvertSurface(surface, SDL_PIXELFORMAT_INDEX8);
  371. if (!surface) {
  372. goto done;
  373. }
  374. free_surface = true;
  375. }
  376. plte_size = surface->palette->ncolors * 3;
  377. trns_size = surface->palette->ncolors;
  378. plte = (Uint8 *)SDL_malloc(plte_size);
  379. trns = (Uint8 *)SDL_malloc(trns_size);
  380. if (!plte || !trns) {
  381. goto done;
  382. }
  383. SDL_Color *colors = surface->palette->colors;
  384. for (int i = 0; i < surface->palette->ncolors; ++i) {
  385. plte[i * 3 + 0] = colors[i].r;
  386. plte[i * 3 + 1] = colors[i].g;
  387. plte[i * 3 + 2] = colors[i].b;
  388. trns[i] = colors[i].a;
  389. }
  390. } else {
  391. if (surface->format != SDL_PIXELFORMAT_RGBA32) {
  392. surface = SDL_ConvertSurface(surface, SDL_PIXELFORMAT_RGBA32);
  393. if (!surface) {
  394. goto done;
  395. }
  396. free_surface = true;
  397. }
  398. }
  399. size_t size = 0;
  400. void *png = tdefl_write_image_to_png_file_in_memory_ex(surface->pixels, surface->w, surface->h, SDL_BYTESPERPIXEL(surface->format), surface->pitch, &size, 6, MZ_FALSE, plte, plte_size, trns, trns_size);
  401. if (png) {
  402. if (SDL_WriteIO(dst, png, size)) {
  403. retval = true;
  404. }
  405. mz_free(png); /* calls SDL_free() */
  406. } else {
  407. SDL_SetError("Failed to convert and save image");
  408. }
  409. #else
  410. SDL_SetError("SDL not built with STB image support");
  411. #endif
  412. done:
  413. if (free_surface) {
  414. SDL_DestroySurface(surface);
  415. }
  416. SDL_free(plte);
  417. SDL_free(trns);
  418. if (dst && closeio) {
  419. retval &= SDL_CloseIO(dst);
  420. }
  421. return retval;
  422. }
  423. bool SDL_SavePNG(SDL_Surface *surface, const char *file)
  424. {
  425. #ifdef SDL_HAVE_STB
  426. // Make sure we have something to save
  427. CHECK_PARAM(!SDL_SurfaceValid(surface)) {
  428. return SDL_InvalidParamError("surface");
  429. }
  430. if (SDL_ISPIXELFORMAT_INDEXED(surface->format) && !surface->palette) {
  431. return SDL_SetError("Indexed surfaces must have a palette");
  432. }
  433. SDL_IOStream *stream = SDL_IOFromFile(file, "wb");
  434. if (!stream) {
  435. return false;
  436. }
  437. return SDL_SavePNG_IO(surface, stream, true);
  438. #else
  439. return SDL_SetError("SDL not built with STB image support");
  440. #endif
  441. }