### Build and Install OpenJPEG on UNIX/Linux/macOS Source: https://github.com/uclouvain/openjpeg/blob/master/INSTALL.md Instructions for building and installing the OpenJPEG library using CMake on UNIX-like systems. This process involves creating a build directory, configuring with CMake, compiling, and then installing the library. Dependencies like doxygen are mentioned for documentation generation. ```bash mkdir build cd build cmake .. -DCMAKE_BUILD_TYPE=Release make make install make clean ``` ```bash make doc ``` -------------------------------- ### Integrate OpenJPEG using CMake Source: https://github.com/uclouvain/openjpeg/blob/master/INSTALL.md This CMakeLists.txt example demonstrates how to integrate the OpenJPEG library into a C application. It uses find_package to locate OpenJPEG, includes its header directories, defines an executable target named 'myapp' from 'myapp.c', and links the application against the OpenJPEG libraries. ```cmake cmake_minimum_required(VERSION 3.1) project(MyApp) find_package(OpenJPEG REQUIRED) include_directories(${OPENJPEG_INCLUDE_DIRS}) add_executable(myapp myapp.c) target_link_libraries(myapp ${OPENJPEG_LIBRARIES}) ``` -------------------------------- ### Configure OpenJPEG Build with CMake Flags Source: https://github.com/uclouvain/openjpeg/blob/master/INSTALL.md Demonstrates how to use CMake flags to customize the OpenJPEG build process. Key options include specifying installation paths, enabling shared libraries, building codec executables, and enabling testing with data root configuration. ```bash cmake .. -DCMAKE_INSTALL_PREFIX=/path cmake .. -DBUILD_SHARED_LIBS:bool=on cmake .. -DBUILD_CODEC:bool=on cmake .. -DWITH_ASTYLE=ON ``` ```bash cmake . -DBUILD_TESTING:BOOL=ON -DOPJ_DATA_ROOT:PATH='path/to/the/data/directory' -DBUILDNAME:STRING='name_of_the_build' make make Experimental ``` -------------------------------- ### Generate Visual Studio Project Files for OpenJPEG Source: https://github.com/uclouvain/openjpeg/blob/master/INSTALL.md Instructions for generating Visual Studio solution and project files using CMake on Windows. This allows building OpenJPEG within the Visual Studio IDE. Examples cover different Visual Studio versions and 64-bit builds. ```bash cmake -G "NMake Makefiles" -DCMAKE_BUILD_TYPE:string="Release" -DBUILD_SHARED_LIBS:bool=on -DCMAKE_INSTALL_PREFIX:path="%USERPROFILE%" -DCMAKE_LIBRARY_PATH:path="%USERPROFILE%" -DCMAKE_INCLUDE_PATH:path="%USERPROFILE%\include" .. cmake -G "Visual Studio 14 2015" -DCMAKE_BUILD_TYPE:string="Release" -DBUILD_SHARED_LIBS:bool=on -DCMAKE_INSTALL_PREFIX:path="%USERPROFILE%" -DCMAKE_LIBRARY_PATH:path="%USERPROFILE%" -DCMAKE_INCLUDE_PATH:path="%USERPROFILE%\include" .. cmake -G "Visual Studio 14 2015 Win64" -DCMAKE_BUILD_TYPE:string="Release" -DBUILD_SHARED_LIBS:bool=on -DCMAKE_INSTALL_PREFIX:path="%USERPROFILE%" -DCMAKE_LIBRARY_PATH:path="%USERPROFILE%" -DCMAKE_INCLUDE_PATH:path="%USERPROFILE%\include" .. ``` -------------------------------- ### Install Development Libraries on Debian-like Systems Source: https://github.com/uclouvain/openjpeg/blob/master/INSTALL.md Provides the command to install necessary development libraries (lcms, tiff, png, z) on Debian-based Linux distributions using apt-get. These libraries are dependencies for the OpenJPEG encoder and decoder. ```bash sudo apt-get install liblcms2-dev libtiff-dev libpng-dev libz-dev ``` -------------------------------- ### Install HTML Documentation (CMake) Source: https://github.com/uclouvain/openjpeg/blob/master/doc/CMakeLists.txt This CMake code snippet defines an installation rule for the generated HTML documentation. It installs the entire contents of the 'html' directory within the build folder to the installation's documentation directory. It also excludes any '.svn' directories. ```cmake # install HTML documentation (install png files too): install(DIRECTORY ${CMAKE_BINARY_DIR}/doc/html DESTINATION ${CMAKE_INSTALL_DOCDIR} PATTERN ".svn" EXCLUDE ) ``` -------------------------------- ### Build Multiple Executables (CMake) Source: https://github.com/uclouvain/openjpeg/blob/master/src/bin/jpip/CMakeLists.txt Builds and installs several executables ('opj_dec_server', 'opj_jpip_transcode', 'opj_jpip_test') by iterating through a list. Each executable is linked against the 'openjpip' library and installed to the binary directory. ```cmake set(EXES opj_dec_server opj_jpip_transcode opj_jpip_test ) foreach(exe ${EXES}) add_executable(${exe} ${exe}.c) target_link_libraries(${exe} openjpip) install( TARGETS ${exe} EXPORT OpenJPEGTargets DESTINATION ${CMAKE_INSTALL_BINDIR} COMPONENT Applications ) endforeach() ``` -------------------------------- ### Install Project Targets and Configuration Files (CMake) Source: https://github.com/uclouvain/openjpeg/blob/master/CMakeLists.txt Installs the OpenJPEG targets and configuration files for package management. It exports targets using `install(EXPORT)`, configures the main `OpenJPEGConfig.cmake` and `OpenJPEGConfigVersion.cmake` files using helper functions, and installs them to the appropriate destination directory. ```cmake # install all targets referenced as OPENJPEGTargets (relocatable with CMake 3.0+) install(EXPORT OpenJPEGTargets DESTINATION ${OPENJPEG_INSTALL_PACKAGE_DIR}) include(CMakePackageConfigHelpers) configure_package_config_file(${CMAKE_CURRENT_LIST_DIR}/cmake/OpenJPEGConfig.cmake.in ${OPENJPEG_BINARY_DIR}/OpenJPEGConfig.cmake INSTALL_DESTINATION ${OPENJPEG_INSTALL_PACKAGE_DIR} PATH_VARS CMAKE_INSTALL_INCLUDEDIR) write_basic_package_version_file( ${OPENJPEG_BINARY_DIR}/OpenJPEGConfigVersion.cmake COMPATIBILITY SameMajorVersion VERSION ${OPENJPEG_VERSION}) install( FILES ${OPENJPEG_BINARY_DIR}/OpenJPEGConfig.cmake ${OPENJPEG_BINARY_DIR}/OpenJPEGConfigVersion.cmake DESTINATION ${OPENJPEG_INSTALL_PACKAGE_DIR}) ``` -------------------------------- ### Complete JPEG 2000 Compression Example in C Source: https://context7.com/uclouvain/openjpeg/llms.txt This C code demonstrates a full workflow for encoding an image into JPEG 2000 format using the OpenJPEG library. It includes functions for setting up encoder parameters, handling image data, and managing the compression process for both lossless and lossy compression. Dependencies include the OpenJPEG library. ```c #include #include #include #include void error_callback(const char* msg, void* client_data) { (void)client_data; fprintf(stderr, "[ERROR] %s", msg); } int encode_jpeg2000(const char* output_file, int width, int height, unsigned char* rgb_data, int use_lossy) { opj_cparameters_t parameters; opj_codec_t* codec = NULL; opj_stream_t* stream = NULL; opj_image_t* image = NULL; opj_image_cmptparm_t cmptparms[3]; int ret = 0; /* Initialize parameters */ opj_set_default_encoder_parameters(¶meters); if (use_lossy) { /* Lossy compression */ parameters.tcp_numlayers = 1; parameters.tcp_rates[0] = 10; /* 10:1 compression */ parameters.cp_disto_alloc = 1; parameters.irreversible = 1; } else { /* Lossless compression (default) */ parameters.tcp_numlayers = 1; parameters.tcp_rates[0] = 0; } parameters.numresolution = 6; /* Setup component parameters */ memset(cmptparms, 0, sizeof(cmptparms)); for (int i = 0; i < 3; i++) { cmptparms[i].dx = 1; cmptparms[i].dy = 1; cmptparms[i].w = width; cmptparms[i].h = height; cmptparms[i].prec = 8; cmptparms[i].sgnd = 0; } /* Create image */ image = opj_image_create(3, cmptparms, OPJ_CLRSPC_SRGB); if (!image) { fprintf(stderr, "Failed to create image\n"); return -1; } image->x0 = 0; image->y0 = 0; image->x1 = width; image->y1 = height; /* Copy RGB data to image components */ for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { int idx = y * width + x; int rgb_idx = idx * 3; image->comps[0].data[idx] = rgb_data[rgb_idx]; /* R */ image->comps[1].data[idx] = rgb_data[rgb_idx + 1]; /* G */ image->comps[2].data[idx] = rgb_data[rgb_idx + 2]; /* B */ } } /* Create codec */ codec = opj_create_compress(OPJ_CODEC_JP2); if (!codec) { fprintf(stderr, "Failed to create codec\n"); ret = -1; goto cleanup; } /* Set error handler */ opj_set_error_handler(codec, error_callback, NULL); /* Setup encoder */ if (!opj_setup_encoder(codec, ¶meters, image)) { fprintf(stderr, "Failed to setup encoder\n"); ret = -1; goto cleanup; } /* Optional: Set extra options (PLT, TLM markers) */ const char* options[] = {"PLT=YES", "TLM=YES", NULL}; opj_encoder_set_extra_options(codec, options); /* Enable multi-threading */ opj_codec_set_threads(codec, 4); /* Create output stream */ stream = opj_stream_create_default_file_stream(output_file, OPJ_STREAM_WRITE); if (!stream) { fprintf(stderr, "Failed to create stream\n"); ret = -1; goto cleanup; } /* Start compression */ if (!opj_start_compress(codec, image, stream)) { fprintf(stderr, "Failed to start compression\n"); ret = -1; goto cleanup; } /* Encode */ if (!opj_encode(codec, stream)) { fprintf(stderr, "Failed to encode\n"); ret = -1; goto cleanup; } /* End compression */ if (!opj_end_compress(codec, stream)) { fprintf(stderr, "Failed to end compression\n"); ret = -1; goto cleanup; } printf("Successfully encoded to %s\n", output_file); cleanup: if (stream) opj_stream_destroy(stream); if (codec) opj_destroy_codec(codec); if (image) opj_image_destroy(image); return ret; } int main(int argc, char* argv[]) { int width = 256, height = 256; /* Create test RGB data */ unsigned char* rgb_data = (unsigned char*)malloc(width * height * 3); for (int i = 0; i < width * height * 3; i++) { rgb_data[i] = i % 256; } /* Encode lossless */ encode_jpeg2000("output_lossless.jp2", width, height, rgb_data, 0); /* Encode lossy */ encode_jpeg2000("output_lossy.jp2", width, height, rgb_data, 1); free(rgb_data); return 0; } ``` -------------------------------- ### CMake: Setup Test Directories and Variables Source: https://github.com/uclouvain/openjpeg/blob/master/tests/conformance/CMakeLists.txt This CMake code snippet initializes directories for temporary files and defines paths to baseline and input data for conformance and non-regression tests. It sets up variables like `TEMP`, `BASELINE_CONF`, `BASELINE_NR`, and `INPUT_CONF`. ```cmake file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/Temporary) set(TEMP ${CMAKE_CURRENT_BINARY_DIR}/Temporary) set(BASELINE_CONF ${OPJ_DATA_ROOT}/baseline/conformance) set(BASELINE_NR ${OPJ_DATA_ROOT}/baseline/nonregression) set(INPUT_CONF ${OPJ_DATA_ROOT}/input/conformance) ``` -------------------------------- ### Enable Native CPU Optimization with CMake Source: https://github.com/uclouvain/openjpeg/blob/master/INSTALL.md This command enables optimizations tailored to the native CPU architecture of the machine where the code is compiled. It uses the '-march=native' flag, which automatically detects and utilizes the best instruction sets available on the host CPU, including SSE4.1 and AVX2 if supported. The '-O3' flag enables aggressive optimization, and '-DNDEBUG' disables assertions. The resulting binary will only run on compatible CPUs. ```bash cmake -DCMAKE_C_FLAGS="-O3 -march=native -DNDEBUG" .. ``` -------------------------------- ### Create and Manage Image Structures in C Source: https://context7.com/uclouvain/openjpeg/llms.txt Provides functions to allocate and initialize opj_image_t structures. Includes examples for standard creation and manual memory allocation for component data. ```c #include #include #include opj_image_t* create_image(int width, int height, int num_components, int precision) { opj_image_cmptparm_t* cmptparms; opj_image_t* image; /* Allocate component parameters */ cmptparms = (opj_image_cmptparm_t*)calloc(num_components, sizeof(opj_image_cmptparm_t)); if (!cmptparms) return NULL; /* Set component parameters */ for (int i = 0; i < num_components; i++) { cmptparms[i].dx = 1; /* Horizontal subsampling */ cmptparms[i].dy = 1; /* Vertical subsampling */ cmptparms[i].w = width; cmptparms[i].h = height; cmptparms[i].x0 = 0; cmptparms[i].y0 = 0; cmptparms[i].prec = precision; /* Bits per component */ cmptparms[i].sgnd = 0; /* Unsigned */ } /* Create image (RGB color space for 3 components) */ OPJ_COLOR_SPACE color_space = (num_components >= 3) ? OPJ_CLRSPC_SRGB : OPJ_CLRSPC_GRAY; image = opj_image_create(num_components, cmptparms, color_space); free(cmptparms); if (!image) return NULL; /* Set image offset and size */ image->x0 = 0; image->y0 = 0; image->x1 = width; image->y1 = height; return image; } /* Example: Create and fill an RGB image */ opj_image_t* create_rgb_test_image(int width, int height) { opj_image_t* image = create_image(width, height, 3, 8); if (!image) return NULL; /* Fill with test pattern */ for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { int idx = y * width + x; image->comps[0].data[idx] = (x + y) % 256; /* Red */ image->comps[1].data[idx] = (x * 2) % 256; /* Green */ image->comps[2].data[idx] = (y * 2) % 256; /* Blue */ } } return image; } /* Using opj_image_data_alloc for custom allocation */ opj_image_t* create_image_manual_alloc(int width, int height) { opj_image_cmptparm_t cmptparms[3]; memset(cmptparms, 0, sizeof(cmptparms)); for (int i = 0; i < 3; i++) { cmptparms[i].dx = cmptparms[i].dy = 1; cmptparms[i].w = width; cmptparms[i].h = height; cmptparms[i].prec = 8; cmptparms[i].sgnd = 0; } /* Create image without allocating component data */ opj_image_t* image = opj_image_tile_create(3, cmptparms, OPJ_CLRSPC_SRGB); if (!image) return NULL; /* Manually allocate component data */ size_t data_size = (size_t)width * height * sizeof(OPJ_INT32); for (int i = 0; i < 3; i++) { image->comps[i].data = (OPJ_INT32*)opj_image_data_alloc(data_size); if (!image->comps[i].data) { opj_image_destroy(image); return NULL; } } image->x0 = 0; image->y0 = 0; image->x1 = width; image->y1 = height; return image; } ``` -------------------------------- ### Define Path Variables for Installation (CMake Macro) Source: https://github.com/uclouvain/openjpeg/blob/master/CMakeLists.txt A CMake macro `set_variable_from_rel_or_absolute_path` that defines installation path variables (like bindir, libdir, includedir). It correctly handles both relative and absolute paths provided during configuration, ensuring that installation directories are set appropriately based on the build prefix. ```cmake macro(set_variable_from_rel_or_absolute_path var root rel_or_abs_path) if(IS_ABSOLUTE "${rel_or_abs_path}") set(${var} "${rel_or_abs_path}") else() set(${var} "${root}/${rel_or_abs_path}") endif() endmacro() set_variable_from_rel_or_absolute_path("bindir" "\\${prefix}" "${CMAKE_INSTALL_BINDIR}") set_variable_from_rel_or_absolute_path("mandir" "\\${prefix}" "${CMAKE_INSTALL_MANDIR}") set_variable_from_rel_or_absolute_path("docdir" "\\${prefix}" "${CMAKE_INSTALL_DOCDIR}") set_variable_from_rel_or_absolute_path("libdir" "\\${prefix}" "${CMAKE_INSTALL_LIBDIR}") set_variable_from_rel_or_absolute_path("includedir" "\\${prefix}" "${CMAKE_INSTALL_INCLUDEDIR}/${OPENJPEG_INSTALL_SUBDIR}") ``` -------------------------------- ### Java Client Compilation Setup (CMake) Source: https://github.com/uclouvain/openjpeg/blob/master/src/bin/jpip/CMakeLists.txt Configures the build to find and use a Java Development Kit (JDK) version 1.8 or higher. It sets default Java source and target versions, allowing users to override them if needed. ```cmake # Build the two java clients: find_package(Java 1.8 COMPONENTS Development) # javac, jar # User can override this: if(NOT DEFINED JAVA_SOURCE_VERSION) set(JAVA_SOURCE_VERSION 1.8) endif() if(NOT DEFINED JAVA_TARGET_VERSION) set(JAVA_TARGET_VERSION 1.8) endif() ``` -------------------------------- ### Configure OpenJPEG Library Build and Installation Source: https://github.com/uclouvain/openjpeg/blob/master/src/lib/openjp2/CMakeLists.txt This snippet defines the core source files for the OpenJPEG library, handles conditional JPIP support, and sets up the library targets for both static and shared builds. It also includes instructions for installing the resulting binaries, headers, and documentation. ```cmake set(OPENJPEG_SRCS ${CMAKE_CURRENT_SOURCE_DIR}/thread.c ${CMAKE_CURRENT_SOURCE_DIR}/bio.c ${CMAKE_CURRENT_SOURCE_DIR}/j2k.c ${CMAKE_CURRENT_SOURCE_DIR}/openjpeg.c # ... additional source files ... ) if(BUILD_JPIP) add_definitions(-DUSE_JPIP) set(OPENJPEG_SRCS ${OPENJPEG_SRCS} ${CMAKE_CURRENT_SOURCE_DIR}/cidx_manager.c) endif() add_library(${OPENJPEG_LIBRARY_NAME} ${OPENJPEG_SRCS}) install(TARGETS ${INSTALL_LIBS} EXPORT OpenJPEGTargets RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} COMPONENT Applications LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} COMPONENT Libraries ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} COMPONENT Libraries ) ``` -------------------------------- ### Build opj_jpip_addxml Executable (CMake) Source: https://github.com/uclouvain/openjpeg/blob/master/src/bin/jpip/CMakeLists.txt Defines and installs the 'opj_jpip_addxml' executable, which is a tool used to embed metadata into JP2 files. It is installed to the binary directory. ```cmake # Tool to embed metadata into JP2 file add_executable(opj_jpip_addxml opj_jpip_addxml.c) # Install exe install( TARGETS opj_jpip_addxml EXPORT OpenJPEGTargets DESTINATION ${CMAKE_INSTALL_BINDIR} COMPONENT Applications ) ``` -------------------------------- ### Build opj_server Executable (CMake) Source: https://github.com/uclouvain/openjpeg/blob/master/src/bin/jpip/CMakeLists.txt Conditionally builds the 'opj_server' executable if BUILD_JPIP_SERVER is enabled. It links against FCGI libraries and openjpip_server, and sets specific compile definitions. It also includes linking to the math library on UNIX systems and is installed to the binary directory. ```cmake if(BUILD_JPIP_SERVER) set(OPJ_SERVER_SRCS ${CMAKE_CURRENT_SOURCE_DIR}/opj_server.c ) # Build executable add_executable(opj_server ${OPJ_SERVER_SRCS}) target_link_libraries(opj_server ${FCGI_LIBRARIES} openjpip_server) set_property( TARGET opj_server APPEND PROPERTY COMPILE_DEFINITIONS SERVER QUIT_SIGNAL="quitJPIP" ) # On unix you need to link to the math library: if(UNIX) target_link_libraries(opj_server m) endif() # Install exe install( TARGETS opj_server EXPORT OpenJPEGTargets DESTINATION ${CMAKE_INSTALL_BINDIR} COMPONENT Applications ) endif() ``` -------------------------------- ### Configure Multi-threading in OpenJPEG C API Source: https://context7.com/uclouvain/openjpeg/llms.txt Demonstrates how to check for thread support, detect available CPU cores, and set the thread count for OpenJPEG codecs. This must be performed after codec setup and before the encoding/decoding process. ```c #include #include void configure_threading(opj_codec_t* codec) { /* Check if library has thread support */ if (opj_has_thread_support()) { printf("OpenJPEG built with thread support\n"); /* Get number of available CPUs */ int num_cpus = opj_get_num_cpus(); printf("Available CPUs: %d\n", num_cpus); /* Set number of threads */ /* Must be called after opj_setup_decoder/encoder and before decode/encode */ opj_codec_set_threads(codec, num_cpus); /* Or use specific thread count */ opj_codec_set_threads(codec, 4); } else { printf("OpenJPEG built without thread support\n"); } } ``` -------------------------------- ### Configure ZLIB Library (CMake) Source: https://github.com/uclouvain/openjpeg/blob/master/thirdparty/CMakeLists.txt This CMake script block handles the configuration of the ZLIB library. It checks the BUILD_THIRDPARTY flag to decide whether to build ZLIB from its third-party subdirectory or to find an existing ZLIB installation on the system using find_package(ZLIB). It sets variables for the library name and include directory based on the chosen method. ```cmake if(NOT BUILD_THIRDPARTY) include(FindPkgConfig) endif(NOT BUILD_THIRDPARTY) #------------ # Try to find lib Z if(BUILD_THIRDPARTY) # Try to build it message(STATUS "We will build Z lib from thirdparty") add_subdirectory(libz) set(Z_LIBNAME z PARENT_SCOPE) set(Z_INCLUDE_DIRNAME ${OPENJPEG_SOURCE_DIR}/thirdparty/include PARENT_SCOPE) set(ZLIB_FOUND 1) else(BUILD_THIRDPARTY) # Try to find lib Z find_package(ZLIB) if(ZLIB_FOUND) set(Z_LIBNAME ${ZLIB_LIBRARIES} PARENT_SCOPE) set(Z_INCLUDE_DIRNAME ${ZLIB_INCLUDE_DIRS} PARENT_SCOPE) message(STATUS "Your system seems to have a Z lib available, we will use it to generate PNG lib") # message(STATUS "DEBUG: ${ZLIB_INCLUDE_DIRS} vs ${ZLIB_INCLUDE_DIR}") else(ZLIB_FOUND) # not found message(STATUS "Z lib not found, activate BUILD_THIRDPARTY if you want build it (necessary to build libPNG)") endif(ZLIB_FOUND) endif(BUILD_THIRDPARTY) ``` -------------------------------- ### Configure Internal Library Dependencies with CMake Source: https://github.com/uclouvain/openjpeg/wiki/FolderReorgProposal An example demonstrating how to use CMake to manage internal library dependencies using LINK_PRIVATE and LINK_PUBLIC. This approach helps in hiding internal implementation details while allowing shared libraries to consume common core functionality. ```cmake add_library(libCore STATIC internal.c) add_library(libA SHARED a.c) target_link_libraries(libA LINK_PRIVATE libCore) add_library(libB SHARED b.c) target_link_libraries(libB LINK_PUBLIC libA LINK_PRIVATE libCore) install(TARGETS libA libB EXPORT myexport RUNTIME DESTINATION bin LIBRARY DESTINATION lib ) install(EXPORT myexport DESTINATION share) ``` -------------------------------- ### Configure OpenJPEG for macOS with Specific Architecture Source: https://github.com/uclouvain/openjpeg/blob/master/INSTALL.md A specific CMake flag for macOS to address potential build issues by targeting the i386 architecture. This is a troubleshooting step for macOS users. ```bash cmake .. -DCMAKE_OSX_ARCHITECTURES:STRING=i386 ``` -------------------------------- ### Prepare Commit Script for OpenJPEG Source: https://github.com/uclouvain/openjpeg/blob/master/INSTALL.md This command executes the 'prepare-commit.sh' script, which is used to prepare changes before committing them to the OpenJPEG repository. This script likely performs tasks such as code formatting, linting, or running pre-commit checks to ensure code quality and consistency. ```bash scripts/prepare-commit.sh ``` -------------------------------- ### Enable SSE4.1 Optimization with CMake Source: https://github.com/uclouvain/openjpeg/blob/master/INSTALL.md This command enables the SSE4.1 instruction set for CPU optimizations in OpenJPEG during the CMake build process. It sets the C compiler flags to include -O3 for optimization, -msse4.1 for SSE4.1 support, and -DNDEBUG to disable assertions. This will result in a binary that runs only on CPUs supporting SSE4.1. ```bash cmake -DCMAKE_C_FLAGS="-O3 -msse4.1 -DNDEBUG" .. ``` -------------------------------- ### Manage Streams for I/O in C Source: https://context7.com/uclouvain/openjpeg/llms.txt Illustrates how to manage input/output streams with OpenJPEG. This includes creating default file streams for reading and writing, creating streams with custom buffer sizes, and setting up custom streams using callback functions for read, seek, and skip operations. ```c #include /* Create a read stream from file */ opj_stream_t* stream = opj_stream_create_default_file_stream( "input.jp2", OPJ_STREAM_READ /* OPJ_TRUE for read */ ); if (!stream) { fprintf(stderr, "Failed to create stream\n"); return -1; } /* Create a write stream for compression */ opj_stream_t* out_stream = opj_stream_create_default_file_stream( "output.jp2", OPJ_STREAM_WRITE /* OPJ_FALSE for write */ ); /* Create stream with custom buffer size */ opj_stream_t* buffered_stream = opj_stream_create_file_stream( "input.jp2", 1024 * 1024, /* 1MB buffer */ OPJ_STREAM_READ ); /* Custom stream with callbacks */ opj_stream_t* custom_stream = opj_stream_create(1024 * 1024, OPJ_STREAM_READ); opj_stream_set_read_function(custom_stream, my_read_callback); opj_stream_set_seek_function(custom_stream, my_seek_callback); opj_stream_set_skip_function(custom_stream, my_skip_callback); opj_stream_set_user_data(custom_stream, my_data, my_free_function); opj_stream_set_user_data_length(custom_stream, data_length); /* Clean up */ opj_stream_destroy(stream); ``` -------------------------------- ### Enable AVX2 Optimization with CMake Source: https://github.com/uclouvain/openjpeg/blob/master/INSTALL.md This command enables the AVX2 instruction set for CPU optimizations in OpenJPEG. It sets the C compiler flags to include -O3 for optimization, -mavx2 for AVX2 support, and -DNDEBUG to disable assertions. AVX2 instruction set implies SSE4.1 support. The resulting binary will only run on CPUs supporting AVX2. ```bash cmake -DCMAKE_C_FLAGS="-O3 -mavx2 -DNDEBUG" .. ``` -------------------------------- ### Configure and Build PNG Static Library with CMake Source: https://github.com/uclouvain/openjpeg/blob/master/thirdparty/libpng/CMakeLists.txt This script removes specific compiler warnings, sets up include directories, and defines a static library target for PNG. It handles platform-specific naming for MSVC and links against required Zlib and math libraries. ```cmake project(libpng C) string(REPLACE "-Wconversion" "" CMAKE_C_FLAGS "${CMAKE_C_FLAGS}") string(REPLACE "-Wsign-conversion" "" CMAKE_C_FLAGS "${CMAKE_C_FLAGS}") include_directories( "${CMAKE_CURRENT_SOURCE_DIR}" ${OPENJPEG_SOURCE_DIR}/thirdparty/include ) file(GLOB SRCS *.c) file(GLOB HDRS *.h) set(EXT_HDRS ${OPENJPEG_SOURCE_DIR}/thirdparty/include/zlib.h ${OPENJPEG_SOURCE_DIR}/thirdparty/include/zconf.h ) set(LIBTARGET "png") add_library(${LIBTARGET} STATIC ${SRCS} ${HDRS} ${EXT_HDRS}) if(MSVC) set_target_properties(${LIBTARGET} PROPERTIES PREFIX "lib") endif(MSVC) target_compile_definitions(${LIBTARGET} PRIVATE PNG_ARM_NEON_OPT=0) target_link_libraries(${LIBTARGET} ${Z_LIBNAME} ${M_LIBRARY}) set_target_properties(${LIBTARGET} PROPERTIES OUTPUT_NAME "${LIBTARGET}" ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/thirdparty/lib) ``` -------------------------------- ### Build OpenJPEG from Source Source: https://context7.com/uclouvain/openjpeg/llms.txt Shell commands for cloning, configuring, and building the OpenJPEG repository using CMake. Includes options for optimization, static linking, and enabling third-party dependencies. ```bash # Clone repository git clone https://github.com/uclouvain/openjpeg.git cd openjpeg # Create build directory mkdir build && cd build # Configure with CMake cmake .. -DCMAKE_BUILD_TYPE=Release \ -DBUILD_SHARED_LIBS=ON \ -DBUILD_CODEC=ON # Build make -j$(nproc) # Install (requires root) sudo make install # Build with optimizations (SSE4.1/AVX2) cmake .. -DCMAKE_BUILD_TYPE=Release \ -DCMAKE_C_FLAGS="-O3 -mavx2 -DNDEBUG" # Build static library cmake .. -DBUILD_SHARED_LIBS=OFF # Build with third-party libraries cmake .. -DBUILD_THIRDPARTY=ON # Enable testing cmake .. -DBUILD_TESTING=ON \ -DOPJ_DATA_ROOT=/path/to/openjpeg-data make make Experimental ``` -------------------------------- ### CMake: Installation Directory Configuration Source: https://github.com/uclouvain/openjpeg/blob/master/CMakeLists.txt Sets up standard installation directories using the GNUInstallDirs module and defines specific subdirectories for OpenJPEG. It configures installation paths for libraries, binaries, and CMake package configuration files, making the installed project easier to manage and use in other CMake projects. ```cmake # -------------------------------------------------------------------------- # Install directories string(TOLOWER ${PROJECT_NAME} PROJECT_NAME) include(GNUInstallDirs) # Build DOCUMENTATION (not in ALL target and only if Doxygen is found) option(BUILD_DOC "Build the HTML documentation (with doxygen if available)." OFF) set(OPENJPEG_INSTALL_SUBDIR "${PROJECT_NAME}-${OPENJPEG_VERSION_MAJOR}.${OPENJPEG_VERSION_MINOR}") if(NOT OPENJPEG_INSTALL_JNI_DIR) if(WIN32) set(OPENJPEG_INSTALL_JNI_DIR ${CMAKE_INSTALL_BINDIR}) else() set(OPENJPEG_INSTALL_JNI_DIR ${CMAKE_INSTALL_LIBDIR}) endif() endif() if(NOT OPENJPEG_INSTALL_PACKAGE_DIR) set(OPENJPEG_INSTALL_PACKAGE_DIR "${CMAKE_INSTALL_LIBDIR}/cmake/${OPENJPEG_INSTALL_SUBDIR}") endif() if (APPLE) option(OPJ_USE_DSYMUTIL "Call dsymutil on binaries after build." OFF) endif() #----------------------------------------------------------------------------- # Big endian test: if (NOT EMSCRIPTEN) include (${CMAKE_ROOT}/Modules/TestBigEndian.cmake) TEST_BIG_ENDIAN(OPJ_BIG_ENDIAN) endif() #----------------------------------------------------------------------------- # Setup file for setting custom ctest vars configure_file( ${${OPENJPEG_NAMESPACE}_SOURCE_DIR}/cmake/CTestCustom.cmake.in ${${OPENJPEG_NAMESPACE}_BINARY_DIR}/CTestCustom.cmake @ONLY ) ``` -------------------------------- ### Synchronize SVN Repository with svnsync Source: https://github.com/uclouvain/openjpeg/wiki/VCSGuideline Steps to create a local mirror of a remote SVN repository, including hook configuration and initialization. ```bash $ cd /tmp $ svnadmin create openjpeg_local $ echo '#!/bin/sh' > ./openjpeg_local/hooks/pre-revprop-change $ chmod +x ./openjpeg_local/hooks/pre-revprop-change $ svnsync initialize file:///tmp/openjpeg_local/ http://openjpeg.googlecode.com/svn/trunk/ $ svnsync sync file:///tmp/openjpeg_local/ ``` -------------------------------- ### Clone and Configure Git-SVN Repository Source: https://github.com/uclouvain/openjpeg/wiki/VCSGuideline Commands to clone an existing SVN repository into a local Git environment and configure the ignore patterns to match the SVN structure. ```bash $ git svn clone https://openjpeg.googlecode.com/svn/ -T trunk -b branches -t tags $ git svn show-ignore >> .git/info/exclude ``` -------------------------------- ### Configure JPEG 2000 Compression Parameters in C Source: https://context7.com/uclouvain/openjpeg/llms.txt Demonstrates how to initialize and customize the opj_cparameters_t structure. It covers setting quality layers, compression ratios, DWT decomposition levels, and specific profiles like Digital Cinema or IMF. ```c #include opj_cparameters_t parameters; /* Initialize default parameters (lossless) */ opj_set_default_encoder_parameters(¶meters); /* Lossy compression with compression ratios */ parameters.tcp_numlayers = 3; parameters.tcp_rates[0] = 20; /* 20:1 compression */ parameters.tcp_rates[1] = 10; /* 10:1 compression */ parameters.tcp_rates[2] = 1; /* Lossless final layer */ parameters.cp_disto_alloc = 1; /* OR: Quality-based (PSNR) compression */ parameters.tcp_numlayers = 3; parameters.tcp_distoratio[0] = 30; /* 30 dB */ parameters.tcp_distoratio[1] = 40; /* 40 dB */ parameters.tcp_distoratio[2] = 0; /* Lossless */ parameters.cp_fixed_quality = 1; /* Irreversible compression (DWT 9-7) */ parameters.irreversible = 1; /* Number of resolutions (DWT decompositions + 1) */ parameters.numresolution = 6; /* Code-block size */ parameters.cblockw_init = 64; parameters.cblockh_init = 64; /* Tile size */ parameters.tile_size_on = OPJ_TRUE; parameters.cp_tx0 = 0; parameters.cp_ty0 = 0; parameters.cp_tdx = 1024; parameters.cp_tdy = 1024; /* Progression order */ parameters.prog_order = OPJ_LRCP; /* LRCP, RLCP, RPCL, PCRL, CPRL */ /* Digital Cinema 2K profile */ parameters.rsiz = OPJ_PROFILE_CINEMA_2K; parameters.max_cs_size = OPJ_CINEMA_24_CS; parameters.max_comp_size = OPJ_CINEMA_24_COMP; /* IMF profile with main level and sublevel */ parameters.rsiz = OPJ_PROFILE_IMF_2K | 0x0040 | 0x0005; /* Mode switches for code-block coding */ parameters.mode = 0; /* Add values: BYPASS=1, RESET=2, RESTART=4, VSC=8, ERTERM=16, SEGMARK=32 */ /* SOP and EPH markers */ parameters.csty |= 0x01; /* SOP marker */ parameters.csty |= 0x02; /* EPH marker */ ``` -------------------------------- ### Encode TIFF to JP2 with JPIP options Source: https://github.com/uclouvain/openjpeg/wiki/OpenJPIP Encodes a TIFF image to JP2 format using `image_to_j2k`. Key options include specifying the input and output files, the JPIP profile (`-p RPCL`), tile size (`-t`), and crucially, embedding the JPIP index table (`-jpip`) and partitioning tiles for JPIP streaming (`-TP R`). The `-jpip` option is essential for JPIP server compatibility. ```bash % ./image_to_j2k -i copenhague1.tif -o copenhague1.jp2 -p RPCL -c [64,64] -t 640,480 -jpip -TP R ``` -------------------------------- ### Configure and Install JPIP Package Configuration Source: https://github.com/uclouvain/openjpeg/blob/master/CMakeLists.txt This CMake snippet conditionally configures the libopenjpip.pc file based on the BUILD_JPIP flag. It retrieves package dependencies, generates the configuration file from a template, and installs it to the system pkgconfig directory. ```cmake if(BUILD_JPIP) get_pkgconfig_deps(openjpip deps) configure_file(${CMAKE_CURRENT_SOURCE_DIR}/src/lib/openjpip/libopenjpip.pc.cmake.in ${CMAKE_CURRENT_BINARY_DIR}/libopenjpip.pc @ONLY) install( FILES ${CMAKE_CURRENT_BINARY_DIR}/libopenjpip.pc DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig ) endif() ``` -------------------------------- ### Configure and Install Pkg-config File (CMake) Source: https://github.com/uclouvain/openjpeg/blob/master/CMakeLists.txt Configures the `libopenjp2.pc` file using a CMake template and installs it to the pkg-config directory. This enables other projects to easily find and link against the OpenJPEG library using standard pkg-config mechanisms. ```cmake # install in lib and not share (CMAKE_INSTALL_LIBDIR takes care of it for multi-arch) configure_file(${CMAKE_CURRENT_SOURCE_DIR}/src/lib/openjp2/libopenjp2.pc.cmake.in ${CMAKE_CURRENT_BINARY_DIR}/libopenjp2.pc @ONLY) install( FILES ${CMAKE_CURRENT_BINARY_DIR}/libopenjp2.pc DESTINATION ${CMAKE_INSTALL_LIBDIR}/pkgconfig ) ``` -------------------------------- ### Example XML metadata structure for JP2 embedding Source: https://github.com/uclouvain/openjpeg/wiki/OpenJPIP An example of an XML file structure used to embed metadata into a JP2 file. It defines regions of interest (ROI) with names and coordinates, and can also include image referencing information (`irt`) for advanced features. ```xml ``` -------------------------------- ### Create and Destroy Codec Handles in C Source: https://context7.com/uclouvain/openjpeg/llms.txt This C code demonstrates the creation and destruction of codec handles using the OpenJPEG library. opj_create_decompress() and opj_create_compress() are used to initialize decompressor and compressor objects, respectively, for different JPEG 2000 formats. opj_destroy_codec() is essential for freeing allocated resources. ```c #include /* Create a JPEG 2000 decompressor for JP2 format */ opj_codec_t* codec = opj_create_decompress(OPJ_CODEC_JP2); if (!codec) { fprintf(stderr, "Failed to create codec\n"); return -1; } /* Supported codec formats: * OPJ_CODEC_J2K - JPEG 2000 codestream (.j2k, .j2c) * OPJ_CODEC_JP2 - JP2 file format (.jp2) * OPJ_CODEC_JPT - JPT stream (JPIP) */ /* Create a compressor */ opj_codec_t* encoder = opj_create_compress(OPJ_CODEC_JP2); /* Clean up */ opj_destroy_codec(codec); opj_destroy_codec(encoder); ``` -------------------------------- ### Build Unit Tests (CMake) Source: https://github.com/uclouvain/openjpeg/blob/master/src/lib/openjp2/CMakeLists.txt This snippet configures the build of unit tests, specifically `bench_dwt` and `test_sparse_array`, when `BUILD_UNIT_TESTS` is enabled and the system is UNIX-like. It links the necessary libraries, including the OpenJPEG library, the math library (`m`), and threading libraries if configured. ```cmake if(BUILD_UNIT_TESTS AND UNIX) add_executable(bench_dwt bench_dwt.c) if(UNIX) target_link_libraries(bench_dwt m ${OPENJPEG_LIBRARY_NAME}) endif() if(OPJ_USE_THREAD AND Threads_FOUND AND CMAKE_USE_PTHREADS_INIT) target_link_libraries(bench_dwt ${CMAKE_THREAD_LIBS_INIT}) endif(OPJ_USE_THREAD AND Threads_FOUND AND CMAKE_USE_PTHREADS_INIT) add_executable(test_sparse_array test_sparse_array.c) if(UNIX) target_link_libraries(test_sparse_array m ${OPENJPEG_LIBRARY_NAME}) endif() if(OPJ_USE_THREAD AND Threads_FOUND AND CMAKE_USE_PTHREADS_INIT) target_link_libraries(test_sparse_array ${CMAKE_THREAD_LIBS_INIT}) endif(OPJ_USE_THREAD AND Threads_FOUND AND CMAKE_USE_PTHREADS_INIT) endif(BUILD_UNIT_TESTS AND UNIX) ``` -------------------------------- ### Build Include OpenJPEG Executable (CMake) Source: https://github.com/uclouvain/openjpeg/blob/master/tests/CMakeLists.txt Compiles the `include_openjpeg.c` source file into an executable named `include_openjpeg`. This likely serves as an example or test for including and using the OpenJPEG library. ```cmake add_executable(include_openjpeg include_openjpeg.c) ``` -------------------------------- ### Configure Doxygen Documentation (CMake) Source: https://github.com/uclouvain/openjpeg/blob/master/doc/CMakeLists.txt This snippet configures the Doxygen configuration file and main page files using CMake's `configure_file` command. It substitutes variables from CMake into the Doxygen input files and places them in the build directory. It also copies necessary image files. ```cmake find_package(Doxygen) if(DOXYGEN_FOUND) # Configure the doxygen config file with variable from CMake and move it configure_file(${CMAKE_CURRENT_SOURCE_DIR}/Doxyfile.dox.cmake.in ${CMAKE_BINARY_DIR}/doc/Doxyfile-html.dox @ONLY) # Configure the html mainpage file of the doxygen documentation with variable # from CMake and move it configure_file(${CMAKE_CURRENT_SOURCE_DIR}/mainpage.dox.in ${CMAKE_BINARY_DIR}/doc/mainpage.dox @ONLY) configure_file(${CMAKE_CURRENT_SOURCE_DIR}/openjpip.dox.in ${CMAKE_BINARY_DIR}/doc/openjpip.dox @ONLY) # copy png file to make local (binary tree) documentation valid: configure_file(${CMAKE_CURRENT_SOURCE_DIR}/jpip_architect.png ${CMAKE_BINARY_DIR}/doc/html/jpip_architect.png COPYONLY) configure_file(${CMAKE_CURRENT_SOURCE_DIR}/jpip_protocol.png ${CMAKE_BINARY_DIR}/doc/html/jpip_protocol.png COPYONLY) else() message(STATUS "Doxygen not found, we cannot generate the documentation") endif() ``` -------------------------------- ### C: Implement Tile-Based Encoding with OpenJPEG Source: https://context7.com/uclouvain/openjpeg/llms.txt This C code snippet demonstrates how to perform tile-based encoding using the OpenJPEG library. It sets up encoder parameters, defines tile dimensions, creates an image structure, and iterates through tiles, writing each one to the output stream. Dependencies include the openjpeg and string.h libraries. ```c #include #include int encode_with_tiles(const char* output_file, int width, int height) { opj_cparameters_t parameters; opj_codec_t* codec = NULL; opj_stream_t* stream = NULL; opj_image_t* image = NULL; opj_image_cmptparm_t cmptparms[3]; int ret = 0; int tile_width = 256; int tile_height = 256; int num_tiles_x = (width + tile_width - 1) / tile_width; int num_tiles_y = (height + tile_height - 1) / tile_height; /* Setup parameters */ opj_set_default_encoder_parameters(¶meters); parameters.tile_size_on = OPJ_TRUE; parameters.cp_tx0 = 0; parameters.cp_ty0 = 0; parameters.cp_tdx = tile_width; parameters.cp_tdy = tile_height; /* Setup component parameters */ memset(cmptparms, 0, sizeof(cmptparms)); for (int i = 0; i < 3; i++) { cmptparms[i].dx = 1; cmptparms[i].dy = 1; cmptparms[i].w = width; cmptparms[i].h = height; cmptparms[i].prec = 8; cmptparms[i].sgnd = 0; } /* Create image for tile-based encoding */ image = opj_image_tile_create(3, cmptparms, OPJ_CLRSPC_SRGB); if (!image) return -1; image->x0 = 0; image->y0 = 0; image->x1 = width; image->y1 = height; /* Create codec and setup */ codec = opj_create_compress(OPJ_CODEC_JP2); opj_setup_encoder(codec, ¶meters, image); /* Create stream */ stream = opj_stream_create_default_file_stream(output_file, OPJ_STREAM_WRITE); /* Start compression */ opj_start_compress(codec, image, stream); /* Allocate tile data buffer */ size_t tile_size = tile_width * tile_height * 3; /* 3 components */ OPJ_BYTE* tile_data = (OPJ_BYTE*)malloc(tile_size); /* Write tiles */ for (int ty = 0; ty < num_tiles_y; ty++) { for (int tx = 0; tx < num_tiles_x; tx++) { int tile_index = ty * num_tiles_x + tx; /* Fill tile_data with pixel values for this tile */ /* Data format: all R values, then all G values, then all B values */ memset(tile_data, 128, tile_size); /* Example: gray fill */ /* Write tile */ if (!opj_write_tile(codec, tile_index, tile_data, tile_size, stream)) { fprintf(stderr, "Failed to write tile %d\n", tile_index); ret = -1; break; } } if (ret != 0) break; } /* End compression */ opj_end_compress(codec, stream); /* Cleanup */ free(tile_data); opj_stream_destroy(stream); opj_destroy_codec(codec); opj_image_destroy(image); return ret; } ```