### Build libspng Documentation with MkDocs Source: https://github.com/randy408/libspng/blob/master/docs/build.md Command to build the documentation for libspng using MkDocs. This assumes MkDocs is installed and configured. ```bash # Run in root directory mkdocs build ``` -------------------------------- ### Build libspng with Meson Source: https://github.com/randy408/libspng/blob/master/docs/build.md Meson build system instructions for libspng. This includes configuring the build with specific types (e.g., release), navigating to the build directory, and using ninja to compile and install. ```bash meson build --buildtype=release # Default is debug cd build ninja ninja install ``` -------------------------------- ### CMake Package and Installation Configuration Source: https://github.com/randy408/libspng/blob/master/CMakeLists.txt This CMake script configures package discovery files (Config.cmake and ConfigVersion.cmake) and defines installation rules for targets, headers, and package configuration files. It ensures that the built library and its associated CMake configuration are correctly installed for external projects to find. ```cmake find_package(ZLIB REQUIRED) foreach(spng_TARGET ${spng_TARGETS}) target_include_directories(${spng_TARGET} PUBLIC $ $ ) target_link_libraries(${spng_TARGET} PRIVATE ZLIB::ZLIB) target_link_libraries(${spng_TARGET} PRIVATE ${MATH_LIBRARY}) endforeach() set(project_config "${CMAKE_CURRENT_BINARY_DIR}/SPNGConfig.cmake") set(project_version_config "${CMAKE_CURRENT_BINARY_DIR}/SPNGConfigVersion.cmake") set(targets_export_name SPNGTargets) set(config_install_dir "${CMAKE_INSTALL_LIBDIR}/cmake/spng") configure_package_config_file(cmake/Config.cmake.in ${project_config} INSTALL_DESTINATION ${config_install_dir} ) write_basic_package_version_file(${project_version_config} VERSION ${SPNG_VERSION} COMPATIBILITY SameMajorVersion ) install( TARGETS ${spng_TARGETS} EXPORT ${targets_export_name} ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR} ) install(FILES spng/spng.h DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}) install( FILES ${project_config} ${project_version_config} DESTINATION ${config_install_dir} ) install( EXPORT ${targets_export_name} NAMESPACE "spng::" DESTINATION ${config_install_dir} ) ``` -------------------------------- ### Build libspng with Profile-Guided Optimization (PGO) Source: https://github.com/randy408/libspng/blob/master/docs/build.md Instructions for enabling profile-guided optimization (PGO) in libspng using Meson. This process involves generating PGO data by running examples and then recompiling with the generated data to improve performance. ```bash # Run in root directory git clone https://github.com/libspng/benchmark_images.git cd build meson configure -Dbuildtype=release --default-library both -Db_pgo=generate ninja ./example ../benchmark_images/medium_rgb8.png ./example ../benchmark_images/medium_rgba8.png ./example ../benchmark_images/large_palette.png meson configure -Db_pgo=use ninja ninja install ``` -------------------------------- ### Clone and Set Up Upstream Repository Source: https://github.com/randy408/libspng/blob/master/CONTRIBUTING.md This snippet shows how to clone the libspng repository from GitHub and set up the upstream remote for future updates. It assumes you have Git installed. ```bash git clone https://github.com/username/libspng.git cd libspng git remote add upstream https://github.com/randy408/libspng.git ``` -------------------------------- ### Run Clang Static Analyzer Source: https://github.com/randy408/libspng/blob/master/CONTRIBUTING.md This command executes the Clang Static Analyzer on the project to identify potential bugs and code quality issues. It assumes the build directory is active and ninja is installed. ```bash ninja scan-build ``` -------------------------------- ### Build libspng with CMake Source: https://github.com/randy408/libspng/blob/master/docs/build.md Standard CMake build process for libspng. This involves creating a build directory, configuring the build with CMake, compiling the project, and installing the library. ```bash mkdir cbuild cd cbuild cmake .. # Don't forget to set optimization level! make make install ``` -------------------------------- ### CMake pkg-config File Generation and Installation Source: https://github.com/randy408/libspng/blob/master/CMakeLists.txt This CMake code generates and installs pkg-config files for the libspng library, enabling easier integration with other build systems. It conditionally executes this logic for non-Windows systems and defines installation paths for the .pc files. ```cmake if(NOT CMAKE_HOST_WIN32 OR CYGWIN OR MINGW) set(prefix ${CMAKE_INSTALL_PREFIX}) set(exec_prefix ${CMAKE_INSTALL_PREFIX}) set(libdir ${CMAKE_INSTALL_FULL_LIBDIR}) set(includedir ${CMAKE_INSTALL_FULL_INCLUDEDIR}) set(LIBS "-lm") foreach(libname ${spng_TARGETS}) configure_file(${CMAKE_CURRENT_SOURCE_DIR}/cmake/libspng.pc.in ${CMAKE_CURRENT_BINARY_DIR}/cmake/lib${libname}.pc @ONLY) install(FILES ${CMAKE_CURRENT_BINARY_DIR}/cmake/lib${libname}.pc DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig) endforeach() endif() ``` -------------------------------- ### CMake Build Configuration for libspng Source: https://github.com/randy408/libspng/blob/master/CMakeLists.txt This snippet defines the core CMake build settings for the libspng project. It sets the minimum CMake version, project name, C standard, version information, and configurable build options like shared/static libraries, optimizations, and examples. It also includes necessary CMake modules for installation and package configuration. ```cmake cmake_minimum_required(VERSION 3.12) project(libspng C) set(CMAKE_C_STANDARD 99) set(SPNG_MAJOR 0) set(SPNG_MINOR 7) set(SPNG_REVISION 4) set(SPNG_VERSION ${SPNG_MAJOR}.${SPNG_MINOR}.${SPNG_REVISION}) option(ENABLE_OPT "Enable architecture-specific optimizations" ON) option(SPNG_SHARED "Build shared lib" ON) option(SPNG_STATIC "Build static lib" ON) option(BUILD_EXAMPLES "Build examples" ON) include(GNUInstallDirs) include(CMakePackageConfigHelpers) ``` -------------------------------- ### Get and Set PNG Color Palette (PLTE) using C Source: https://context7.com/randy408/libspng/llms.txt Demonstrates how to retrieve an image's color palette using spng_get_plte and how to create an indexed color PNG with a custom palette using spng_set_plte. Handles cases where no palette is present. ```c #include int read_palette(spng_ctx *ctx) { struct spng_plte plte; int ret = spng_get_plte(ctx, &plte); if (ret == SPNG_ECHUNKAVAIL) { printf("No palette in this image\n"); return 0; } if (ret) return ret; printf("Palette has %u entries:\n", plte.n_entries); for (uint32_t i = 0; i < plte.n_entries && i < 8; i++) { printf(" [%u] RGB: %u, %u, %u\n", i, plte.entries[i].red, plte.entries[i].green, plte.entries[i].blue); } if (plte.n_entries > 8) printf(" ... and %u more\n", plte.n_entries - 8); return 0; } int create_indexed_png(void) { spng_ctx *ctx = spng_ctx_new(SPNG_CTX_ENCODER); spng_set_option(ctx, SPNG_ENCODE_TO_BUFFER, 1); /* Set up indexed color image */ struct spng_ihdr ihdr = { .width = 16, .height = 16, .bit_depth = 8, .color_type = SPNG_COLOR_TYPE_INDEXED }; spng_set_ihdr(ctx, &ihdr); /* Create a simple 4-color palette */ struct spng_plte plte = { .n_entries = 4 }; plte.entries[0] = (struct spng_plte_entry){255, 0, 0}; /* Red */ plte.entries[1] = (struct spng_plte_entry){0, 255, 0}; /* Green */ plte.entries[2] = (struct spng_plte_entry){0, 0, 255}; /* Blue */ plte.entries[3] = (struct spng_plte_entry){255, 255, 255}; /* White */ spng_set_plte(ctx, &plte); /* Create image with palette indices */ unsigned char image[256]; /* 16x16 = 256 pixels */ for (int i = 0; i < 256; i++) { image[i] = i % 4; /* Cycle through palette colors */ } spng_encode_image(ctx, image, sizeof(image), SPNG_FMT_PNG, SPNG_ENCODE_FINALIZE); size_t size; int error; void *png = spng_get_png_buffer(ctx, &size, &error); if (png) { printf("Created indexed PNG: %zu bytes\n", size); free(png); } spng_ctx_free(ctx); return 0; } ``` -------------------------------- ### Palette (PLTE) Handling Source: https://context7.com/randy408/libspng/llms.txt Functions to get and set the color palette for indexed color PNG images. ```APIDOC ## spng_get_plte / spng_set_plte ### Description Gets or sets the color palette for indexed color images (PLTE chunk). ### Method - `spng_get_plte`: GET - `spng_set_plte`: POST ### Endpoint - `spng_get_plte`: N/A (Function call) - `spng_set_plte`: N/A (Function call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body (for spng_set_plte) - **plte** (struct spng_plte*) - Required - Pointer to a structure containing palette information. - **n_entries** (uint32_t) - Number of entries in the palette. - **entries** (struct spng_plte_entry[n_entries]) - Array of palette entries. - **red** (uint8_t) - Red component (0-255). - **green** (uint8_t) - Green component (0-255). - **blue** (uint8_t) - Blue component (0-255). ### Request Example (Conceptual for spng_set_plte) ```c struct spng_plte plte = { .n_entries = 4 }; plte.entries[0] = (struct spng_plte_entry){255, 0, 0}; /* Red */ plte.entries[1] = (struct spng_plte_entry){0, 255, 0}; /* Green */ plte.entries[2] = (struct spng_plte_entry){0, 0, 255}; /* Blue */ plte.entries[3] = (struct spng_plte_entry){255, 255, 255}; /* White */ spng_set_plte(ctx, &plte); ``` ### Response #### Success Response (0) - **spng_get_plte**: Returns 0 on success. SPNG_ECHUNKAVAIL if no PLTE chunk is present. - **spng_set_plte**: Returns 0 on success. #### Response Example (Conceptual for spng_get_plte) ```json { "n_entries": 4, "entries": [ {"red": 255, "green": 0, "blue": 0}, {"red": 0, "green": 255, "blue": 0}, {"red": 0, "green": 0, "blue": 255}, {"red": 255, "green": 255, "blue": 255} ] } ``` ``` -------------------------------- ### Decode and Re-encode PNG Image with libspng Source: https://context7.com/randy408/libspng/llms.txt A comprehensive C example showcasing the full workflow of decoding a PNG image and then re-encoding it using libspng. It includes setting security limits, handling different image formats, error checking, and proper resource management with goto cleanup. ```c #include #include #include int decode_and_reencode(const char *input_file, const char *output_file) { FILE *in = NULL, *out = NULL; spng_ctx *decoder = NULL, *encoder = NULL; unsigned char *image = NULL; int ret = 0; /* Open input file */ in = fopen(input_file, "rb"); if (!in) { printf("Cannot open input: %s\n", input_file); return -1; } /* Create decoder */ decoder = spng_ctx_new(0); if (!decoder) { printf("Failed to create decoder context\n"); ret = -1; goto cleanup; } /* Security limits for untrusted files */ spng_set_image_limits(decoder, 8192, 8192); spng_set_chunk_limits(decoder, 16 * 1024 * 1024, 64 * 1024 * 1024); /* Set input */ ret = spng_set_png_file(decoder, in); if (ret) { printf("spng_set_png_file error: %s\n", spng_strerror(ret)); goto cleanup; } /* Read header */ struct spng_ihdr ihdr; ret = spng_get_ihdr(decoder, &ihdr); if (ret) { printf("spng_get_ihdr error: %s\n", spng_strerror(ret)); goto cleanup; } printf("Input: %ux%u, %u-bit, color type %u\n", ihdr.width, ihdr.height, ihdr.bit_depth, ihdr.color_type); /* Calculate and allocate output buffer */ size_t image_size; ret = spng_decoded_image_size(decoder, SPNG_FMT_RGBA8, &image_size); if (ret) { printf("spng_decoded_image_size error: %s\n", spng_strerror(ret)); goto cleanup; } image = malloc(image_size); if (!image) { printf("Failed to allocate %zu bytes\n", image_size); ret = -1; goto cleanup; } /* Decode with transparency and gamma correction */ ret = spng_decode_image(decoder, image, image_size, SPNG_FMT_RGBA8, SPNG_DECODE_TRNS | SPNG_DECODE_GAMMA); if (ret) { printf("spng_decode_image error: %s\n", spng_strerror(ret)); goto cleanup; } printf("Decoded %zu bytes\n", image_size); /* Create encoder */ encoder = spng_ctx_new(SPNG_CTX_ENCODER); if (!encoder) { printf("Failed to create encoder context\n"); ret = -1; goto cleanup; } /* Open output file */ out = fopen(output_file, "wb"); if (!out) { printf("Cannot open output: %s\n", output_file); ret = -1; goto cleanup; } spng_set_png_file(encoder, out); /* Configure encoder for 8-bit RGBA output */ struct spng_ihdr out_ihdr = { .width = ihdr.width, .height = ihdr.height, .bit_depth = 8, .color_type = SPNG_COLOR_TYPE_TRUECOLOR_ALPHA }; ret = spng_set_ihdr(encoder, &out_ihdr); if (ret) { printf("spng_set_ihdr error: %s\n", spng_strerror(ret)); goto cleanup; } /* Fast encoding settings */ spng_set_option(encoder, SPNG_IMG_COMPRESSION_LEVEL, 3); /* Encode */ ret = spng_encode_image(encoder, image, image_size, SPNG_FMT_PNG, SPNG_ENCODE_FINALIZE); if (ret) { printf("spng_encode_image error: %s\n", spng_strerror(ret)); goto cleanup; } printf("Successfully encoded to: %s\n", output_file); ret = 0; cleanup: free(image); spng_ctx_free(decoder); spng_ctx_free(encoder); if (in) fclose(in); if (out) fclose(out); return ret; } int main(int argc, char **argv) { if (argc != 3) { printf("Usage: %s \n", argv[0]); return 1; } return decode_and_reencode(argv[1], argv[2]); } ``` -------------------------------- ### Decode PNG Image to RGBA8 Format using C Source: https://github.com/randy408/libspng/blob/master/docs/usage.md This C code snippet demonstrates the basic workflow for decoding a PNG image using the libspng library. It involves creating a context, setting the input PNG data, calculating the required output buffer size for an 8-bit RGBA format, decoding the image into that format, and finally freeing the context. This example assumes the input PNG data is available in a buffer `buf` of size `buf_size` and the decoded output will be stored in `out`. ```c #include /* Create a context */ spng_ctx *ctx = spng_ctx_new(0); /* Set an input buffer */ spng_set_png_buffer(ctx, buf, buf_size); /* Calculate output image size */ spng_decoded_image_size(ctx, SPNG_FMT_RGBA8, &out_size); /* Get an 8-bit RGBA image regardless of PNG format */ spng_decode_image(ctx, SPNG_FMT_RGBA8, out, out_size, 0); /* Free context memory */ spng_ctx_free(ctx); ``` -------------------------------- ### Get Image Width and Height Limits (C) Source: https://github.com/randy408/libspng/blob/master/docs/context.md Retrieves the currently set image width and height limits for the libspng context. The output parameters 'width' and 'height' must be valid pointers to uint32_t variables. ```c int spng_get_image_limits(spng_ctx *ctx, uint32_t *width, uint32_t *height); ``` -------------------------------- ### Get and Set PNG Gamma Value using C Source: https://context7.com/randy408/libspng/llms.txt Illustrates how to retrieve the gamma correction value of a PNG image using spng_get_gama and how to set a gamma value for an image being encoded using spng_set_gama. Handles cases where the gamma chunk is not present. ```c #include int handle_gamma(spng_ctx *ctx) { double gamma; int ret = spng_get_gama(ctx, &gamma); if (ret == SPNG_ECHUNKAVAIL) { printf("No gamma chunk (assuming 2.2)\n"); gamma = 2.2; } else if (ret == 0) { printf("Image gamma: %.4f\n", gamma); } return ret; } int set_gamma_for_encoding(spng_ctx *encoder_ctx) { /* Set standard sRGB gamma */ double gamma = 1.0 / 2.2; /* ~0.4545 */ return spng_set_gama(encoder_ctx, gamma); } ``` -------------------------------- ### Progressive Image Decoding Source: https://github.com/randy408/libspng/blob/master/docs/decode.md Explains how to perform progressive decoding for both interlaced and non-interlaced images using spng_decode_row(). It also provides code examples for iterating through rows and handling the end of the image (SPNG_EOI). ```APIDOC ## Progressive Image Decoding If the `SPNG_DECODE_PROGRESSIVE` flag is set, the decoder will be initialized with `fmt` and `flags` for progressive decoding. The values of `img` and `len` are ignored. Progressive decoding is straightforward when the image is not interlaced. Calling `spng_decode_row()` for each row of the image will yield the return value `SPNG_EOI` for the final row: ```c int error; size_t image_width = image_size / ihdr.height; for(i = 0; i < ihdr.height; i++) { void *row = image + image_width * i; error = spng_decode_row(ctx, row, image_width); if(error) break; } if(error == SPNG_EOI) /* success */ ``` But for interlaced images, rows are accessed multiple times and non-sequentially. Use `spng_get_row_info()` to get the current row number: ```c int error; struct spng_row_info row_info; do { error = spng_get_row_info(ctx, &row_info); if(error) break; void *row = image + image_width * row_info.row_num; error = spng_decode_row(ctx, row, len); } while(!error) if(error == SPNG_EOI) /* success */ ``` This is the recommended solution in all cases. For non-interlaced images, `row_num` will increase linearly. ``` -------------------------------- ### Get Suggested Palettes (C) Source: https://github.com/randy408/libspng/blob/master/docs/chunk.md Retrieves suggested palette information from the PNG image. This function copies data from sPLT chunks into a provided buffer and updates a count of the suggested palettes. It's useful for applications that can utilize predefined color palettes. ```c int spng_get_splt(spng_ctx *ctx, struct spng_splt *splt, uint32_t *n_splt) ``` -------------------------------- ### Get Chunk Size and Cache Limits (C) Source: https://github.com/randy408/libspng/blob/master/docs/context.md Retrieves the currently configured limits for PNG chunk size and chunk cache. The output parameters 'chunk_size' and 'cache_limit' must be valid pointers to size_t variables. ```c int spng_get_chunk_limits(spng_ctx *ctx, size_t *chunk_size, size_t *cache_limit); ``` -------------------------------- ### Conditional Library and Executable Definitions in CMake Source: https://github.com/randy408/libspng/blob/master/CMakeLists.txt This CMake code defines how shared and static libraries, along with an example executable, are built and linked. It conditionally adds targets based on build options like SPNG_SHARED and BUILD_EXAMPLES, and sets specific compile definitions for static builds. ```cmake if(NOT CMAKE_HOST_WIN32) set(MATH_LIBRARY "m") else() set(MATH_LIBRARY "") endif() if(NOT ENABLE_OPT) add_definitions( -DSPNG_DISABLE_OPT=1 ) endif() set(spng_TARGETS "") set(spng_SOURCES spng/spng.c) if(SPNG_SHARED) add_library(spng SHARED ${spng_SOURCES}) list(APPEND spng_TARGETS spng) if(BUILD_EXAMPLES) add_executable(example examples/example.c) target_link_libraries(example PRIVATE spng) endif() endif() if(SPNG_STATIC) add_library(spng_static STATIC ${spng_SOURCES}) target_compile_definitions(spng_static PUBLIC SPNG_STATIC) list(APPEND spng_TARGETS spng_static) endif() ``` -------------------------------- ### Get and Set PNG Text Metadata (tEXt, zTXt, iTXt) using C Source: https://context7.com/randy408/libspng/llms.txt Shows how to extract text metadata chunks (tEXt, zTXt, iTXt) from a PNG using spng_get_text and how to add custom text metadata to a PNG during encoding using spng_set_text. Includes handling for different text chunk types and internationalized text. ```c #include #include #include int read_text_chunks(spng_ctx *ctx) { uint32_t n_text = 0; /* First call to get count */ int ret = spng_get_text(ctx, NULL, &n_text); if (ret == SPNG_ECHUNKAVAIL) { printf("No text chunks in image\n"); return 0; } if (ret) return ret; struct spng_text *text = malloc(n_text * sizeof(struct spng_text)); ret = spng_get_text(ctx, text, &n_text); if (ret) { free(text); return ret; } printf("Found %u text chunks:\n", n_text); for (uint32_t i = 0; i < n_text; i++) { const char *type_names[] = {NULL, "tEXt", "zTXt", "iTXt"}; printf("\n[%u] Type: %s\n", i, type_names[text[i].type]); printf(" Keyword: %s\n", text[i].keyword); printf(" Text (%zu chars): %.100s%s\n", text[i].length, text[i].text, text[i].length > 100 ? "..." : ""); if (text[i].type == SPNG_ITXT) { printf(" Language: %s\n", text[i].language_tag); printf(" Translated keyword: %s\n", text[i].translated_keyword); } } free(text); return 0; } int add_text_metadata(spng_ctx *ctx) { struct spng_text text[2]; memset(text, 0, sizeof(text)); /* Simple tEXt chunk */ text[0].type = SPNG_TEXT; strcpy(text[0].keyword, "Author"); text[0].text = "John Doe"; text[0].length = strlen(text[0].text); /* Another text chunk */ text[1].type = SPNG_TEXT; strcpy(text[1].keyword, "Description"); text[1].text = "A sample PNG image created with libspng"; text[1].length = strlen(text[1].text); return spng_set_text(ctx, text, 2); } ``` -------------------------------- ### Create and Free libspng Contexts (C) Source: https://context7.com/randy408/libspng/llms.txt Demonstrates how to create new decoder or encoder contexts using `spng_ctx_new` and release them with `spng_ctx_free`. Supports flags for encoding and ignoring checksums. Memory must be managed carefully. ```c #include /* Create a decoder context */ spng_ctx *decoder = spng_ctx_new(0); if (decoder == NULL) { fprintf(stderr, "Failed to create decoder context\n"); return -1; } /* Create an encoder context */ spng_ctx *encoder = spng_ctx_new(SPNG_CTX_ENCODER); if (encoder == NULL) { fprintf(stderr, "Failed to create encoder context\n"); spng_ctx_free(decoder); return -1; } /* Create decoder that ignores Adler-32 checksums (for corrupted files) */ spng_ctx *lenient_decoder = spng_ctx_new(SPNG_CTX_IGNORE_ADLER32); /* Always free contexts when done */ spng_ctx_free(decoder); spng_ctx_free(encoder); spng_ctx_free(lenient_decoder); ``` ```c #include spng_ctx *ctx = spng_ctx_new(0); /* ... use context ... */ /* Free all resources */ spng_ctx_free(ctx); ctx = NULL; /* Good practice to avoid dangling pointer */ ``` -------------------------------- ### Configure Meson for Development Builds and Sanitizers Source: https://github.com/randy408/libspng/blob/master/tests/README.md Enables developer builds for exposing test cases and configures Meson to use address and undefined sanitizers for enhanced debugging during testing. Requires Meson build system. ```bash meson configure -Ddev_build=true meson configure -Db_sanitize=address,undefined ``` -------------------------------- ### Force Fallback for Dependency Builds in Meson Source: https://github.com/randy408/libspng/blob/master/tests/README.md Forces Meson to download and build libpng and zlib from source, which is necessary for MemorySanitizer testing. This ensures all dependencies are instrumented correctly. Uses Meson's `--wrap-mode` option. ```bash meson setup --wrap-mode=forcefallback builddir ``` -------------------------------- ### Physical Pixel Dimensions (pHYs) Source: https://context7.com/randy408/libspng/llms.txt Functions to get and set the physical pixel dimensions (pHYs chunk) which specifies the intended display resolution. ```APIDOC ## spng_get_phys / spng_set_phys ### Description Gets or sets the physical pixel dimensions (pHYs chunk) specifying the intended display resolution. ### Method - `spng_get_phys`: GET - `spng_set_phys`: SET ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - `spng_get_phys`: `struct spng_phys *phys` - Pointer to a structure to store the physical dimensions. - `spng_set_phys`: `const struct spng_phys *phys` - Pointer to a structure containing the physical dimensions to set. ### Request Example ```c // Example for setting DPI struct spng_phys phys = { .ppu_x = (uint32_t)(dpi * 39.3701), /* Convert DPI to pixels per meter */ .ppu_y = (uint32_t)(dpi * 39.3701), .unit_specifier = 1 /* 1 = meters */ }; spng_set_phys(encoder_ctx, &phys); ``` ### Response #### Success Response (200) - `spng_get_phys`: Returns 0 on success, SPNG_ECHUNKAVAIL if no physical dimensions are specified. - `spng_set_phys`: Returns 0 on success. #### Response Example ```json // Example output from spng_get_phys { "unit_specifier": 1, // 1 = meters "ppu_x": 3780, // Pixels per meter X "ppu_y": 3780 // Pixels per meter Y } ``` ``` -------------------------------- ### Run Test Suite Source: https://github.com/randy408/libspng/blob/master/CONTRIBUTING.md This command runs the project's test suite using ninja. All tests should pass for a successful contribution. Runtime errors reported by ASan/UBSan might not fail a test but should be addressed as bugs. ```bash ninja test ``` -------------------------------- ### Image and Chunk Limits API Source: https://github.com/randy408/libspng/blob/master/docs/context.md Functions for setting and getting limits on image dimensions and chunk sizes to manage memory usage. ```APIDOC ## spng_set_image_limits() ### Description Sets the maximum allowed width and height for PNG images. These limits cannot exceed 2^31 - 1. ### Method `int spng_set_image_limits(spng_ctx *ctx, uint32_t width, uint32_t height)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```c spng_set_image_limits(ctx, 4096, 4096); ``` ### Response #### Success Response (200) - **0** on success. #### Response Example None ## spng_get_image_limits() ### Description Retrieves the currently set image width and height limits. ### Method `int spng_get_image_limits(spng_ctx *ctx, uint32_t *width, uint32_t *height)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```c uint32_t max_width, max_height; spng_get_image_limits(ctx, &max_width, &max_height); ``` ### Response #### Success Response (200) - **0** on success. - **width** (uint32_t *) - Pointer to store the maximum width. - **height** (uint32_t *) - Pointer to store the maximum height. #### Response Example None ## spng_set_chunk_limits() ### Description Sets the limits for chunk size and chunk cache. The default chunk size limit is 2^31 - 1, and the default chunk cache limit is SIZE_MAX. Exceeding these limits during decoding is treated as an out-of-memory error. ### Method `int spng_set_chunk_limits(spng_ctx *ctx, size_t chunk_size, size_t cache_limit)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```c spng_set_chunk_limits(ctx, 1024 * 1024, SIZE_MAX); ``` ### Response #### Success Response (200) - **0** on success. #### Response Example None ## spng_get_chunk_limits() ### Description Retrieves the currently set chunk size and chunk cache limits. ### Method `int spng_get_chunk_limits(spng_ctx *ctx, size_t *chunk_size, size_t *cache_limit)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```c size_t max_chunk_size, max_cache_limit; spng_get_chunk_limits(ctx, &max_chunk_size, &max_cache_limit); ``` ### Response #### Success Response (200) - **0** on success. - **chunk_size** (size_t *) - Pointer to store the maximum chunk size. - **cache_limit** (size_t *) - Pointer to store the maximum cache limit. #### Response Example None ``` -------------------------------- ### Input/Output Configuration API Source: https://context7.com/randy408/libspng/llms.txt APIs for configuring input sources (buffers, files) for decoding and output destinations for encoding. ```APIDOC ## Input/Output Configuration API ### spng_set_png_buffer **Description**: Sets an input PNG buffer for decoding. This is an efficient method when the entire PNG is in memory. The buffer must remain valid until the context is freed. **Method**: N/A (C function) **Endpoint**: N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```c #include #include #include // Assume 'buf' contains PNG data and 'size' is its size void *buf = malloc(size); /* ... fill buf ... */ spng_ctx *ctx = spng_ctx_new(0); int ret = spng_set_png_buffer(ctx, buf, size); if (ret) { /* handle error */ } /* ... decode image ... */ spng_ctx_free(ctx); free(buf); ``` ### Response #### Success Response (0) - **int**: 0 on success. #### Error Response (Non-zero) - **int**: Non-zero error code. Use `spng_strerror()` to get a description. #### Response Example N/A (C function returns int) --- ### spng_set_png_file **Description**: Sets a FILE pointer as the input source for decoding or output destination for encoding. The file must remain open for the lifetime of the context. **Method**: N/A (C function) **Endpoint**: N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```c #include #include FILE *png = fopen("image.png", "rb"); if (!png) { /* handle error */ } spng_ctx *ctx = spng_ctx_new(0); int ret = spng_set_png_file(ctx, png); if (ret) { /* handle error */ } /* ... decode image ... */ spng_ctx_free(ctx); close(png); ``` ### Response #### Success Response (0) - **int**: 0 on success. #### Error Response (Non-zero) - **int**: Non-zero error code. Use `spng_strerror()` to get a description. #### Response Example N/A (C function returns int) ``` -------------------------------- ### Get libspng Version String (C) Source: https://github.com/randy408/libspng/blob/master/docs/version.md Retrieves the current version of the libspng library as a human-readable string. This function is useful for logging or displaying version information to users. ```c const char *spng_version_string(void) ``` -------------------------------- ### Get Option Value - C Source: https://github.com/randy408/libspng/blob/master/docs/context.md Retrieves the integer value of a specified spng_option from the spng_ctx. This function is essential for querying the current state of decoding or encoding parameters. ```c int spng_get_option(spng_ctx *ctx, enum spng_option option, int *value) ``` -------------------------------- ### Get Image Histogram (C) Source: https://github.com/randy408/libspng/blob/master/docs/chunk.md Retrieves the histogram of colors present in the PNG image. The histogram provides information about the frequency of each color in the image, stored in the hIST chunk. This can be useful for image analysis and processing. ```c int spng_get_hist(spng_ctx *ctx, struct spng_hist *hist) ``` -------------------------------- ### Configure Build Options (Meson) Source: https://github.com/randy408/libspng/blob/master/meson_options.txt These options are used within the Meson build system to configure the libspng build. They allow developers to enable or disable specific features, optimizations, and external dependencies. ```meson option('dev_build', type : 'boolean', value : false, description : 'Enable the testsuite, requires libpng') option('enable_opt', type : 'boolean', value : true, description : 'Enable architecture-specific optimizations') option('use_miniz', type : 'boolean', value : false, description : 'Compile with miniz instead of zlib, disables some features') option('static_zlib', type : 'boolean', value : false, description : 'Link zlib statically') option('benchmarks', type : 'boolean', value : false, description : 'Enable benchmarks, requires Git LFS') option('build_examples', type : 'boolean', value : true, description : 'Build examples, overriden by dev_build') option('multithreading', type : 'feature', value : 'disabled', description : 'Experimental multithreading features') option('oss_fuzz', type : 'boolean', value : false, description : 'Enable regression tests with OSS-Fuzz corpora') ``` -------------------------------- ### Get Error Message from Code (C) Source: https://github.com/randy408/libspng/blob/master/docs/errors.md The spng_strerror function takes an integer error code and returns a constant character pointer to the corresponding error message string. This is useful for debugging and providing user-friendly error feedback. ```c const char *spng_strerror(int err) ``` -------------------------------- ### Encoder Configuration Source: https://github.com/randy408/libspng/blob/master/docs/migrate-libpng.md This section details how to configure the spng encoder, mapping libpng functions to their spng equivalents and noting any differences or unsupported features. ```APIDOC ## Encoder Configuration This section maps libpng encoder configuration functions to their corresponding spng equivalents. ### `spng_set_option()` This function is used to set various encoder options in spng, analogous to several libpng functions. #### Options mapped from libpng: - `png_set_keep_unknown_chunks()` -> `spng_set_option(ctx, SPNG_KEEP_UNKNOWN_CHUNKS, ...)` - `png_set_compression_level()` -> `spng_set_option(ctx, SPNG_IMG_COMPRESSION_LEVEL, ...)` - `png_set_compression_mem_level()` -> `spng_set_option(ctx, SPNG_IMG_MEM_LEVEL, ...)` - `png_set_compression_strategy()` -> `spng_set_option(ctx, SPNG_IMG_COMPRESSION_STRATEGY, ...)` - `png_set_compression_window_bits()` -> `spng_set_option(ctx, SPNG_IMG_WINDOW_BITS, ...)` - `png_set_text_compression_level()` -> `spng_set_option(ctx, SPNG_TEXT_COMPRESSION_LEVEL, ...)` - `png_set_text_compression_mem_level()` -> `spng_set_option(ctx, SPNG_TEXT_MEM_LEVEL, ...)` - `png_set_text_compression_strategy()` -> `spng_set_option(ctx, SPNG_TEXT_COMPRESSION_STRATEGY, ...)` - `png_set_text_compression_window_bits()` -> `spng_set_option(ctx, SPNG_TEXT_WINDOW_BITS, ...)` - `png_set_filter()` -> `spng_set_option(ctx, SPNG_FILTER_CHOICE, ...)` (See [Filter choices](#filter-choices)) - `png_set_chunk_cache_max()` -> `spng_set_option(ctx, SPNG_CHUNK_COUNT_LIMIT, ...)` ### `spng_set_chunk_limits()` This function is used to set the maximum chunk size, analogous to `png_set_chunk_malloc_max()` in libpng. - `png_set_chunk_malloc_max()` -> `spng_set_chunk_limits(ctx, chunk_size)` ### `spng_get_chunk_limits()` This function retrieves the maximum chunk size, analogous to `png_get_chunk_malloc_max()` in libpng. - `png_get_chunk_malloc_max()` -> `spng_get_chunk_limits(ctx, &chunk_size)` ### Unsupported Features: - `png_handle_as_unknown()` - `png_set_unknown_chunk_location()` - `png_set_compression_method()` - `png_set_text_compression_method()` - `png_set_quantize()` ### Context Management: - `png_create_write_struct()` and `png_destroy_write_struct()` are managed via spng contexts (See [Contexts](#contexts)). ``` -------------------------------- ### Set PNG Input Buffer for Decoding (C) Source: https://context7.com/randy408/libspng/llms.txt Shows how to load an entire PNG image into memory and set it as the input for decoding using `spng_set_png_buffer`. The buffer must remain valid until the context is freed. Error handling for file operations and context creation is included. ```c #include #include #include int decode_from_buffer(void) { /* Read PNG file into memory */ FILE *file = fopen("image.png", "rb"); if (!file) return -1; fseek(file, 0, SEEK_END); size_t size = ftell(file); fseek(file, 0, SEEK_SET); void *buf = malloc(size); fread(buf, 1, size, file); fclose(file); /* Create context and set buffer */ spng_ctx *ctx = spng_ctx_new(0); int ret = spng_set_png_buffer(ctx, buf, size); if (ret) { printf("spng_set_png_buffer() error: %s\n", spng_strerror(ret)); spng_ctx_free(ctx); free(buf); return ret; } /* Buffer must remain valid until context is freed */ /* ... decode image ... */ spng_ctx_free(ctx); free(buf); return 0; } ``` -------------------------------- ### Get Image Offset (C) Source: https://github.com/randy408/libspng/blob/master/docs/chunk.md Retrieves the image offset information from a PNG context. This data, stored in the oFFs chunk, specifies the offset of the image relative to a background. It populates a spng_offs structure with x and y offset values. ```c int spng_get_offs(spng_ctx *ctx, struct spng_offs *offs) ``` -------------------------------- ### Running Meson Unit Tests Source: https://github.com/randy408/libspng/blob/master/tests/README.md Executes all unit tests configured within the Meson build system for the libspng project. This command is used after configuring the build environment. ```bash meson test ``` -------------------------------- ### Get Image Background Color (C) Source: https://github.com/randy408/libspng/blob/master/docs/chunk.md Retrieves the background color information for the PNG image. This is stored in the bKGD chunk and is used to determine the background color when an image is displayed with transparency. The function populates a spng_bkgd structure. ```c int spng_get_bkgd(spng_ctx *ctx, struct spng_bkgd *bkgd) ``` -------------------------------- ### Enable AddressSanitizer and UndefinedBehaviorSanitizer Source: https://github.com/randy408/libspng/blob/master/CONTRIBUTING.md This command configures the Meson build to enable AddressSanitizer (ASan) and UndefinedBehaviorSanitizer (UBSan) for detecting memory errors and undefined behavior during runtime. This requires the build directory to be active. ```bash meson configure -Db_sanitize=address,undefined ``` -------------------------------- ### Set PNG File Input/Output (C) Source: https://context7.com/randy408/libspng/llms.txt Illustrates how to use `spng_set_png_file` to set a `FILE` pointer as the source for decoding or destination for encoding. The `FILE` pointer must remain open throughout the context's lifetime. Includes error checking for file opening and function calls. ```c #include #include int decode_from_file(const char *filename) { FILE *png = fopen(filename, "rb"); if (!png) { printf("Error opening file: %s\n", filename); return -1; } spng_ctx *ctx = spng_ctx_new(0); int ret = spng_set_png_file(ctx, png); if (ret) { printf("spng_set_png_file() error: %s\n", spng_strerror(ret)); spng_ctx_free(ctx); fclose(png); return ret; } /* ... decode image ... */ spng_ctx_free(ctx); fclose(png); return 0; } ``` -------------------------------- ### Reproducing Fuzz Test Cases Source: https://github.com/randy408/libspng/blob/master/tests/README.md Utilizes the `fuzz_repro` executable to reproduce specific test cases identified during fuzz testing. This utility replaces the libFuzzer dependency, allowing for isolated reproduction of bugs. ```bash ./fuzz_repro ``` -------------------------------- ### Create Debug Build with Meson Source: https://github.com/randy408/libspng/blob/master/CONTRIBUTING.md This command creates a debug build of libspng using Meson, enabling development-specific features. It then changes the directory into the build folder. ```bash meson -Ddev_build=true --buildtype=debug build cd build ``` -------------------------------- ### Create New spng_ctx Context (C) Source: https://github.com/randy408/libspng/blob/master/docs/context.md Creates and initializes a new libspng context handle. The 'flags' parameter can be used to configure initial context behavior, such as enabling encoder mode. Returns a pointer to the new context or NULL on failure. ```c spng_ctx *spng_ctx_new(int flags); ``` -------------------------------- ### Get Modification Time (C) Source: https://github.com/randy408/libspng/blob/master/docs/chunk.md Retrieves the modification time of the PNG image. This information is stored in the tIME chunk and indicates when the image was last modified. It's recommended to call this after decoding the image to ensure the tIME chunk is available. ```c int spng_get_time(spng_ctx *ctx, struct spng_time *time) ```